@aurora-is-near/intents-connect 7.25.1 → 7.27.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.
|
@@ -217,6 +217,7 @@ const u = (e, t, n) => {
|
|
|
217
217
|
monad: 143,
|
|
218
218
|
plasma: 9745,
|
|
219
219
|
adi: 36900,
|
|
220
|
+
hood: 4663,
|
|
220
221
|
aurora: 1313161554
|
|
221
222
|
}, Rt = new Set(
|
|
222
223
|
Object.keys(re)
|
|
@@ -1607,4 +1608,4 @@ export {
|
|
|
1607
1608
|
zt as y,
|
|
1608
1609
|
Jt as z
|
|
1609
1610
|
};
|
|
1610
|
-
//# sourceMappingURL=recovery-
|
|
1611
|
+
//# sourceMappingURL=recovery-C4NJU6-O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recovery-C4NJU6-O.js","sources":["../../src/types/execution.ts","../../src/types/signing.ts","../../src/errors.ts","../../src/logger.ts","../../src/machine/context.ts","../../src/machine/phases.ts","../../src/machine/machine.ts","../../src/runner/constants.ts","../../src/machine/guards/checks/amountMustExceedFee.ts","../../src/machine/guards/checks/destinationTokenIsTouched.ts","../../src/machine/guards/checks/feeMustBeEstimated.ts","../../src/machine/guards/checks/feeWithinBudget.ts","../../src/chains.ts","../../src/machine/guards/checks/memoPresentForStellar.ts","../../src/machine/guards/checks/mustBeSignedBeforeDeposit.ts","../../src/machine/guards/checks/mustHaveSigningPayload.ts","../../src/machine/guards/checks/noExecutionInFlight.ts","../../src/machine/guards/checks/originNetworkMatches.ts","../../src/machine/guards/checks/publicKeyMatchesStandard.ts","../../src/machine/guards/checks/quoteMustNotHaveMoved.ts","../../src/machine/guards/checks/recipientOnlyOnOutOperation.ts","../../src/machine/guards/checks/solanaStepsAreLegal.ts","../../src/machine/guards/checks/stepShapeIsLegal.ts","../../src/machine/guards/checks/stepsRequiredForRealCreate.ts","../../src/machine/guards/checks/stepsUsePlaceholder.ts","../../src/machine/guards/checks/strategiesAreExclusive.ts","../../src/runner/depositPlan.ts","../../src/runner/transfer.ts","../../src/runner/stages/deposit.ts","../../src/runner/stages/fail.ts","../../src/runner/stages/settle.ts","../../src/signers/standards/encoding.ts","../../src/signers/standards/erc191.ts","../../src/signers/standards/rawEd25519.ts","../../src/signers/standards/nep413.ts","../../src/signers/standards/sep53.ts","../../src/signers/intentsConnect.ts","../../src/runner/stages/signAndSubmit.ts","../../src/runner/quoteAmounts.ts","../../src/runner/stages/validatePreparedExecution.ts","../../src/runner/flows/resume.ts","../../src/runner/flows/retryDeposit.ts","../../src/runner/capture.ts","../../src/runner/stages/cancel.ts","../../src/runner/identity.ts","../../src/runner/planHelpers.ts","../../src/runner/stages/create.ts","../../src/runner/stages/planSteps.ts","../../src/runner/flows/run.ts","../../src/runner/isolated.ts","../../src/runner/flows/preview.ts","../../src/runner/stages/planStepsOnly.ts","../../src/runner/flows/previewSteps.ts","../../src/runner/flows/runSteps.ts","../../src/runner/createExecutionRunner.ts","../../src/recovery.ts"],"sourcesContent":["import type { SigningPayload, SigningStandard } from '@/types/signing';\n\nexport type Chain = string;\n\n/**\n * Which endpoint shape an execution uses.\n *\n * - `bridge-in`: a 1Click quote funds the intermediary, then the steps run.\n * - `steps-only`: no quote — the steps spend what the intermediary already\n * holds (`POST /executions/{wallet}/steps`).\n */\nexport type FlowShape = 'bridge-in' | 'steps-only';\n\n/** How the service created an execution. Optional on the wire. */\nexport type ExecutionMode = 'quote_with_steps' | 'steps_only';\n\nexport type SwapType = 'EXACT_INPUT' | 'EXACT_OUTPUT';\n\nexport type ExecutionType = 'evm' | 'solana';\n\n/**\n * Server-side status. Authoritative, polled, eventually consistent.\n *\n * `EXPIRED` is NOT hard-terminal: a deposit that settles late can revive an\n * execution straight to `OPERATION_PROCESSING`.\n */\nexport type ExecutionStatus =\n | 'CREATED'\n | 'DEPOSIT_PENDING'\n | 'DEPOSIT_PROCESSING'\n | 'OPERATION_PENDING'\n | 'OPERATION_PROCESSING'\n | 'SUCCESS'\n | 'DEPOSIT_FAILED'\n | 'OPERATION_FAILED'\n | 'EXPIRED';\n\nexport const TERMINAL_STATUSES: readonly ExecutionStatus[] = [\n 'SUCCESS',\n 'DEPOSIT_FAILED',\n 'OPERATION_FAILED',\n];\n\n/**\n * Statuses for which the service still holds the per-(intermediary, chain)\n * in-flight lock, so a `dry: false` create would answer 409.\n *\n * `EXPIRED` is excluded: the deadline has passed and a new execution is exactly\n * what the user needs, even though a late deposit could still revive the old one.\n */\nexport const IN_FLIGHT_STATUSES: readonly ExecutionStatus[] = [\n 'CREATED',\n 'DEPOSIT_PENDING',\n 'DEPOSIT_PROCESSING',\n 'OPERATION_PENDING',\n 'OPERATION_PROCESSING',\n];\n\n/**\n * Statuses that still mean \"waiting on the user's funds\": `CREATED` before\n * the signature, `DEPOSIT_PENDING` after it (the /submit response names the\n * same state SIGNED_PENDING_DEPOSIT). Everything later means the watcher has\n * observed the deposit.\n *\n * `EXPIRED` is deliberately excluded: the deadline has passed, so nothing is\n * \"waiting\" — but a late deposit still revives it, which is why `resume()`\n * treats EXPIRED as deposit-needing on top of this set.\n */\nexport const AWAITING_FUNDS_STATUSES: readonly ExecutionStatus[] = [\n 'CREATED',\n 'DEPOSIT_PENDING',\n];\n\n/** Status values `/submit` may answer with, which are not execution statuses. */\nexport type SubmitStatus =\n | 'SIGNED_PENDING_DEPOSIT'\n /** Out-operations only: already OPERATION_PENDING, no deposit needed. */\n | 'SIGNING'\n | ExecutionStatus;\n\n/**\n * A step parameter: an ABI scalar as a string, or a nested array for a tuple /\n * array argument (the API allows up to 6 levels of nesting). Placeholders like\n * `{MIN_AMOUNT_OUT}` are valid anywhere a scalar is.\n */\nexport type StepParameter = string | StepParameter[];\n\n/**\n * The ONLY five keys a step may carry. Any other key — including a differently\n * cased spelling or a duplicate — is rejected with 400.\n */\nexport type Step = {\n /** A contract address, or the `{DEPOSIT_ADDRESS}` placeholder. */\n to: string;\n /** Empty string means a bare value transfer with no calldata. */\n functionSignature: string;\n parameters: StepParameter[];\n /** Atomic amount, or an amount placeholder. */\n value: string;\n /** Passed through untouched by the backend. */\n metadata?: Record<string, unknown>;\n};\n\nexport type SolanaAccountMeta = {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n};\n\nexport type SolanaArg = {\n name: string;\n} & (\n | {\n type:\n | 'u8'\n | 'u16'\n | 'u32'\n | 'u64'\n | 'u128'\n | 'i8'\n | 'i16'\n | 'i32'\n | 'i64';\n value: string | number;\n }\n | { type: 'bool'; value: boolean }\n | { type: 'pubkey' | 'bytes' | 'string'; value: string }\n);\n\nexport type SolanaStep = {\n programId: string;\n /** Hex without 0x. May contain the entire encoded instruction when args is empty. */\n discriminator?: string;\n args: SolanaArg[];\n /** Order is significant; only {INTERMEDIARY} may be a signer. */\n accounts: SolanaAccountMeta[];\n metadata?: Record<string, unknown>;\n};\n\n/** Step remains the EVM alias for existing consumers. */\nexport type ExecutionStep = Step | SolanaStep;\n\nexport type PreparedSteps<TStep extends ExecutionStep = ExecutionStep> = {\n steps: TStep[];\n addressLookupTables?: string[];\n};\n\nexport const MAX_STEPS: Readonly<Record<ExecutionType, number>> = {\n evm: 30,\n solana: 50,\n};\n\nexport const MAX_FUNCTION_SIGNATURE_BYTES = 1024;\n\nexport const STEP_KEYS = [\n 'to',\n 'functionSignature',\n 'parameters',\n 'value',\n 'metadata',\n] as const;\n\n/** Placeholders the backend substitutes server-side. Emit them literally. */\nexport const BACKEND_PLACEHOLDERS = {\n intermediary: '{INTERMEDIARY}',\n minAmountOut: '{MIN_AMOUNT_OUT}',\n depositAddress: '{DEPOSIT_ADDRESS}',\n amountIn: '{AMOUNT_IN}',\n} as const;\n\nexport type QuoteRequest = {\n originAsset: string;\n destinationAsset: string;\n /** Atomic. Denominated in the origin token for EXACT_INPUT, destination for EXACT_OUTPUT. */\n amount: string;\n swapType: SwapType;\n /** Basis points. */\n slippageTolerance: number;\n /** ISO 8601. Drives the deposit-address validity countdown. */\n deadline?: string;\n /** Out-operation only. Sending it on a bridge-in is a 400. */\n recipient?: string;\n};\n\nexport type ExecutionQuote = {\n amount: string;\n /** Deposit THIS for EXACT_OUTPUT. Never recompute it. */\n amountIn: string;\n amountOut: string;\n /** EVM: post-fee after estimation. Solana: gross; subtract details.networkFee. */\n minAmountOut: string;\n depositAddress: string;\n /** Stellar: required on both the transfer and `deposit/submit`. */\n depositMemo: string | null;\n /** ISO 8601. Echoed back from the request, so `resume` can recover it. */\n deadline?: string;\n recipient?: string;\n /** Echoed back from the request — lets `resume` rebuild the deposit leg. */\n originAsset?: string;\n destinationAsset?: string;\n swapType?: SwapType;\n};\n\nexport type ExecutionDetails = {\n intermediaryAddress: string;\n /** Absent means gas estimation FAILED and amounts are still gross. */\n networkFee?: string;\n estimatedTime?: string;\n messageSigned?: boolean;\n messageToSign?: string;\n signingStandard?: SigningStandard;\n payload?: SigningPayload;\n};\n\nexport type Execution = {\n id: string;\n createdAt?: string;\n status: ExecutionStatus;\n quote: ExecutionQuote;\n details: ExecutionDetails;\n /** Your steps plus the service's appended fee-transfer step. */\n steps: ExecutionStep[];\n metadata?: Record<string, unknown>;\n type?: ExecutionType;\n /** Absent on older deployments; `metadata.intentsConnectFlow` is the fallback. */\n executionMode?: ExecutionMode;\n version?: string;\n transaction?: { evmTxHash?: string; solanaTxHash?: string };\n};\n\nexport type Intermediary = {\n originAccount: string;\n originType: 'evm' | 'solana' | 'near' | 'stellar' | 'tron' | 'ton';\n evm: string;\n solana: string | null;\n};\n\n/**\n * How the spendable amount is sized against the fee the service carves.\n *\n * Mutually exclusive by construction: `{MIN_AMOUNT_OUT}` exists to collapse the\n * three-round protocol into one call, so mixing them would mean two steps\n * operate on different amounts.\n */\nexport type FeeStrategy =\n /** One round. The service substitutes the post-fee amount server-side. */\n | { kind: 'placeholder' }\n /** Three rounds. You compute the amount and can show an exact figure first. */\n | {\n kind: 'threeRound';\n /**\n * Portion of the post-fee guarantee left out of the encoded spend to\n * absorb movement before real create. Defaults to 0; integer 0–9999.\n * Callers must account for this reserve in their total slippage budget.\n */\n amountReserveBps?: number;\n };\n","/**\n * Signing standards.\n *\n * Two distinct sets, deliberately:\n *\n * - `SigningStandard` is the WIRE contract — every value the API can put in\n * `details.signingStandard`. It is pinned against the OpenAPI document by\n * `api/generated/conformance.ts`, so a new server-side standard becomes a\n * type error here rather than a runtime surprise.\n * - `SupportedSigningStandard` is the subset this package can actually sign.\n *\n * Keeping them apart makes \"the API asked for a standard we do not implement\" a\n * typed, reachable branch instead of an unreachable `default` case.\n */\nexport type SigningStandard =\n | 'erc191' // EVM secp256k1 — publicKey MUST be omitted (ecrecover)\n | 'tip191' // Tron secp256k1 — not implemented yet\n | 'raw_ed25519' // Solana ed25519 — publicKey required; sign payload bytes\n | 'nep413' // NEAR ed25519 — publicKey required; sign {message,recipient,nonce}\n | 'sep53' // Stellar ed25519 — publicKey required (StrKey-decoded)\n | 'ton_connect'; // TON ed25519 — not implemented yet; needs the tonConnect envelope\n\nexport type SupportedSigningStandard = Extract<\n SigningStandard,\n 'erc191' | 'raw_ed25519' | 'nep413' | 'sep53'\n>;\n\nconst SUPPORTED_SIGNING_STANDARDS: readonly SupportedSigningStandard[] = [\n 'erc191',\n 'raw_ed25519',\n 'nep413',\n 'sep53',\n];\n\n/**\n * Standards whose `/submit` body must carry a `publicKey`: ed25519 cannot\n * recover a key from a signature. Includes `ton_connect` even though signing it\n * is unimplemented — the asymmetry is a property of the curve, not of our\n * coverage.\n */\nexport const ED25519_STANDARDS: readonly SigningStandard[] = [\n 'raw_ed25519',\n 'nep413',\n 'sep53',\n 'ton_connect',\n];\n\nexport const isSupportedSigningStandard = (\n standard: SigningStandard,\n): standard is SupportedSigningStandard =>\n (SUPPORTED_SIGNING_STANDARDS as readonly SigningStandard[]).includes(\n standard,\n );\n\n/** `details.payload` as returned by the API. */\nexport type SigningPayload = {\n standard: SigningStandard;\n /** Sign verbatim for erc191 / sep53. Parse for nep413. */\n payload_json: string;\n /** Base64. Decode to bytes and sign those for raw_ed25519. */\n payload_bytes_base64: string;\n};\n\n/**\n * The wallet-chosen envelope a TON signature must be submitted with: the wallet\n * folds these into the signed digest, so the backend needs them to rebuild it.\n */\nexport type TonConnectEnvelope = {\n domain: string;\n timestamp: number;\n address: string;\n};\n\n/**\n * NEP-413 mixes `recipient` and `nonce` into the signed digest, so a DELETE\n * signed with nep413 must repeat them on the wire for the backend to rebuild\n * the exact bytes the wallet signed. Omitting the block is a 400.\n */\nexport type Nep413Envelope = {\n recipient: string;\n /** Base64-encoded 32 bytes — the same nonce handed to the wallet as raw bytes. */\n nonce: string;\n};\n\n/** What `/submit` and `DELETE` accept. */\nexport type SignatureEnvelope = {\n /** `secp256k1:<bs58>` or `ed25519:<bs58>` */\n signature: string;\n /** ed25519 standards only — omitted for secp256k1. */\n publicKey?: string;\n /** `ton_connect` only. */\n tonConnect?: TonConnectEnvelope;\n};\n\n/**\n * The DELETE body only: `/submit` does not accept the nep413 block (the create\n * payload already carries recipient and nonce), while a nep413 DELETE is a 400\n * without it.\n */\nexport type DeleteSignatureEnvelope = SignatureEnvelope & {\n /** nep413 only — the client-generated envelope. */\n nep413?: Nep413Envelope;\n};\n","/** Base class for every error this package throws. */\nexport class IntentsConnectError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = 'IntentsConnectError';\n\n if (options?.cause !== undefined) {\n this.cause = options.cause;\n }\n }\n}\n\n/**\n * Normalises an arbitrary thrown value into an `Error` with a readable\n * message.\n *\n * Needed because wallet providers routinely reject with PLAIN OBJECTS rather\n * than `Error` instances — an EIP-1193 rejection travels as\n * `{ code: 4001, message: 'User rejected the request.' }`, and some connectors\n * nest it one level down as `{ error: { code, message } }`. `String(...)` on\n * those renders \"[object Object]\", which is what a UI would end up showing.\n * The original value is preserved on `cause`.\n */\nexport const toError = (value: unknown): Error => {\n if (value instanceof Error) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null) {\n const outer = value as {\n message?: unknown;\n code?: unknown;\n error?: unknown;\n };\n\n const inner =\n typeof outer.error === 'object' && outer.error !== null\n ? (outer.error as { message?: unknown; code?: unknown })\n : undefined;\n\n const messages = [outer.message, inner?.message];\n const message = messages.find(\n (candidate): candidate is string => typeof candidate === 'string',\n );\n\n const code = outer.code ?? inner?.code;\n\n if (message) {\n return new IntentsConnectError(\n code !== undefined ? `${message} (code ${String(code)})` : message,\n { cause: value },\n );\n }\n\n try {\n return new IntentsConnectError(JSON.stringify(value), { cause: value });\n } catch {\n // Circular — fall through to String().\n }\n }\n\n return new IntentsConnectError(String(value), { cause: value });\n};\n\n/**\n * How wallets word a rejection when they report no code. Kept in sync with the\n * widget's `isUserDeniedSigning`: Freighter says \"User declined access\", and\n * several connectors report a dismissed popup as \"user closed\".\n */\nconst USER_REJECTION_PROSE =\n /user (rejected|denied|cancell?ed|declined|closed)/i;\n\nconst saysRejected = (value: unknown): boolean =>\n typeof value === 'string' && USER_REJECTION_PROSE.test(value);\n\n/**\n * Whether a thrown value is the user declining a wallet prompt.\n *\n * EIP-1193 names it `userRejectedRequest` = 4001, and the major Solana wallets\n * reuse the same code. The code may sit on the value itself, nested one level\n * (`{ error: { code } }`), or on a wrapping Error's `cause`; older providers\n * only say it in prose, hence the message fallback.\n *\n * The prose fallback reads the nested value too, not just `message`: a wallet\n * that reports a rejection IN-BAND (Freighter's `{ error }`) reaches\n * `toError` as a bare string, so it arrives here as a `cause` carrying the\n * only evidence there is.\n */\nexport const isUserRejection = (value: unknown): boolean => {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const outer = value as {\n code?: unknown;\n message?: unknown;\n error?: unknown;\n cause?: unknown;\n };\n\n if (outer.code === 4001) {\n return true;\n }\n\n const inner = outer.error ?? outer.cause;\n const innerObject =\n inner && typeof inner === 'object'\n ? (inner as { code?: unknown; message?: unknown })\n : undefined;\n\n if (innerObject?.code === 4001) {\n return true;\n }\n\n return (\n saysRejected(outer.message) ||\n saysRejected(inner) ||\n saysRejected(innerObject?.message)\n );\n};\n\n/** A non-2xx response from the Intents Connect API. */\nexport class IntentsConnectApiError extends IntentsConnectError {\n constructor(\n message: string,\n readonly status: number,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = 'IntentsConnectApiError';\n }\n\n /**\n * A `dry: false` create is already live for this (intermediary, chain). The\n * caller must wait for a terminal status or delete the open execution.\n */\n get isExecutionInFlight(): boolean {\n return this.status === 409;\n }\n}\n\n/**\n * The execution was cancelled through `runner.cancel()`. Distinct from a guard\n * violation: nothing went wrong, the caller asked to stop.\n */\nexport class ExecutionCancelledError extends IntentsConnectError {\n constructor(readonly executionId: string) {\n super(`execution ${executionId} was cancelled`);\n this.name = 'ExecutionCancelledError';\n }\n}\n\n/**\n * The runner was disposed (typically because the bound wallet or account\n * changed) while an execution was still in flight. The execution itself is\n * untouched server-side — reattach with `resume()` from a runner bound to the\n * owning wallet.\n */\nexport class RunnerDisposedError extends IntentsConnectError {\n constructor(readonly executionId?: string) {\n super(\n 'the runner was disposed while an execution was in flight — resume() it from a runner bound to the owning wallet',\n );\n this.name = 'RunnerDisposedError';\n }\n}\n\n/**\n * Polling stopped without observing a terminal status. NOT a verdict on the\n * execution — it is still live server-side and may yet succeed. Reattach with\n * `resume(executionId)` to keep watching it.\n */\nexport class ExecutionPollTimeoutError extends IntentsConnectError {\n constructor(\n readonly executionId: string,\n detail: string,\n ) {\n super(\n `${detail} — the execution is still live server-side; call resume('${executionId}') to keep watching it`,\n );\n this.name = 'ExecutionPollTimeoutError';\n }\n}\n\n/**\n * The deposit transfer was rejected or failed in the wallet. The execution is\n * still valid and signed server-side; call `runner.retryDeposit()` to prompt\n * the transfer again.\n */\nexport class DepositTransferError extends IntentsConnectError {\n constructor(\n readonly executionId: string,\n options?: { cause?: unknown },\n ) {\n super(\n `the deposit transfer for execution ${executionId} was not completed — call retryDeposit() to prompt it again`,\n options,\n );\n this.name = 'DepositTransferError';\n }\n}\n\n/**\n * A precondition of the Intents Connect protocol was violated. Every code\n * corresponds to one named guard under `machine/guards/checks`.\n */\nexport type GuardCode =\n | 'STEPS_REQUIRED'\n | 'FEE_NOT_ESTIMATED'\n | 'FEE_EXCEEDS_AMOUNT'\n | 'QUOTE_MOVED'\n | 'ILLEGAL_STEP_SHAPE'\n | 'DESTINATION_TOKEN_UNTOUCHED'\n | 'RECIPIENT_NOT_ALLOWED'\n | 'STRATEGY_CONFLICT'\n | 'EXECUTION_IN_FLIGHT'\n | 'NO_INTERMEDIARY'\n | 'NETWORK_MISMATCH'\n | 'MEMO_REQUIRED'\n | 'DEPOSIT_BEFORE_SIGNATURE'\n | 'PUBLIC_KEY_MISMATCH'\n | 'NO_SIGNING_PAYLOAD'\n | 'UNSUPPORTED_SIGNING_STANDARD'\n | 'NO_TRANSFER_IMPLEMENTATION'\n | 'WALLET_NOT_CONNECTED';\n\nexport type GuardMeta = {\n /** Set by EXECUTION_IN_FLIGHT: the execution holding the lock. */\n executionId?: string;\n};\n\nexport class GuardError extends IntentsConnectError {\n constructor(\n readonly code: GuardCode,\n message: string,\n /** Structured context, so UIs can act on the error instead of parsing prose. */\n readonly meta: GuardMeta = {},\n ) {\n super(message);\n this.name = 'GuardError';\n }\n}\n\nexport const failGuard = (\n code: GuardCode,\n message: string,\n meta?: GuardMeta,\n): never => {\n throw new GuardError(code, message, meta);\n};\n","export type Logger = {\n debug: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n};\n\nconst PREFIX = '[INTENTS-CONNECT]';\n\n/* eslint-disable no-console */\nexport const defaultLogger: Logger = {\n debug: () => {},\n warn: (message, ...args) => console.warn(`${PREFIX} ${message}`, ...args),\n error: (message, ...args) => console.error(`${PREFIX} ${message}`, ...args),\n};\n/* eslint-enable no-console */\n\nexport const noopLogger: Logger = {\n debug: () => {},\n warn: () => {},\n error: () => {},\n};\n","import type {\n Execution,\n ExecutionStatus,\n Intermediary,\n} from '@/types/execution';\n\n/**\n * Declared as a type alias rather than an interface so it keeps an implicit\n * index signature — some store helpers constrain context to\n * `Record<string, unknown>`, which interfaces do not satisfy.\n */\nexport type Context = {\n intermediary?: Intermediary;\n\n executionId?: string;\n execution?: Execution;\n status?: ExecutionStatus;\n\n /** Present once a fee has been measured (threeRound) or reported. */\n networkFee?: string;\n /** The amount the steps may spend, post-fee. */\n spendable?: string;\n /** threeRound only: the amount actually baked into the created steps. */\n bakedAmount?: string;\n\n /** Only ever set after the signature is submitted. */\n depositAddress?: string;\n depositMemo?: string | null;\n /** ISO — the deposit-address validity deadline. */\n deadline?: string;\n depositTxHash?: string;\n\n hasSubmittedSignature: boolean;\n\n /**\n * A `delete_execution` signature / request is in flight.\n *\n * Deliberately NOT a phase: `cancel()` can be invoked from almost any point\n * in the lifecycle — including terminal phases, where a transition would be\n * refused — so cancelling is orthogonal to where the execution itself got\n * to. A UI needs it to say \"sign to cancel\" rather than mislabelling the\n * prompt with the phase it interrupted (e.g. \"Awaiting signature\").\n */\n isCancelling: boolean;\n\n error?: Error;\n};\n\nexport const createInitialContext = (): Context => ({\n hasSubmittedSignature: false,\n isCancelling: false,\n});\n","/**\n * Client-side phases — what a UI renders.\n *\n * Distinct from `ExecutionStatus`, which is the server's view and only exists\n * from `creating` onward.\n */\nexport type Phase =\n | 'idle'\n /** GET /intermediary — deterministic, cached per wallet. */\n | 'resolving-identity'\n /** Build steps and size the amount against the fee (0 or 2 dry rounds). */\n | 'planning'\n /** POST create, dry: false. */\n | 'creating'\n /** Waiting on the wallet prompt. */\n | 'awaiting-signature'\n /** POST /submit. */\n | 'submitting'\n /** User sends funds — wallet transfer or QR / exchange. */\n | 'awaiting-deposit'\n /** Polling to a terminal status. */\n | 'settling'\n | 'success'\n | 'failed'\n | 'expired'\n | 'cancelled';\n\n/**\n * Legal transitions.\n *\n * Two entries carry non-obvious behaviour:\n *\n * - `submitting` FORKS. v1 is bridge-in so it always needs a deposit, but the\n * direct edge to `settling` is modelled now because out-operations answer\n * `SIGNING` from /submit and skip the deposit phase entirely.\n * - `expired` re-enters `settling`. `EXPIRED` looks terminal but is not: a\n * deposit that settles late revives an execution straight to\n * `OPERATION_PROCESSING`.\n * - `awaiting-deposit` and `expired` go DIRECTLY to `success` (and `failed`):\n * a terminal status can be observed on the very poll that would otherwise\n * have flipped to `settling` first, and hopping through an intermediate\n * phase would emit a `settling` the execution never meaningfully occupied.\n * - `idle` may go directly to `awaiting-signature`, `awaiting-deposit` or\n * `settling`. Those are `resume()` re-entry points: identity and planning\n * already happened in an earlier session, so replaying them would emit events\n * for work this runner never did. Which one it enters depends on how far the\n * execution actually got.\n * - `idle` may also go to `failed`, because `run()` and `resume()` can both fail\n * on their very first call (an unknown execution id, a disconnected wallet)\n * and must still record the error rather than silently staying idle.\n * - EVERY non-terminal phase may go to `cancelled`. `cancel()` is the user's\n * escape hatch from a stuck execution and can be invoked at any point after\n * an execution id exists — refusing the transition from any live phase would\n * leave the machine claiming an execution that was already deleted.\n */\nexport const PHASE_TRANSITIONS: Readonly<Record<Phase, readonly Phase[]>> = {\n idle: [\n 'resolving-identity',\n 'awaiting-signature',\n 'awaiting-deposit',\n 'settling',\n 'failed',\n 'cancelled',\n ],\n 'resolving-identity': ['planning', 'failed', 'cancelled'],\n planning: ['creating', 'failed', 'cancelled'],\n creating: ['awaiting-signature', 'failed', 'cancelled'],\n 'awaiting-signature': ['submitting', 'failed', 'cancelled'],\n submitting: ['awaiting-deposit', 'settling', 'failed', 'cancelled'],\n 'awaiting-deposit': ['settling', 'success', 'expired', 'cancelled', 'failed'],\n settling: ['success', 'failed', 'expired', 'cancelled'],\n expired: ['settling', 'success', 'failed', 'cancelled'],\n success: [],\n failed: [],\n cancelled: [],\n};\n\nexport const TERMINAL_PHASES: readonly Phase[] = [\n 'success',\n 'failed',\n 'cancelled',\n];\n\nexport const isTerminalPhase = (phase: Phase): boolean =>\n TERMINAL_PHASES.includes(phase);\n\n/**\n * Phases in which a flow is (or may still be) driving the execution, so\n * `run()` / `resume()` / `retryDeposit()` would refuse re-entry.\n *\n * DERIVED from the taxonomy rather than listed by hand, and deliberately\n * defined here rather than in the React binding: `expired` keeps polling for\n * a late deposit (see the transition table above), so a UI that treated it as\n * idle would re-enable its submit control for a click that can only fail with\n * EXECUTION_IN_FLIGHT. A new intermediate phase is in-flight by construction.\n *\n * NOT sufficient on its own: `awaiting-deposit` is also where a rejected\n * transfer PARKS with nothing running. Use {@link isInFlightPhase} together\n * with the absence of a recorded error — which is exactly what `useExecution`\n * exposes as `isBusy`.\n */\nexport const IN_FLIGHT_PHASES: readonly Phase[] = (\n Object.keys(PHASE_TRANSITIONS) as Phase[]\n).filter((phase) => phase !== 'idle' && !isTerminalPhase(phase));\n\nexport const isInFlightPhase = (phase: Phase): boolean =>\n IN_FLIGHT_PHASES.includes(phase);\n","import { proxy } from 'valtio/vanilla';\n\nimport { defaultLogger, type Logger } from '@/logger';\nimport { type Context, createInitialContext } from '@/machine/context';\nimport { type Phase, PHASE_TRANSITIONS } from '@/machine/phases';\n\n/** The valtio store a framework binding subscribes to. */\nexport type ExecutionMachineStore = {\n state: Phase;\n context: Context;\n};\n\nexport type ExecutionMachine = {\n readonly current: Phase;\n readonly context: Context;\n getStore: () => ExecutionMachineStore;\n canMoveTo: (phase: Phase) => boolean;\n /** Returns whether it moved — an illegal transition is refused. */\n moveTo: (phase: Phase) => boolean;\n /**\n * Returns to `idle` with a fresh context. Deliberately bypasses the\n * transition table: it is how a runner is made reusable after a terminal\n * phase, which by design has no outgoing edges.\n */\n reset: () => void;\n};\n\n/**\n * A FACTORY, deliberately — unlike the widget, which exports a module-level\n * singleton machine.\n *\n * Two reasons: several executions may be in flight in one app (deposit while a\n * previous one settles), and a module-level valtio store leaks state across\n * requests under SSR.\n *\n * Built on `valtio/vanilla` rather than `valtio-fsm`. `valtio-fsm` imports\n * valtio's ROOT entry, which re-exports `valtio/react` and therefore requires\n * `react` to be installed — so importing this \"headless\" package in Node or a\n * worker failed with ERR_MODULE_NOT_FOUND. `valtio/vanilla` pulls only\n * `proxy-compare`. Only five members of `valtio-fsm` were ever used, so the\n * transitions table below replaces it outright.\n */\nexport const createExecutionMachine = (): ExecutionMachine => {\n const store = proxy<ExecutionMachineStore>({\n state: 'idle',\n context: createInitialContext(),\n });\n\n const machine: ExecutionMachine = {\n get current() {\n return store.state;\n },\n get context() {\n return store.context;\n },\n getStore: () => store,\n canMoveTo: (phase) => PHASE_TRANSITIONS[store.state].includes(phase),\n moveTo: (phase) => {\n if (!machine.canMoveTo(phase)) {\n return false;\n }\n\n store.state = phase;\n\n return true;\n },\n reset: () => {\n store.state = 'idle';\n store.context = createInitialContext();\n },\n };\n\n return machine;\n};\n\nexport type MoveToOptions = {\n logger?: Logger;\n onMoved?: (phase: Phase) => void;\n};\n\n/**\n * Guarded transition. Mirrors `moveTo` in the widget's machine: an illegal\n * transition is refused and logged rather than throwing, so a stray event\n * cannot corrupt a live execution.\n *\n * Returns whether the move happened.\n */\nexport const moveTo = (\n machine: ExecutionMachine,\n phase: Phase,\n { logger = defaultLogger, onMoved }: MoveToOptions = {},\n): boolean => {\n if (machine.current === phase) {\n return true;\n }\n\n if (!machine.moveTo(phase)) {\n logger.error(\n `invalid transition requested (from ${machine.current} to ${phase})`,\n );\n\n return false;\n }\n\n onMoved?.(phase);\n\n return true;\n};\n","import type { FeeStrategy } from '@/types/execution';\n\nexport const DEFAULT_POLL_INTERVAL_MS = 3_000;\nexport const DEFAULT_MAX_POLL_ATTEMPTS = 240;\nexport const DEFAULT_FEE_STRATEGY: FeeStrategy = { kind: 'placeholder' };\n/** Applied when the caller supplies no `quote.deadline` — the API requires one. */\nexport const DEFAULT_QUOTE_DEADLINE_MS = 10 * 60_000;\n/**\n * How long past `quote.deadline` the deposit wait keeps polling before the\n * regular attempt budget takes over — covers clock skew and a deposit sent at\n * the last second that the watcher has not observed yet.\n */\nexport const DEPOSIT_DEADLINE_GRACE_MS = 5 * 60_000;\n/**\n * Transient poll failures tolerated in a row. A single network blip must not\n * report a live execution as failed; a persistently unreachable API must.\n */\nexport const MAX_CONSECUTIVE_POLL_ERRORS = 5;\n/**\n * While holding for user funds (QR / exchange deposits) the poll interval\n * grows by this factor per poll, capped below — the hold spans the quote\n * deadline plus grace (~15 minutes by default), and detection latency during\n * a multi-minute exchange transfer is irrelevant. The interval snaps back to\n * `pollIntervalMs` the moment the hold ends.\n */\nexport const HOLDING_POLL_BACKOFF_FACTOR = 1.5;\nexport const MAX_HOLDING_POLL_INTERVAL_MS = 30_000;\n/**\n * How long a new flow waits for a CANCELLED one to release the flow lock\n * before refusing. The cancelled flow usually unwinds in a few microtask hops,\n * but one parked on an open wallet prompt only settles when the user dismisses\n * it — and nothing can abort that from here, so the wait must be bounded.\n */\nexport const DOOMED_FLOW_SETTLE_TIMEOUT_MS = 10_000;\n/** How long a `previewSteps()` snapshot stays committable by default. */\nexport const DEFAULT_PREVIEW_TTL_MS = 30_000;\n","import { failGuard } from '@/errors';\n\n/** The bridged amount must be able to pay for the batch it funds. */\nexport const amountMustExceedFee = (\n grossAmount: string,\n networkFee: string,\n) => {\n if (BigInt(grossAmount) - BigInt(networkFee) <= 0n) {\n failGuard(\n 'FEE_EXCEEDS_AMOUNT',\n `network fee (${networkFee}) exceeds the delivered amount (${grossAmount})`,\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport type { Step } from '@/types/execution';\n\n/**\n * At least one step must call the destination token contract.\n *\n * The network fee is collected in the destination token via a fee-transfer step\n * the backend appends, so a step set that never engages that token is rejected.\n * Native destinations are exempt — the fee is taken in native value.\n *\n * When the real steps genuinely never touch the payout token, satisfy this by\n * appending a zero-value transfer of it to the intermediary.\n */\nexport const destinationTokenIsTouched = (\n steps: Step[],\n destinationTokenAddress?: string,\n) => {\n if (!destinationTokenAddress) {\n return;\n }\n\n const target = destinationTokenAddress.toLowerCase();\n const touched = steps.some((step) => step.to.toLowerCase() === target);\n\n if (!touched) {\n failGuard(\n 'DESTINATION_TOKEN_UNTOUCHED',\n `steps must include at least one call to destination token ${destinationTokenAddress}`,\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport type { Execution } from '@/types/execution';\n\n/**\n * An absent `details.networkFee` means gas estimation failed, so nothing was\n * carved and the response amounts are still GROSS. Copying them forward bakes\n * an amount the batch cannot cover once the fee step is appended.\n *\n * The correct response is to retry the round, never to proceed.\n */\nexport const feeMustBeEstimated = (execution: Execution): string => {\n const fee = execution.details.networkFee;\n\n if (typeof fee !== 'string' || !/^[0-9]+$/.test(fee)) {\n return failGuard(\n 'FEE_NOT_ESTIMATED',\n 'no details.networkFee returned — gas estimation failed; retry the round',\n );\n }\n\n return fee;\n};\n","import { failGuard } from '@/errors';\n\n/**\n * Steps-only executions: the fee measured by the dry round is what the\n * spendable amount was sized against (or what the caller capped it at). A\n * real create reporting MORE would either overdraw the transferred token or\n * eat the whole swap output, so it must not be signed.\n *\n * An equal or lower fee is fine — the difference stays at the intermediary.\n */\nexport const feeWithinBudget = (networkFee: string, budget: string) => {\n if (BigInt(networkFee) > BigInt(budget)) {\n failGuard(\n 'FEE_EXCEEDS_AMOUNT',\n `network fee (${networkFee}) exceeds the budget the steps were sized for (${budget})`,\n );\n }\n};\n","/**\n * Chain-family routing. Mirrors `packages/intents-swap-widget/src/utils/chains`\n * but carries only what deposit routing needs — no chain SDKs.\n */\n\n/**\n * Numeric EVM chain ids. Used by `resume()` to rebuild a deposit transfer from\n * an execution alone — the EVM transfer path refuses to run without a target\n * chain id. Mirrors the widget's `EVM_CHAIN_IDS_MAP`.\n *\n * This record is the single registry of known EVM chains: `EVM_CHAINS` is\n * derived from its keys, so a chain can never be \"EVM\" for routing yet missing\n * its id for resume.\n */\nexport const EVM_CHAIN_IDS: Readonly<Record<string, number>> = {\n eth: 1,\n arb: 42161,\n base: 8453,\n bsc: 56,\n op: 10,\n pol: 137,\n avax: 43114,\n scroll: 534352,\n gnosis: 100,\n xlayer: 196,\n bera: 80094,\n monad: 143,\n plasma: 9745,\n adi: 36900,\n hood: 4663,\n aurora: 1313161554,\n};\n\nexport const EVM_CHAINS: ReadonlySet<string> = new Set(\n Object.keys(EVM_CHAIN_IDS),\n);\n\n/**\n * Chains whose shared deposit address attributes incoming funds by memo —\n * a deposit without one is unattributable and effectively lost.\n */\nexport const MEMO_MODE_CHAINS = new Set(['stellar']);\n\n/**\n * The chain a wallet's signing standard implies, for executions that do not\n * name their origin (`quote.originAsset` absent or not a bridged `*.omft.near`\n * form). Lives here, next to `MEMO_MODE_CHAINS`, on purpose: the memo guard\n * downstream fails OPEN for any wallet standard this map misses, so a new\n * memo-mode chain must land in both registries in the same edit.\n */\nexport const SIGNING_STANDARD_CHAINS: Readonly<Record<string, string>> = {\n sep53: 'stellar',\n};\n\n/**\n * Signing standards whose origin provably cannot be a memo-mode chain, so the\n * memo guard may be skipped when the origin chain itself is unknown.\n *\n * Deliberately the SAFE list rather than the unsafe one, so the default is to\n * fail CLOSED: a standard nobody has classified here — a new one, or\n * `ton_connect`, whose chain attributes deposits by comment exactly like\n * Stellar — must not slip past the guard just because the inference above\n * came back empty. `sep53` is absent because it resolves to a chain outright.\n */\nexport const MEMO_FREE_SIGNING_STANDARDS: ReadonlySet<string> = new Set([\n 'erc191',\n 'raw_ed25519',\n 'nep413',\n]);\n\n/**\n * Chains whose create body must carry `publicKey` — per the API contract, a\n * TON address cannot yield its public key, so `/execution` needs it up front\n * (every other ed25519 origin supplies it at `/submit` instead).\n */\nexport const PUBLIC_KEY_REQUIRED_CHAINS = new Set(['ton']);\n\nexport type ChainFamily = 'evm' | 'sol' | 'stellar' | 'near';\n\nconst OMFT_SUFFIX = '.omft.near';\n\n/**\n * Decodes the origin chain and token address baked into a bridged asset id:\n * `nep141:gnosis-0x2a22….omft.near` → `{ chain: 'gnosis', tokenAddress: '0x2a22…' }`,\n * `nep141:base.omft.near` → `{ chain: 'base' }` (the chain's native asset).\n *\n * Returns `undefined` for anything that is not an `*.omft.near` bridged form\n * (NEAR-native nep141 tokens, nep245 multi-tokens) — callers must treat that\n * as \"origin unknown\", not as an error.\n */\nexport const parseOriginAsset = (\n assetId: string,\n): { chain: string; tokenAddress?: string } | undefined => {\n const [, rest] = assetId.split(':');\n\n if (!rest?.endsWith(OMFT_SUFFIX)) {\n return undefined;\n }\n\n const body = rest.slice(0, -OMFT_SUFFIX.length);\n // Chain slugs never contain a dash, so the first one separates the slug\n // from the token address.\n const dash = body.indexOf('-');\n\n if (dash === -1) {\n return body ? { chain: body } : undefined;\n }\n\n const chain = body.slice(0, dash);\n const tokenAddress = body.slice(dash + 1);\n\n return chain && tokenAddress ? { chain, tokenAddress } : undefined;\n};\n\nexport const isEvmChain = (chain: string): boolean => EVM_CHAINS.has(chain);\n\nexport const getChainFamily = (chain: string): ChainFamily | undefined => {\n if (isEvmChain(chain)) {\n return 'evm';\n }\n\n if (chain === 'sol') {\n return 'sol';\n }\n\n if (chain === 'stellar') {\n return 'stellar';\n }\n\n if (chain === 'near') {\n return 'near';\n }\n\n return undefined;\n};\n","import { MEMO_FREE_SIGNING_STANDARDS, MEMO_MODE_CHAINS } from '@/chains';\nimport { failGuard } from '@/errors';\n\n/**\n * Stellar 1Click uses a SHARED deposit address, so the per-quote memo is the\n * only thing attributing incoming funds to this execution. It must appear on\n * the payment AND on `deposit/submit` — omitting it on either loses the deposit.\n *\n * Fails CLOSED when the origin chain is unknown AND no memo is present. The\n * caller's inference is lossy (an execution need not echo `quote.originAsset`,\n * and only some wallet standards name their chain), and treating \"cannot tell\"\n * as \"not memo mode\" is exactly how a memo-less deposit reaches the shared\n * address. With the origin unresolved, only a present memo or a signing\n * standard that provably cannot originate on a memo-mode chain\n * (`MEMO_FREE_SIGNING_STANDARDS`) may pass.\n */\nexport const memoPresentForStellar = (\n originChain: string | undefined,\n memo?: string | null,\n signingStandard?: string,\n) => {\n if (originChain === undefined) {\n // A memo that IS present is safe whatever the chain turns out to be —\n // this guard only ever catches a MISSING one, so refusing here would\n // block a perfectly fundable deposit.\n if (memo) {\n return;\n }\n\n if (signingStandard && MEMO_FREE_SIGNING_STANDARDS.has(signingStandard)) {\n return;\n }\n\n return failGuard(\n 'MEMO_REQUIRED',\n `cannot determine the origin chain of this deposit${\n signingStandard ? ` (signing standard: ${signingStandard})` : ''\n }, so a memo requirement cannot be ruled out — pass the origin chain, or deposit through a plan that names it`,\n );\n }\n\n if (MEMO_MODE_CHAINS.has(originChain) && !memo) {\n failGuard(\n 'MEMO_REQUIRED',\n 'a Stellar deposit requires quote.depositMemo on both the transfer and deposit/submit',\n );\n }\n};\n","import { failGuard } from '@/errors';\n\n/**\n * Signing happens BEFORE the deposit: the service holds a pre-signed batch and\n * fires it the moment the bridge settles.\n *\n * So a deposit address must never reach the user — as a QR code or otherwise —\n * until the signature is submitted, or funds can arrive with no batch to fire.\n */\nexport const mustBeSignedBeforeDeposit = (hasSubmittedSignature: boolean) => {\n if (!hasSubmittedSignature) {\n failGuard(\n 'DEPOSIT_BEFORE_SIGNATURE',\n 'refusing to expose a deposit address before the intent signature is submitted',\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport type { Execution } from '@/types/execution';\nimport type { SigningPayload, SigningStandard } from '@/types/signing';\n\n/** A created execution without a signing payload cannot be progressed. */\nexport const mustHaveSigningPayload = (\n execution: Execution,\n): { payload: SigningPayload; standard: SigningStandard } => {\n const { payload, signingStandard } = execution.details;\n\n if (!payload || !signingStandard) {\n return failGuard(\n 'NO_SIGNING_PAYLOAD',\n 'execution returned no signing payload — fee estimation likely failed',\n );\n }\n\n return { payload, standard: signingStandard };\n};\n","import { failGuard } from '@/errors';\nimport type { Execution } from '@/types/execution';\n\n/**\n * A `dry: false` create takes an in-flight lock per (intermediary, chain); a\n * second one answers 409. Checking first turns that into an actionable error\n * naming the execution to wait for or cancel.\n */\nexport const noExecutionInFlight = (openExecutions: Execution[]) => {\n const [open] = openExecutions;\n\n if (open) {\n failGuard(\n 'EXECUTION_IN_FLIGHT',\n `execution ${open.id} is already in progress — resume it, cancel it, or wait for it to reach a terminal status`,\n { executionId: open.id },\n );\n }\n};\n","import { failGuard } from '@/errors';\n\n/**\n * EVM origins only: the wallet must be on the origin chain before it can send\n * the deposit. Skipped when the connector exposes no chain id.\n */\nexport const originNetworkMatches = async (\n getChainId: (() => Promise<number>) | undefined,\n expectedChainId: number | null | undefined,\n) => {\n if (!getChainId || expectedChainId == null) {\n return;\n }\n\n const actual = await getChainId();\n\n if (actual !== expectedChainId) {\n failGuard(\n 'NETWORK_MISMATCH',\n `wallet is on chain ${actual} but the origin requires chain ${expectedChainId}`,\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport { ED25519_STANDARDS, type SigningStandard } from '@/types/signing';\n\n/**\n * ed25519 cannot recover a public key from a signature, so the verifier needs\n * one. secp256k1 can (`ecrecover`), so sending one is rejected. Enforcing the\n * asymmetry here turns a confusing 400 into a local error.\n */\nexport const publicKeyMatchesStandard = (\n standard: SigningStandard,\n publicKey?: string,\n) => {\n const requiresPublicKey = ED25519_STANDARDS.includes(standard);\n\n if (requiresPublicKey && !publicKey) {\n failGuard(\n 'PUBLIC_KEY_MISMATCH',\n `${standard} requires a publicKey — ed25519 keys are not recoverable from a signature`,\n );\n }\n\n if (!requiresPublicKey && publicKey) {\n failGuard(\n 'PUBLIC_KEY_MISMATCH',\n `${standard} must omit publicKey — the signer is recovered via ecrecover`,\n );\n }\n};\n","import { failGuard } from '@/errors';\n\n/**\n * Three-round flow only: the quote can move between the measuring round and the\n * create. If the service now guarantees LESS than the amount baked into the\n * steps, the batch cannot cover `spend + fee` and must not be signed.\n *\n * A higher guarantee is fine — the surplus simply stays at the intermediary.\n */\nexport const quoteMustNotHaveMoved = (\n bakedAmount: string,\n returnedMinAmountOut: string,\n) => {\n if (BigInt(returnedMinAmountOut) < BigInt(bakedAmount)) {\n failGuard(\n 'QUOTE_MOVED',\n `quote moved: steps baked ${bakedAmount} but the service now guarantees ${returnedMinAmountOut}`,\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport type { FlowShape } from '@/types/execution';\n\n/**\n * `quote.recipient` is out-operation only. On a bridge-in the recipient is\n * always the intermediary, and sending one is a 400.\n *\n * v1 implements `bridge-in` only, so any recipient is rejected. The `flow`\n * argument is threaded through now so that adding `out-operation` to\n * `FlowShape` turns this into a real branch rather than a signature change at\n * every call site.\n */\nexport const recipientOnlyOnOutOperation = (\n flow: FlowShape,\n recipient?: string,\n) => {\n if (recipient && flow === 'bridge-in') {\n failGuard(\n 'RECIPIENT_NOT_ALLOWED',\n 'quote.recipient is only valid for out-operations',\n );\n }\n};\n","import { base58 } from '@scure/base';\nimport { failGuard } from '@/errors';\nimport {\n BACKEND_PLACEHOLDERS,\n type SolanaArg,\n type SolanaStep,\n} from '@/types/execution';\n\nconst hex = /^(?:[0-9a-fA-F]{2})*$/;\nconst { intermediary } = BACKEND_PLACEHOLDERS;\n\nconst legal = (condition: boolean, message: string) => {\n if (!condition) {\n failGuard('ILLEGAL_STEP_SHAPE', message);\n }\n};\n\nconst isAddress = (value: unknown): value is string => {\n if (typeof value !== 'string' || value.length < 32 || value.length > 44) {\n return false;\n }\n\n try {\n return base58.decode(value).length === 32;\n } catch {\n return false;\n }\n};\n\nconst keysAreLegal = (value: object, keys: string[]) =>\n legal(\n Object.keys(value).every((key) => keys.includes(key)),\n 'Unknown Solana instruction field',\n );\n\nconst validateArg = (arg: SolanaArg) => {\n legal(!!arg && typeof arg === 'object', 'Invalid Solana argument');\n keysAreLegal(arg, ['name', 'type', 'value']);\n legal(typeof arg.name === 'string', 'Solana arguments require a name');\n\n const integer = /^(u8|u16|u32|u64|u128|i8|i16|i32|i64)$/.exec(arg.type);\n\n if (integer) {\n if (arg.type === 'u64' && arg.value === BACKEND_PLACEHOLDERS.minAmountOut) {\n return;\n }\n\n legal(\n (typeof arg.value === 'number' && Number.isSafeInteger(arg.value)) ||\n (typeof arg.value === 'string' && /^-?[0-9]+$/.test(arg.value)),\n 'Solana integer arguments require an exact integer (use decimal strings for large values)',\n );\n const value = BigInt(arg.value);\n const bits = BigInt(arg.type.slice(1));\n const signed = arg.type.startsWith('i');\n const limit = 2n ** (signed ? bits - 1n : bits);\n\n legal(\n value >= (signed ? -limit : 0n) && value < limit,\n `${arg.type} argument is out of range`,\n );\n } else if (arg.type === 'bool') {\n legal(typeof arg.value === 'boolean', 'Invalid bool argument');\n } else if (arg.type === 'pubkey') {\n legal(\n arg.value === intermediary || isAddress(arg.value),\n 'Invalid pubkey argument',\n );\n } else if (arg.type === 'bytes') {\n legal(\n typeof arg.value === 'string' && hex.test(arg.value),\n 'Bytes arguments must be hex without 0x',\n );\n } else if (arg.type === 'string') {\n legal(typeof arg.value === 'string', 'Invalid string argument');\n } else {\n failGuard('ILLEGAL_STEP_SHAPE', 'Unsupported Solana argument type');\n }\n};\n\n/** Validates the bridge-in instruction shape without changing account or table order. */\nexport const solanaStepsAreLegal = (\n steps: SolanaStep[],\n addressLookupTables: string[] = [],\n) => {\n legal(\n addressLookupTables.length <= 16 && addressLookupTables.every(isAddress),\n 'Solana allows at most 16 valid lookup table addresses',\n );\n legal(steps.length <= 50, 'Solana allows at most 50 steps');\n legal(\n new TextEncoder().encode(JSON.stringify({ steps, addressLookupTables }))\n .length <=\n 256 * 1024,\n 'Solana step payload exceeds 256 KiB',\n );\n\n steps.forEach((step) => {\n legal(!!step && typeof step === 'object', 'Invalid Solana instruction');\n keysAreLegal(step, [\n 'programId',\n 'discriminator',\n 'args',\n 'accounts',\n 'metadata',\n ]);\n legal(\n isAddress(step.programId),\n 'Solana programId must be a base58 address',\n );\n legal(\n step.programId !== 'ComputeBudget111111111111111111111111111111',\n 'Connect supplies compute-budget instructions',\n );\n legal(\n step.discriminator === undefined ||\n (typeof step.discriminator === 'string' &&\n hex.test(step.discriminator)),\n 'Solana discriminator must be hex without 0x',\n );\n legal(Array.isArray(step.args), 'Solana args must be an array');\n step.args.forEach(validateArg);\n legal(\n Array.isArray(step.accounts) && step.accounts.length > 0,\n 'Solana instructions require accounts',\n );\n step.accounts.forEach((account) => {\n legal(!!account && typeof account === 'object', 'Invalid Solana account');\n keysAreLegal(account, ['pubkey', 'isSigner', 'isWritable']);\n legal(\n account.pubkey === intermediary || isAddress(account.pubkey),\n 'Invalid Solana account address',\n );\n legal(\n typeof account.isSigner === 'boolean' &&\n typeof account.isWritable === 'boolean',\n 'Solana account flags must be boolean',\n );\n legal(\n !account.isSigner || account.pubkey === intermediary,\n 'Only {INTERMEDIARY} may sign Solana instructions',\n );\n });\n });\n};\n","import { failGuard } from '@/errors';\nimport {\n type ExecutionStep,\n type ExecutionType,\n MAX_FUNCTION_SIGNATURE_BYTES,\n MAX_STEPS,\n type SolanaStep,\n type Step,\n STEP_KEYS,\n} from '@/types/execution';\nimport { solanaStepsAreLegal } from './solanaStepsAreLegal';\n\nconst ALLOWED_KEYS = new Set<string>(STEP_KEYS);\n\n/**\n * Steps accept only the five documented keys. An unknown key, a differently\n * cased spelling, or a duplicate is a 400 — so it is worth catching locally\n * where the message can name the offending step.\n */\nexport const stepShapeIsLegal = (\n steps: ExecutionStep[],\n type: ExecutionType,\n) => {\n if (type === 'solana') {\n solanaStepsAreLegal(steps as SolanaStep[]);\n\n return;\n }\n\n const max = MAX_STEPS[type];\n\n if (steps.length > max) {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `${type} allows at most ${max} steps, got ${steps.length}`,\n );\n }\n\n (steps as Step[]).forEach((step, index) => {\n Object.keys(step).forEach((key) => {\n if (!ALLOWED_KEYS.has(key)) {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: unknown key \"${key}\" (allowed: ${STEP_KEYS.join(', ')})`,\n );\n }\n });\n\n if (typeof step.to !== 'string' || step.to === '') {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: \"to\" must be a non-empty string`,\n );\n }\n\n if (!Array.isArray(step.parameters)) {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: \"parameters\" must be an array`,\n );\n }\n\n if (typeof step.value !== 'string') {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: \"value\" must be a string`,\n );\n }\n\n if (typeof step.functionSignature !== 'string') {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: \"functionSignature\" must be a string (empty for a bare value transfer)`,\n );\n }\n\n // The limit is bytes, so measure bytes: `.length` counts UTF-16 code units\n // and under-counts multi-byte content, letting an over-limit payload\n // through to a server 400.\n const signatureBytes = new TextEncoder().encode(\n step.functionSignature,\n ).length;\n\n if (signatureBytes > MAX_FUNCTION_SIGNATURE_BYTES) {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n `step ${index}: functionSignature exceeds ${MAX_FUNCTION_SIGNATURE_BYTES} bytes`,\n );\n }\n });\n};\n","import { failGuard } from '@/errors';\nimport type { ExecutionStep } from '@/types/execution';\n\n/**\n * A `dry: false` create with an empty steps array is rejected with\n * `400 steps are required for non-dry executions`.\n */\nexport const stepsRequiredForRealCreate = (steps: ExecutionStep[]) => {\n if (steps.length === 0) {\n failGuard('STEPS_REQUIRED', 'dry: false requires a non-empty steps array');\n }\n};\n","import {\n BACKEND_PLACEHOLDERS,\n type ExecutionStep,\n type StepParameter,\n} from '@/types/execution';\n\nconst PLACEHOLDER = BACKEND_PLACEHOLDERS.minAmountOut;\n\nconst parameterUsesPlaceholder = (parameter: StepParameter): boolean =>\n Array.isArray(parameter)\n ? parameter.some(parameterUsesPlaceholder)\n : parameter.includes(PLACEHOLDER);\n\n/**\n * True when the steps embed `{MIN_AMOUNT_OUT}` in a field the backend\n * substitutes — `to`, `value` or `parameters`. `metadata` and\n * `functionSignature` are deliberately not scanned: the backend passes them\n * through untouched, so placeholder-looking text there is inert and must not\n * trip the strategy-conflict guard.\n */\nexport const stepsUsePlaceholder = (steps: ExecutionStep[]): boolean =>\n steps.some((step) =>\n 'programId' in step\n ? step.args.some(\n (arg) =>\n typeof arg.value === 'string' && arg.value.includes(PLACEHOLDER),\n )\n : step.to.includes(PLACEHOLDER) ||\n step.value.includes(PLACEHOLDER) ||\n step.parameters.some(parameterUsesPlaceholder),\n );\n","import { failGuard } from '@/errors';\nimport type { ExecutionStep, FeeStrategy } from '@/types/execution';\nimport { stepsUsePlaceholder } from '@/machine/guards/checks/stepsUsePlaceholder';\n\n/**\n * `{MIN_AMOUNT_OUT}` exists to collapse the three-round protocol into one call,\n * so the two strategies are alternatives. A `threeRound` flow computes literal\n * amounts, and leaking the placeholder into one of its steps would leave two\n * steps operating on different amounts.\n *\n * The converse is deliberately NOT asserted. Under the placeholder strategy the\n * runner passes `{MIN_AMOUNT_OUT}` as `ctx.amount`, so the placeholder appears\n * exactly when the recipe interpolates the amount. A recipe that legitimately\n * never does — a bare `claim()`, or steps with intentionally fixed amounts — is\n * valid, and rejecting it here would block it for no reason. The runner logs a\n * warning via `stepsUsePlaceholder` instead.\n */\nexport const strategiesAreExclusive = (\n strategy: FeeStrategy,\n steps: ExecutionStep[],\n) => {\n if (strategy.kind === 'threeRound' && stepsUsePlaceholder(steps)) {\n failGuard(\n 'STRATEGY_CONFLICT',\n 'threeRound steps must carry literal amounts, not {MIN_AMOUNT_OUT}',\n );\n }\n};\n","import { EVM_CHAIN_IDS, getChainFamily, parseOriginAsset } from '@/chains';\nimport type { Execution, SwapType } from '@/types/execution';\nimport type { OriginToken, ResumeDepositOptions } from '@/runner/types';\n\n/**\n * The subset of an `ExecutionPlan` the deposit leg actually consumes. `run()`\n * retains its full plan (a structural superset), while `resume()` can rebuild\n * one of these from the execution alone — which is what lets a reloaded page\n * still drive the wallet transfer instead of only showing the address.\n */\nexport type DepositPlan = {\n originChain: string;\n originToken: OriginToken;\n originChainId?: number | null;\n depositViaWallet: boolean;\n quote: { swapType: SwapType; deadline?: string };\n};\n\n/**\n * Rebuilds the deposit leg from the execution alone, for a resume with no\n * retained plan. `quote.originAsset` decodes to the chain and token address,\n * the amounts already live on the execution, and for EVM the chain id comes\n * from the built-in registry (EVM transfers move `amountAtomic` and never\n * consult `decimals`). Every other family formats with the token's decimals,\n * so those require `options.originToken` — `undefined` here means \"cannot\n * rebuild safely\", and the caller surfaces the address instead.\n *\n * `quote.swapType` is required for the same reason: it selects WHICH amount\n * the transfer moves, so an execution that does not echo it cannot be driven.\n */\nexport const buildResumeDepositPlan = (\n execution: Execution,\n depositOptions?: ResumeDepositOptions,\n): DepositPlan | undefined => {\n if (depositOptions?.depositViaWallet === false) {\n return undefined;\n }\n\n const { originAsset } = execution.quote;\n const origin = originAsset ? parseOriginAsset(originAsset) : undefined;\n\n if (!origin) {\n return undefined;\n }\n\n const family = getChainFamily(origin.chain);\n\n if (!family) {\n return undefined;\n }\n\n const decimals = depositOptions?.originToken?.decimals;\n\n if (family !== 'evm' && decimals === undefined) {\n return undefined;\n }\n\n const originChainId =\n depositOptions?.originChainId ??\n (family === 'evm' ? (EVM_CHAIN_IDS[origin.chain] ?? null) : null);\n\n if (family === 'evm' && originChainId === null) {\n return undefined;\n }\n\n const { swapType } = execution.quote;\n\n // Never defaulted. The two swap types deposit DIFFERENT fields —\n // `quote.amount` for EXACT_INPUT, `quote.amountIn` for EXACT_OUTPUT, which\n // are denominated in different tokens — so guessing here would move the\n // wrong amount on-chain. Absent means \"cannot rebuild safely\", exactly like\n // the missing decimals and chain id above.\n if (!swapType) {\n return undefined;\n }\n\n return {\n originChain: origin.chain,\n originToken: {\n contractAddress:\n depositOptions?.originToken?.contractAddress ?? origin.tokenAddress,\n decimals: decimals ?? 0,\n },\n originChainId,\n depositViaWallet: true,\n quote: {\n swapType,\n deadline: execution.quote.deadline,\n },\n };\n};\n","import { getChainFamily } from '@/chains';\nimport { failGuard } from '@/errors';\nimport type {\n MakeTransfer,\n MakeTransferArgs,\n TransferPlugins,\n TransferResult,\n} from '@/types/transfer';\nimport type { WalletConnector } from '@/types/wallet';\n\nexport type TransferFn = (\n args: MakeTransferArgs,\n) => Promise<Pick<TransferResult, 'hash'>>;\n\nexport type TransferDeps = {\n getWallet: () => WalletConnector;\n plugins?: TransferPlugins;\n pluginOptions?: unknown;\n makeTransferOverride?: MakeTransfer<void>;\n};\n\n/**\n * Resolves the transfer implementation for an origin chain, in precedence\n * order: the explicit `makeTransfer` override, the connector's own\n * `makeTransfer`, then the chain-family plugin. `undefined` means none is\n * configured — `resume()` uses that to fall back to surfacing the deposit\n * address instead of failing a resumable execution.\n */\nexport const findTransfer = (\n deps: TransferDeps,\n originChain: string,\n): TransferFn | undefined => {\n const { getWallet, plugins, pluginOptions, makeTransferOverride } = deps;\n\n if (makeTransferOverride) {\n return (args) => makeTransferOverride(args, undefined as void);\n }\n\n // Captured at resolution so optional members are read off the live\n // connector exactly once per deposit attempt.\n const activeWallet = getWallet();\n const walletTransfer = activeWallet.makeTransfer;\n\n if (walletTransfer) {\n // Invoked through the connector so a class-based implementation keeps\n // its `this`.\n return (args) => walletTransfer.call(activeWallet, args);\n }\n\n const family = getChainFamily(originChain);\n const plugin = family ? plugins?.[family] : undefined;\n\n if (!family || !plugin) {\n return undefined;\n }\n\n // Each plugin family expects a DIFFERENT options shape, so a multi-chain\n // integration namespaces them by family ({ evm: {…}, sol: {…}, … }) and\n // each plugin receives only its slice. A flat object (single-family\n // setups) passes through unchanged.\n const familyOptions =\n pluginOptions &&\n typeof pluginOptions === 'object' &&\n family in pluginOptions\n ? (pluginOptions as Record<string, unknown>)[family]\n : pluginOptions;\n\n return (args) => plugin.makeTransfer(args, familyOptions);\n};\n\n/**\n * Like `findTransfer`, but a missing implementation throws at resolution\n * rather than invocation: it is a configuration error, not a retryable\n * transfer failure.\n */\nexport const requireTransfer = (\n deps: TransferDeps,\n originChain: string,\n): TransferFn =>\n findTransfer(deps, originChain) ??\n failGuard(\n 'NO_TRANSFER_IMPLEMENTATION',\n `no transfer implementation for origin chain \"${originChain}\" — pass a wallet connector with makeTransfer, a plugin, or makeTransfer directly`,\n );\n","import { parseOriginAsset, SIGNING_STANDARD_CHAINS } from '@/chains';\nimport { DepositTransferError, toError } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type { Execution } from '@/types/execution';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport type { DepositPlan } from '@/runner/depositPlan';\nimport { requireTransfer } from '@/runner/transfer';\n\nexport const exposeDepositAddress = (\n ctx: RunnerCtx,\n execution: Execution,\n deadline?: string,\n /**\n * The origin chain when the caller holds an authoritative one (a plan);\n * otherwise it is derived from the execution itself, falling back to the\n * `SIGNING_STANDARD_CHAINS` inference when the execution does not name its\n * origin.\n */\n originChainHint?: string,\n) => {\n const { to, patch, emit, machine, getWallet } = ctx;\n\n // The memo guard lives HERE, at the one choke point where the shared\n // deposit address is surfaced: a memo-mode deposit without its memo is\n // unattributable — lost, not just failed — so no caller may reach the\n // address without passing it.\n //\n // An unresolved origin is handed to the guard rather than skipping it: the\n // inference below is lossy, and \"cannot tell\" must fail closed.\n const namedOrigin =\n originChainHint ??\n (execution.quote.originAsset\n ? parseOriginAsset(execution.quote.originAsset)?.chain\n : undefined);\n\n // The wallet is consulted ONLY when the execution did not name its origin.\n // A QR / exchange deposit never touches the wallet after signing, so it must\n // still be able to surface its address once the wallet is disconnected or\n // switched — which is exactly when this accessor throws.\n const signingStandard = namedOrigin ? undefined : getWallet().signingStandard;\n\n const originChain =\n namedOrigin ??\n (signingStandard ? SIGNING_STANDARD_CHAINS[signingStandard] : undefined);\n\n guards.memoPresentForStellar(\n originChain,\n execution.quote.depositMemo,\n signingStandard,\n );\n\n to('awaiting-deposit');\n\n guards.mustBeSignedBeforeDeposit(machine.context.hasSubmittedSignature);\n\n const { depositAddress, depositMemo } = execution.quote;\n const validUntil = deadline ?? execution.quote.deadline;\n\n patch({ depositAddress, depositMemo, deadline: validUntil });\n\n emit({\n type: 'deposit-address',\n address: depositAddress,\n memo: depositMemo,\n deadline: validUntil,\n });\n\n return { depositAddress, depositMemo };\n};\n\nexport const awaitDeposit = async (\n ctx: RunnerCtx,\n plan: DepositPlan,\n execution: Execution,\n) => {\n const { api, logger, state, patch, emit, assertLive } = ctx;\n\n const { depositAddress, depositMemo } = exposeDepositAddress(\n ctx,\n execution,\n plan.quote.deadline,\n plan.originChain,\n );\n\n // QR / exchange path: the sender is not our wallet, so there is no tx hash\n // to record. The backend's deposit watcher observes settlement instead.\n if (!plan.depositViaWallet) {\n return;\n }\n\n // A cancel() or dispose() that landed while the earlier stages ran must\n // stop the flow BEFORE the wallet is asked to move funds.\n assertLive(execution.id);\n\n // EXACT_INPUT sends quote.amount verbatim; EXACT_OUTPUT sends the service's\n // computed origin commitment. Never recompute it.\n const amountAtomic =\n plan.quote.swapType === 'EXACT_OUTPUT'\n ? execution.quote.amountIn\n : execution.quote.amount;\n\n const transfer = requireTransfer(ctx, plan.originChain);\n\n let hash: string;\n\n try {\n ({ hash } = await transfer({\n amountAtomic,\n // Duplicated on the widget-compat alias: the widget's network plugins\n // read `args.amount` (already atomic there) and never look at\n // `amountAtomic`, so omitting it would crash every plugin deposit.\n amount: amountAtomic,\n decimals: plan.originToken.decimals,\n address: depositAddress,\n tokenAddress: plan.originToken.contractAddress,\n chain: plan.originChain,\n evmChainId: plan.originChainId ?? null,\n isNativeEvmTokenTransfer: !plan.originToken.contractAddress,\n memo: depositMemo ?? undefined,\n }));\n } catch (error) {\n // A rejected wallet prompt is the single most common event at this\n // stage, and the execution is still valid and signed server-side — so\n // this is a retryable pause (`retryDeposit()`), not a terminal failure.\n throw new DepositTransferError(execution.id, { cause: toError(error) });\n }\n\n // Recorded on `state`, which survives the machine reset a later resume()\n // performs — the context's `depositTxHash` does not, and a resume that\n // forgot this would prompt a second transfer for funds already sent.\n //\n // BEFORE the liveness checkpoint below, and unconditionally: a broadcast tx\n // cannot be un-sent, so it must be remembered even when the flow is about to\n // die — that is precisely when a resume() would otherwise re-prompt for it.\n state.depositSentExecutionIds.add(execution.id);\n\n // Re-checked AFTER the prompt, not only before it — the same checkpoint\n // signAndSubmit places once its own prompt returns. A cancel() that landed\n // while the transfer sat open has already DELETED the execution and wiped\n // exactly the fields written below, so recording the hash would resurrect a\n // cancelled execution as one holding a live deposit; a dispose() has rebound\n // the runner's owner, whose onEvent this is no longer. The funds are gone\n // either way, so the hash is logged rather than swallowed.\n try {\n assertLive(execution.id);\n } catch (error) {\n logger.warn(\n `deposit ${hash} for execution ${execution.id} was broadcast after the execution was cancelled or the runner was disposed — the funds were sent but are not recorded server-side`,\n );\n\n throw error;\n }\n\n patch({ depositTxHash: hash });\n emit({ type: 'deposit-sent', txHash: hash });\n\n // Best-effort: notifies 1Click without waiting for the watcher.\n try {\n await api.recordDeposit({\n txHash: hash,\n depositAddress,\n ...(depositMemo ? { memo: depositMemo } : {}),\n });\n } catch (error) {\n logger.warn('failed to record the deposit (non-fatal)', error);\n }\n};\n","import {\n DepositTransferError,\n ExecutionCancelledError,\n RunnerDisposedError,\n toError,\n} from '@/errors';\nimport type { RunnerCtx } from '@/runner/ctx';\n\n/** Shared failure handling: record it, announce it, then rethrow. */\nexport const fail = (ctx: RunnerCtx, error: unknown): never => {\n const { machine, state, patch, emit, to } = ctx;\n const failure = toError(error);\n\n // A cancellation is not a failure: nothing went wrong, the caller asked to\n // stop. cancel() already cleared `error` and moved the machine — recording\n // the checkpoint's throw here would undo that cleanup and make a UI keyed\n // off `error` render the deliberate cancel as a failure.\n //\n // Tested by OWNERSHIP first, because the error type alone misses the\n // auto-cancel path: a rejected signature that cancel() cleaned up still\n // rethrows the ORIGINAL rejection, not an ExecutionCancelledError. If the\n // execution this flow was driving is already deleted, there is nothing left\n // to record a failure against.\n //\n // A disposal is not a failure either: the execution is untouched\n // server-side and resumable from a correctly bound runner, and dispose()'s\n // contract is that the orphaned run stops emitting — patching and emitting\n // here would surface a spurious failure through the shared onEvent right\n // after a normal account switch.\n const { executionId } = machine.context;\n const alreadyCancelled =\n executionId !== undefined && state.cancelledExecutionIds.has(executionId);\n\n if (\n alreadyCancelled ||\n failure instanceof ExecutionCancelledError ||\n failure instanceof RunnerDisposedError\n ) {\n throw failure;\n }\n\n patch({ error: failure });\n emit({ type: 'error', error: failure });\n\n // A rejected deposit transfer is retryable — the execution is still valid\n // and signed, so the machine stays in `awaiting-deposit` for\n // `retryDeposit()`. A cancellation already moved the machine to\n // `cancelled`. Anything else is a failure, including one raised before any\n // phase progress.\n const retryable = failure instanceof DepositTransferError;\n\n if (\n !retryable &&\n machine.current !== 'cancelled' &&\n machine.current !== 'failed'\n ) {\n to('failed');\n }\n\n throw failure;\n};\n","import { ExecutionPollTimeoutError } from '@/errors';\nimport type { Phase } from '@/machine/phases';\nimport {\n AWAITING_FUNDS_STATUSES,\n type Execution,\n type ExecutionStatus,\n TERMINAL_STATUSES,\n} from '@/types/execution';\nimport {\n DEPOSIT_DEADLINE_GRACE_MS,\n HOLDING_POLL_BACKOFF_FACTOR,\n MAX_CONSECUTIVE_POLL_ERRORS,\n MAX_HOLDING_POLL_INTERVAL_MS,\n} from '@/runner/constants';\nimport type { RunnerCtx, RunnerState } from '@/runner/ctx';\n\n/**\n * Interruptible sleep: `dispose()` (and a completed `cancel()`) resolve it\n * early via `state.wakeSleepers`, so the loop reaches its checkpoint now\n * instead of after up to a full poll interval — and nothing retains the\n * settle closure (or, under Node/SSR, a live timer) across that gap.\n */\nconst sleep = (ms: number, state: RunnerState) =>\n new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const wake = () => {\n clearTimeout(timer);\n state.wakeSleepers.delete(wake);\n resolve();\n };\n\n timer = setTimeout(wake, ms);\n state.wakeSleepers.add(wake);\n });\n\n/**\n * The phase a non-terminal poll observation should move to, or `undefined`\n * to hold the current one.\n *\n * EXPIRED is soft-terminal: reflect it in the phase and keep polling, because\n * a late deposit revives the execution. Held rather than flipped back each\n * iteration, so the phase mirrors the observed state instead of emitting two\n * events per poll. While `awaiting-deposit`, only a status PAST the\n * awaiting-funds pair means the watcher observed the deposit — the\n * waiting-for-funds hold ends.\n */\nexport const reconcileSettlePhase = (\n current: Phase,\n status: ExecutionStatus,\n): Phase | undefined => {\n if (status === 'EXPIRED') {\n return 'expired';\n }\n\n if (current === 'expired') {\n return 'settling';\n }\n\n if (\n current === 'awaiting-deposit' &&\n !AWAITING_FUNDS_STATUSES.includes(status)\n ) {\n return 'settling';\n }\n\n return undefined;\n};\n\n/* ── 7. Settle ───────────────────────────────────────────────────────────\n * The API answers with an array even for a single id.\n *\n * `no-await-in-loop` is disabled deliberately: polling is inherently\n * sequential. Each round must observe the result of the previous sleep, so\n * parallelising the requests would just hammer the API. */\nexport const settle = async (\n ctx: RunnerCtx,\n executionId: string,\n): Promise<Execution> => {\n const {\n api,\n logger,\n machine,\n state,\n to,\n patch,\n emit,\n requireAddress,\n throwIfDisposed,\n throwIfCancelled,\n pollIntervalMs,\n maxPollAttempts,\n } = ctx;\n\n // The QR / exchange path stays in `awaiting-deposit` until the watcher\n // observes funds — the UI's deposit screen keys off that phase, and the\n // user may take minutes to move funds. `DEPOSIT_PENDING` still counts as\n // waiting: it means signed with the deposit NOT yet observed. Every other\n // entry settles at once.\n const holdingForDeposit = () =>\n machine.current === 'awaiting-deposit' &&\n machine.context.status !== undefined &&\n AWAITING_FUNDS_STATUSES.includes(machine.context.status) &&\n !machine.context.depositTxHash;\n\n if (!holdingForDeposit()) {\n to('settling');\n }\n\n // Captured once. Re-reading it per iteration would turn a wallet disconnect\n // during a multi-minute settle into a reported failure for an execution that\n // is completing successfully on-chain.\n const address = requireAddress();\n\n const deadlineMs = machine.context.deadline\n ? Date.parse(machine.context.deadline)\n : Number.NaN;\n\n let attempt = 0;\n let consecutiveErrors = 0;\n let holdInterval = pollIntervalMs;\n\n while (attempt < maxPollAttempts) {\n throwIfDisposed();\n throwIfCancelled(executionId);\n\n let execution: Execution | undefined;\n\n try {\n // eslint-disable-next-line no-await-in-loop\n [execution] = await api.listExecutions(address, { id: executionId });\n consecutiveErrors = 0;\n } catch (error) {\n // One transient failure must not report a live execution as failed;\n // only a persistently unreachable API escalates.\n consecutiveErrors += 1;\n\n if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {\n throw error;\n }\n\n logger.warn(\n `poll for execution ${executionId} failed (${consecutiveErrors}/${MAX_CONSECUTIVE_POLL_ERRORS} consecutive) — retrying`,\n error,\n );\n }\n\n // Re-checked AFTER the round-trip, not only before it. A cancel() or\n // dispose() that landed while this poll was in flight has already wiped\n // the context and rebound the runner's owner, so writing the response\n // below would resurrect a deleted execution and emit through an onEvent\n // that is no longer ours.\n throwIfDisposed();\n throwIfCancelled(executionId);\n\n if (execution) {\n // Patch and emit only on change: every React consumer re-renders per\n // event, and settling can span hundreds of identical polls.\n if (execution.status !== machine.context.status) {\n patch({ execution, status: execution.status });\n emit({ type: 'status', status: execution.status });\n }\n\n if (TERMINAL_STATUSES.includes(execution.status)) {\n if (execution.status === 'SUCCESS') {\n to('success');\n\n return execution;\n }\n\n to('failed');\n\n throw new Error(`execution ${execution.status}`);\n }\n\n const next = reconcileSettlePhase(machine.current, execution.status);\n\n if (next) {\n to(next);\n }\n }\n\n // While waiting on user funds, the clock is the quote deadline, not the\n // poll budget: burning the attempts while the user is still moving funds\n // through an exchange would declare a live execution failed.\n const withinDepositWindow =\n holdingForDeposit() &&\n Number.isFinite(deadlineMs) &&\n Date.now() < deadlineMs + DEPOSIT_DEADLINE_GRACE_MS;\n\n if (!withinDepositWindow) {\n attempt += 1;\n }\n\n if (attempt < maxPollAttempts) {\n // The deposit-window hold can span ~15 minutes by default, so its\n // interval backs off — detection latency barely matters while the user\n // is still routing funds. Keyed on the WINDOW, not the hold: once\n // attempts start counting, they must burn at pollIntervalMs, or the\n // timeout stretches from minutes to hours. Updated before the await so\n // the read/advance pair stays together.\n const delayMs = withinDepositWindow ? holdInterval : pollIntervalMs;\n\n holdInterval = withinDepositWindow\n ? Math.min(\n holdInterval * HOLDING_POLL_BACKOFF_FACTOR,\n MAX_HOLDING_POLL_INTERVAL_MS,\n )\n : pollIntervalMs;\n\n // eslint-disable-next-line no-await-in-loop\n await sleep(delayMs, state);\n }\n }\n\n const expired = machine.current === 'expired';\n\n to('failed');\n\n // Typed, and explicit that this is NOT a verdict: the execution is still\n // live server-side and `resume()` reattaches to it.\n throw new ExecutionPollTimeoutError(\n executionId,\n expired\n ? `execution ${executionId} expired and was not revived within ${maxPollAttempts} polls`\n : `polling timed out after ${maxPollAttempts} attempts for execution ${executionId}`,\n );\n};\n","import { base58, base64, hex } from '@scure/base';\n\n/**\n * Wire encodings the NEAR intents verifier expects.\n *\n * These are the rules that cost the most time to rediscover, so they live in\n * exactly one place: base58 (never base64) on the wire, a `secp256k1:` or\n * `ed25519:` prefix, and a recovery byte normalised to 0/1.\n */\n\nconst SIGNATURE_BYTE_LENGTH_ED25519 = 64;\nconst SIGNATURE_BYTE_LENGTH_SECP256K1 = 65;\nconst RECOVERY_BYTE_INDEX = 64;\n\nexport const fromBase64 = (value: string): Uint8Array => base64.decode(value);\n\nexport const toBase64 = (bytes: Uint8Array): string => base64.encode(bytes);\n\nexport const toBase58 = (bytes: Uint8Array): string => base58.encode(bytes);\n\n/**\n * `hex.decode` accepts both cases and throws loudly on odd length or a\n * non-hex character — a malformed wallet signature must never decode into a\n * well-formed all-zero one. Only the `0x` prefix has to be stripped here.\n */\nexport const fromHex = (value: string): Uint8Array =>\n hex.decode(value.replace(/^0x/i, ''));\n\n/**\n * `personal_sign` / TIP-191 return `v` as 27 or 28; the verifier wants 0 or 1.\n * Only byte 64 is touched — `r` and `s` are left alone.\n */\nexport const normaliseRecoveryByte = (signature: Uint8Array): Uint8Array => {\n if (signature.length !== SIGNATURE_BYTE_LENGTH_SECP256K1) {\n throw new Error(\n `secp256k1 signature must be ${SIGNATURE_BYTE_LENGTH_SECP256K1} bytes, got ${signature.length}`,\n );\n }\n\n const normalised = Uint8Array.from(signature);\n const recovery = normalised[RECOVERY_BYTE_INDEX];\n\n if (recovery >= 27) {\n normalised[RECOVERY_BYTE_INDEX] = recovery - 27;\n }\n\n return normalised;\n};\n\nexport const assertEd25519SignatureLength = (\n signature: Uint8Array,\n label: string,\n): Uint8Array => {\n if (signature.length !== SIGNATURE_BYTE_LENGTH_ED25519) {\n throw new Error(\n `${label} signature must be ${SIGNATURE_BYTE_LENGTH_ED25519} bytes, got ${signature.length}`,\n );\n }\n\n return signature;\n};\n\nexport const secp256k1Signature = (bytes: Uint8Array): string =>\n `secp256k1:${toBase58(bytes)}`;\n\nexport const ed25519Signature = (bytes: Uint8Array): string =>\n `ed25519:${toBase58(bytes)}`;\n\nexport const ed25519PublicKeyFromBytes = (bytes: Uint8Array): string =>\n `ed25519:${toBase58(bytes)}`;\n\n/** Solana addresses are already the base58 public key. */\nexport const ed25519PublicKeyFromBase58 = (value: string): string =>\n value.startsWith('ed25519:') ? value : `ed25519:${value}`;\n","import type { EvmProvider } from '@/types/providers';\nimport type { SignatureEnvelope } from '@/types/signing';\nimport {\n fromHex,\n normaliseRecoveryByte,\n secp256k1Signature,\n} from '@/signers/standards/encoding';\n\nexport type Erc191SignArgs = {\n /** Signed verbatim. Never parse-then-stringify — that changes the hash. */\n message: string;\n provider: EvmProvider;\n /** The address the execution is bound to. */\n expectedAddress: string;\n};\n\n/**\n * EIP-191 `personal_sign`. The wallet applies the\n * `\"\\x19Ethereum Signed Message:\\n\" + len` prefix and keccak256 internally, so\n * the message is passed through untouched and never pre-hashed.\n *\n * No `publicKey` is returned: the backend recovers the signer with `ecrecover`,\n * and sending one is rejected.\n */\nexport const signErc191 = async ({\n message,\n provider,\n expectedAddress,\n}: Erc191SignArgs): Promise<SignatureEnvelope> => {\n const resolved = typeof provider === 'function' ? await provider() : provider;\n\n const accounts = await resolved.request({ method: 'eth_requestAccounts' });\n\n if (!Array.isArray(accounts)) {\n throw new Error('EVM provider returned no accounts');\n }\n\n const signingAccount = accounts.find(\n (account): account is string =>\n typeof account === 'string' &&\n account.toLowerCase() === expectedAddress.toLowerCase(),\n );\n\n if (!signingAccount) {\n throw new Error('Connected EVM account does not match the execution');\n }\n\n const signature = await resolved.request({\n method: 'personal_sign',\n // Argument order is [message, address].\n params: [message, signingAccount],\n });\n\n if (typeof signature !== 'string') {\n throw new Error('EVM provider returned no signature');\n }\n\n return {\n signature: secp256k1Signature(normaliseRecoveryByte(fromHex(signature))),\n };\n};\n","import type { SolanaProvider } from '@/types/providers';\nimport type { SignatureEnvelope } from '@/types/signing';\nimport {\n assertEd25519SignatureLength,\n ed25519PublicKeyFromBase58,\n ed25519Signature,\n} from '@/signers/standards/encoding';\n\nexport type RawEd25519SignArgs = {\n /**\n * The exact bytes the backend hashes.\n *\n * Callers MUST pass decoded bytes, not a UTF-8 encoded string: some wallet\n * versions re-encode strings in a way that does not byte-match what the\n * backend verifies against.\n */\n bytes: Uint8Array;\n provider: SolanaProvider;\n /** Base58 Solana address, which is also the ed25519 public key. */\n expectedAddress: string;\n};\n\n/**\n * Raw ed25519 over the payload bytes. No envelope (no SIWS, no\n * `\"\\x19Solana Signed Message:\"`) and no pre-hashing.\n */\nexport const signRawEd25519 = async ({\n bytes,\n provider,\n expectedAddress,\n}: RawEd25519SignArgs): Promise<SignatureEnvelope> => {\n const providerPublicKey = provider.publicKey?.toString();\n\n if (providerPublicKey && providerPublicKey !== expectedAddress) {\n throw new Error('Connected Solana account does not match the execution');\n }\n\n const signature = await provider.signMessage(bytes);\n\n return {\n signature: ed25519Signature(\n assertEd25519SignatureLength(signature, 'Solana'),\n ),\n publicKey: ed25519PublicKeyFromBase58(providerPublicKey ?? expectedAddress),\n };\n};\n","import type { NearWalletBase } from '@/types/providers';\nimport type { SignatureEnvelope } from '@/types/signing';\nimport {\n ed25519PublicKeyFromBase58,\n ed25519Signature,\n fromBase64,\n} from '@/signers/standards/encoding';\n\nexport type Nep413Payload = {\n message: string;\n /** Base64-encoded 32 bytes. */\n nonce: string;\n recipient: string;\n callbackUrl?: string | null;\n};\n\nexport type Nep413SignArgs = {\n payload: Nep413Payload;\n getProvider: () => NearWalletBase;\n /** The NEAR account the execution is bound to. */\n expectedAccountId: string;\n};\n\n/**\n * NEP-413. The wallet builds the prefix tag, borsh-encodes and SHA-256 hashes\n * internally — do not pre-hash, do not pre-borsh, do not wrap the message.\n */\nexport const signNep413 = async ({\n payload,\n getProvider,\n expectedAccountId,\n}: Nep413SignArgs): Promise<SignatureEnvelope> => {\n const wallet = getProvider();\n\n if (!wallet.signMessage) {\n throw new Error('NEAR wallet does not expose signMessage');\n }\n\n // The nonce must reach the wallet as 32 raw bytes. Passing the base64 string\n // makes the borsh-encoded payload diverge from what the backend verifies.\n const nonce = fromBase64(payload.nonce);\n\n // Only the NEP-413 trio. `callbackUrl` is borsh-encoded as Option<String>,\n // so forwarding it would change the signed digest byte-for-byte — the\n // backend verifies against {message, recipient, nonce} alone.\n const signed = await wallet.signMessage({\n message: payload.message,\n recipient: payload.recipient,\n nonce,\n });\n\n if (!signed) {\n throw new Error('NEAR wallet failed to sign the message');\n }\n\n if (signed.accountId !== expectedAccountId) {\n throw new Error('Connected NEAR account does not match the execution');\n }\n\n const publicKey = ed25519PublicKeyFromBase58(signed.publicKey);\n\n // NEP-413 wallets return base64; the verifier wants ed25519:<base58>.\n // Wallets disagree about whether they already applied the prefix — and some\n // return raw bytes instead of a string.\n const rawSignature = signed.signature as string | Uint8Array;\n\n let signature: string;\n\n if (typeof rawSignature !== 'string') {\n signature = ed25519Signature(rawSignature);\n } else if (rawSignature.startsWith('ed25519:')) {\n signature = rawSignature;\n } else {\n signature = ed25519Signature(fromBase64(rawSignature));\n }\n\n return { signature, publicKey };\n};\n","import { toError } from '@/errors';\nimport type { StellarProvider } from '@/types/providers';\nimport type { SignatureEnvelope } from '@/types/signing';\nimport {\n assertEd25519SignatureLength,\n ed25519PublicKeyFromBytes,\n ed25519Signature,\n fromBase64,\n} from '@/signers/standards/encoding';\n\nexport type Sep53SignArgs = {\n /** Signed verbatim, like erc191. */\n message: string;\n provider: StellarProvider;\n /** The `G…` StrKey address the execution is bound to. */\n expectedAddress: string;\n /**\n * StrKey `G…` → 32 raw bytes.\n *\n * Injected rather than implemented here so `@stellar/stellar-sdk` stays out\n * of this package — the same indirection the widget's `StellarNetworkPlugin`\n * uses. A `G…` string is NOT raw base58, so it cannot be encoded directly.\n */\n decodePublicKey: () => Uint8Array;\n};\n\n/**\n * SEP-53. Freighter applies the `\"Stellar Signed Message:\\n\"` prefix and\n * SHA-256 internally — do not pre-hash and do not wrap.\n */\nexport const signSep53 = async ({\n message,\n provider,\n expectedAddress,\n decodePublicKey,\n}: Sep53SignArgs): Promise<SignatureEnvelope> => {\n const result = await provider.signMessage(message);\n\n // Freighter reports failures IN-BAND rather than rejecting: a user\n // rejection arrives as `{ error }` with no signedMessage, and destructuring\n // it blindly turns a clean rejection into an opaque decoding crash.\n // Rethrown through toError so the original value survives on `cause` —\n // isUserRejection reads the rejection code from there.\n const inBandError = (result as { error?: { message?: string } | string })\n ?.error;\n\n if (inBandError) {\n throw toError(inBandError);\n }\n\n const { signedMessage, signerAddress } = result;\n\n if (!signedMessage) {\n throw new Error('Stellar wallet returned no signed message');\n }\n\n if (signerAddress && signerAddress !== expectedAddress) {\n throw new Error('Connected Stellar account does not match the execution');\n }\n\n // Freighter versions disagree: base64 string or Uint8Array.\n const signature =\n signedMessage instanceof Uint8Array\n ? signedMessage\n : fromBase64(signedMessage);\n\n return {\n signature: ed25519Signature(\n assertEd25519SignatureLength(signature, 'SEP-53'),\n ),\n publicKey: ed25519PublicKeyFromBytes(decodePublicKey()),\n };\n};\n","import { failGuard } from '@/errors';\nimport type { Providers } from '@/types/providers';\nimport type {\n DeleteSignatureEnvelope,\n SignatureEnvelope,\n SigningPayload,\n SigningStandard,\n} from '@/types/signing';\nimport {\n fromBase64,\n type Nep413Payload,\n signErc191,\n signNep413,\n signRawEd25519,\n signSep53,\n toBase64,\n} from '@/signers/standards';\n\nexport type SignPayloadArgs = {\n payload: SigningPayload;\n standard: SigningStandard;\n /** The origin wallet address the execution is bound to. */\n address: string;\n providers: Providers;\n /** Required for `sep53`. Supplied by the Stellar wallet package. */\n decodePublicKey?: () => Uint8Array;\n};\n\nconst requireProvider = <T>(\n provider: T | null | undefined,\n standard: SigningStandard,\n): T => {\n if (!provider) {\n return failGuard(\n 'WALLET_NOT_CONNECTED',\n `no provider available to sign a ${standard} payload`,\n );\n }\n\n return provider;\n};\n\nconst parseNep413Payload = (payloadJson: string): Nep413Payload => {\n const parsed: unknown = JSON.parse(payloadJson);\n\n if (!parsed || typeof parsed !== 'object') {\n throw new Error('nep413 payload_json is not an object');\n }\n\n return parsed as Nep413Payload;\n};\n\n/**\n * Adapts `execution.details.payload` onto the shared standards layer.\n *\n * Which field to sign differs per standard, and getting it wrong produces a\n * signature the backend rejects with no useful diagnostic:\n *\n * - `erc191` / `sep53` — `payload_json`, verbatim as a string.\n * - `raw_ed25519` — the DECODED bytes of `payload_bytes_base64`.\n * - `nep413` — `payload_json` parsed into `{ message, recipient, nonce }`.\n */\nexport const signIntentsConnectPayload = async ({\n payload,\n standard,\n address,\n providers,\n decodePublicKey,\n}: SignPayloadArgs): Promise<SignatureEnvelope> => {\n switch (standard) {\n case 'erc191':\n return signErc191({\n message: payload.payload_json,\n provider: requireProvider(providers.evm, standard),\n expectedAddress: address,\n });\n\n case 'raw_ed25519':\n // Deliberately the base64-decoded bytes, not payload_json. The widget's\n // 1Click signer encodes the JSON string instead, which does not\n // byte-match what this API verifies against.\n return signRawEd25519({\n bytes: fromBase64(payload.payload_bytes_base64),\n provider: requireProvider(providers.sol, standard),\n expectedAddress: address,\n });\n\n case 'nep413':\n return signNep413({\n payload: parseNep413Payload(payload.payload_json),\n getProvider: requireProvider(providers.near, standard),\n expectedAccountId: address,\n });\n\n case 'sep53':\n if (!decodePublicKey) {\n return failGuard(\n 'UNSUPPORTED_SIGNING_STANDARD',\n 'sep53 requires a decodePublicKey implementation (supply it from the Stellar wallet package)',\n );\n }\n\n return signSep53({\n message: payload.payload_json,\n provider: requireProvider(providers.stellar, standard),\n expectedAddress: address,\n decodePublicKey,\n });\n\n default:\n return failGuard(\n 'UNSUPPORTED_SIGNING_STANDARD',\n `signing standard ${String(standard)} is not implemented`,\n );\n }\n};\n\nexport type SignTextArgs = {\n text: string;\n standard: SigningStandard;\n address: string;\n providers: Providers;\n decodePublicKey?: () => Uint8Array;\n};\n\n/**\n * `recipient` for a nep413 DELETE. Mixed into the signed digest server-side,\n * so it must be exactly this value — see the delete-execution guide.\n */\nconst NEP413_DELETE_RECIPIENT = 'intents.near';\n\nconst NEP413_NONCE_BYTES = 32;\n\nconst randomNonce = (): Uint8Array => {\n const bytes = new Uint8Array(NEP413_NONCE_BYTES);\n\n globalThis.crypto.getRandomValues(bytes);\n\n return bytes;\n};\n\n/**\n * Signs a bare ASCII string — used only for `delete_execution:{executionId}`.\n * No JSON, no envelope, no hashing: the wallet applies its own standard framing.\n *\n * `nep413` additionally returns the client-generated `{ recipient, nonce }`\n * envelope — the backend needs both to rebuild the exact bytes the wallet\n * signed, and omitting the block is a 400.\n *\n * `sep53` is refused: the delete endpoint accepts only raw_ed25519, nep413,\n * erc191, tip191 and ton_connect, so a Stellar-signed delete would be signed,\n * submitted, and rejected with a 400 anyway. Failing before the wallet prompt\n * is the honest version of that outcome.\n */\nexport const signIntentsConnectText = async ({\n text,\n standard,\n address,\n providers,\n}: SignTextArgs): Promise<DeleteSignatureEnvelope> => {\n switch (standard) {\n case 'erc191':\n return signErc191({\n message: text,\n provider: requireProvider(providers.evm, standard),\n expectedAddress: address,\n });\n\n case 'raw_ed25519':\n return signRawEd25519({\n bytes: new TextEncoder().encode(text),\n provider: requireProvider(providers.sol, standard),\n expectedAddress: address,\n });\n\n case 'nep413': {\n const nonceBytes = randomNonce();\n\n const envelope = await signNep413({\n payload: {\n message: text,\n recipient: NEP413_DELETE_RECIPIENT,\n nonce: toBase64(nonceBytes),\n },\n getProvider: requireProvider(providers.near, standard),\n expectedAccountId: address,\n });\n\n return {\n ...envelope,\n nep413: {\n recipient: NEP413_DELETE_RECIPIENT,\n nonce: toBase64(nonceBytes),\n },\n };\n }\n\n case 'sep53':\n return failGuard(\n 'UNSUPPORTED_SIGNING_STANDARD',\n 'the delete_execution endpoint does not accept sep53 — a Stellar-origin execution cannot be cancelled client-side and clears on expiry',\n );\n\n default:\n return failGuard(\n 'UNSUPPORTED_SIGNING_STANDARD',\n `cancelling a ${String(standard)} origin execution is not supported yet`,\n );\n }\n};\n","import * as guards from '@/machine/guards';\nimport { signIntentsConnectPayload } from '@/signers/intentsConnect';\nimport type { Execution } from '@/types/execution';\nimport type { SignatureEnvelope, SigningStandard } from '@/types/signing';\nimport type { RunnerCtx } from '@/runner/ctx';\n\n/**\n * Returns the standard alongside the envelope. The caller has to validate the\n * envelope against the standard it was actually signed with — which comes from\n * the execution, not from what the connector claims to be.\n */\nconst signPayload = async (\n ctx: RunnerCtx,\n execution: Execution,\n): Promise<{ envelope: SignatureEnvelope; standard: SigningStandard }> => {\n const { payload, standard } = guards.mustHaveSigningPayload(execution);\n const activeWallet = ctx.getWallet();\n\n const envelope = await signIntentsConnectPayload({\n payload,\n standard,\n address: ctx.requireAddress(),\n providers: activeWallet.getProviders(),\n // Bound to the connector so a class-based implementation keeps its `this`\n // when the sep53 signer invokes it bare.\n decodePublicKey: activeWallet.decodePublicKey?.bind(activeWallet),\n });\n\n return { envelope, standard };\n};\n\nexport const signAndSubmit = async (\n ctx: RunnerCtx,\n execution: Execution,\n): Promise<boolean> => {\n const { api, requireAddress, to, patch, assertLive } = ctx;\n\n to('awaiting-signature');\n assertLive(execution.id);\n\n const { envelope, standard } = await signPayload(ctx, execution);\n\n // The wallet prompt can sit open across a cancel() or a dispose(); a\n // signature approved after either must not be submitted.\n assertLive(execution.id);\n\n // Checked against the execution's standard, not the connector's: the\n // envelope was produced from the former, and a disagreement between the two\n // is itself the fault to report rather than a publicKey mismatch.\n guards.publicKeyMatchesStandard(standard, envelope.publicKey);\n\n to('submitting');\n\n const { status } = await api.submitSignature(requireAddress(), {\n ...envelope,\n executionId: execution.id,\n });\n\n patch({ hasSubmittedSignature: true });\n\n // Out-operations answer SIGNING — already OPERATION_PENDING, nothing to\n // deposit. v1 only creates bridge-ins, but the branch is real.\n return status !== 'SIGNING';\n};\n","import * as guards from '@/machine/guards';\nimport type { Execution } from '@/types/execution';\n\n/** Solana reports the bridge guarantee before its separate fee; EVM reports net. */\nexport const getQuoteSpendable = (execution: Execution): string => {\n const networkFee = guards.feeMustBeEstimated(execution);\n const minimum = execution.quote.minAmountOut;\n\n if (execution.type !== 'solana') {\n return minimum;\n }\n\n guards.amountMustExceedFee(minimum, networkFee);\n\n return (BigInt(minimum) - BigInt(networkFee)).toString();\n};\n","import { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type { Execution } from '@/types/execution';\nimport { getQuoteSpendable } from '@/runner/quoteAmounts';\n\n/** Used by preview, real create, and an unsigned resume. Always compare net amounts. */\nexport const validatePreparedExecution = (\n execution: Execution,\n bakedAmount?: string,\n) => {\n const recorded = execution.metadata?.intentsConnectSpendable;\n const amount =\n bakedAmount ?? (typeof recorded === 'string' ? recorded : undefined);\n\n if (execution.type === 'solana' && !amount) {\n failGuard(\n 'QUOTE_MOVED',\n 'Missing prepared Solana spendable amount; cancel and prepare a new execution',\n );\n }\n\n if (amount) {\n guards.quoteMustNotHaveMoved(amount, getQuoteSpendable(execution));\n }\n};\n","import * as guards from '@/machine/guards';\nimport { AWAITING_FUNDS_STATUSES, type Execution } from '@/types/execution';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport { buildResumeDepositPlan } from '@/runner/depositPlan';\nimport { awaitDeposit, exposeDepositAddress } from '@/runner/stages/deposit';\nimport { fail } from '@/runner/stages/fail';\nimport { settle } from '@/runner/stages/settle';\nimport { signAndSubmit } from '@/runner/stages/signAndSubmit';\nimport { validatePreparedExecution } from '@/runner/stages/validatePreparedExecution';\nimport { findTransfer } from '@/runner/transfer';\nimport type { ResumeDepositOptions } from '@/runner/types';\n\n/**\n * Whether an execution was created steps-only, i.e. has no deposit leg.\n * `executionMode` is optional on the wire, so the marker `runSteps()` writes\n * into metadata is the fallback for older deployments.\n */\nexport const isStepsOnlyExecution = (execution: Execution): boolean =>\n execution.executionMode === 'steps_only' ||\n execution.metadata?.intentsConnectFlow === 'steps-only';\n\n/**\n * The steps-only counterpart of `validatePreparedExecution`: there is no\n * quote to compare, but the fee the steps were sized for travels in metadata\n * and the real fee must still fit it.\n */\nconst validateStepsExecution = (execution: Execution) => {\n const budget = execution.metadata?.intentsConnectFeeBudget;\n\n if (typeof budget === 'string') {\n guards.feeWithinBudget(guards.feeMustBeEstimated(execution), budget);\n }\n};\n\n/**\n * Reattaches to an execution from an earlier session.\n *\n * Picks up from wherever it actually got rather than assuming it is already\n * settling: an execution that was signed but never funded still needs its\n * deposit address surfaced, and one that was never signed can still be signed.\n */\nexport const resume = async (\n ctx: RunnerCtx,\n executionId: string,\n depositOptions?: ResumeDepositOptions,\n): Promise<Execution> => {\n const { api, state, requireAddress, patch } = ctx;\n\n ctx.prepareForNewFlow();\n\n try {\n const [execution] = await api.listExecutions(requireAddress(), {\n id: executionId,\n });\n\n if (!execution) {\n throw new Error(`no execution found for id ${executionId}`);\n }\n\n const { messageSigned, payload } = execution.details;\n\n // Sign whenever a payload is still offered and nothing says it was\n // signed. `messageSigned` alone is not trustworthy in the other\n // direction: it is optional on the wire, and inferring \"signed\" from a\n // non-CREATED status mislabels a deposit that was detected before the\n // signature.\n const needsSigning = messageSigned !== true && Boolean(payload);\n\n // An unsigned CREATED execution with no payload can never progress —\n // name that instead of polling it to a timeout.\n if (execution.status === 'CREATED' && messageSigned !== true && !payload) {\n guards.mustHaveSigningPayload(execution);\n }\n\n patch({\n execution,\n executionId: execution.id,\n status: execution.status,\n hasSubmittedSignature: !needsSigning,\n });\n\n // The awaiting-funds statuses need their deposit driven — DEPOSIT_PENDING\n // is the single most common resume case, since a failed transfer leg\n // strands an execution exactly there. EXPIRED is on top of the shared\n // set: it may be revived by a late deposit — the package's own design —\n // which requires re-surfacing the address, or the user has no means to\n // effect the revival. From DEPOSIT_PROCESSING onward the funds have been\n // observed, so prompting another transfer would double-spend.\n //\n // A steps-only execution spends the intermediary's existing balance and\n // never has a deposit leg, whatever its status reads.\n const stepsOnly = isStepsOnlyExecution(execution);\n\n let needsDeposit =\n !stepsOnly &&\n (AWAITING_FUNDS_STATUSES.includes(execution.status) ||\n execution.status === 'EXPIRED');\n\n if (needsSigning) {\n if (stepsOnly) {\n validateStepsExecution(execution);\n } else {\n validatePreparedExecution(execution);\n }\n\n const validate =\n depositOptions?.validateExecution ??\n state.executionValidators.get(execution.id);\n\n await validate?.(execution);\n // ANDed, never overwritten: /submit's answer distinguishes \"still needs\n // a deposit\" from \"out-operation, nothing to deposit\" — it cannot\n // re-enable the transfer for an execution whose funds were already\n // observed before the signature (the double-spend the initialisation\n // above rules out).\n needsDeposit = (await signAndSubmit(ctx, execution)) && needsDeposit;\n }\n\n if (needsDeposit && execution.quote?.depositAddress) {\n // Same-session resume: this runner created the execution and still\n // holds its plan, so the wallet deposit itself can be replayed — the\n // recovery path for \"rejected the signature, trying again\".\n const drivenHere = state.activePlanExecutionId === execution.id;\n\n // A deposit this runner already broadcast must never be sent again,\n // whatever the status now reads: DEPOSIT_PENDING means the watcher has\n // not caught up, and EXPIRED means the deadline passed first — the very\n // state a late deposit revives. Keyed on the broadcast itself rather\n // than on a list of statuses, so a new awaiting-funds status cannot\n // silently reopen the window.\n const alreadySent = state.depositSentExecutionIds.has(execution.id);\n\n // Without that local record the two cases are indistinguishable from\n // the status alone — a reload loses it — so a cross-session resume needs\n // the caller to say the transfer is safe to (re-)send. CREATED is\n // exempt: it is unsigned, so no deposit can have been made yet.\n const needsSendPermission =\n !drivenHere &&\n execution.status !== 'CREATED' &&\n depositOptions?.depositViaWallet !== true;\n\n const depositMayBeInFlight = alreadySent || needsSendPermission;\n\n // `depositViaWallet: false` is an UNCONDITIONAL opt-out, so it gates the\n // retained plan as well as the rebuilt one. `buildResumeDepositPlan`\n // honours it on its own; without the same gate here, a caller switching a\n // same-session execution to the QR / exchange path would still be\n // prompted for a wallet transfer, because the retained plan carries the\n // original run's `depositViaWallet: true`.\n const optedOutOfWalletDeposit =\n depositOptions?.depositViaWallet === false;\n\n let plan =\n drivenHere && !optedOutOfWalletDeposit ? state.activePlan : undefined;\n\n if (!plan) {\n // Cross-session resume: the plan is gone (page reload), but the\n // deposit leg can usually be rebuilt from the execution itself.\n const rebuilt = buildResumeDepositPlan(execution, depositOptions);\n\n if (rebuilt && findTransfer(ctx, rebuilt.originChain)) {\n plan = rebuilt;\n }\n }\n\n if (plan && !depositMayBeInFlight) {\n // Retained so a failed transfer stays retryable via retryDeposit().\n ctx.setActivePlan(plan, execution.id);\n\n await awaitDeposit(ctx, plan, execution);\n } else {\n // No plan to drive a transfer from, or one that must not be driven\n // unprompted — surface the address instead. The settle loop below\n // still watches for the deposit, so a transfer already in flight\n // completes normally; a caller that knows none was sent re-drives it\n // with `depositViaWallet: true`.\n // exposeDepositAddress derives the origin chain from the execution\n // (or the SIGNING_STANDARD_CHAINS fallback) and enforces the memo\n // guard itself.\n exposeDepositAddress(ctx, execution);\n }\n }\n\n return await settle(ctx, execution.id);\n } catch (error) {\n return fail(ctx, error);\n }\n};\n","import type { Execution } from '@/types/execution';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport { awaitDeposit } from '@/runner/stages/deposit';\nimport { fail } from '@/runner/stages/fail';\nimport { settle } from '@/runner/stages/settle';\n\n/**\n * Retries the deposit transfer after the wallet prompt was rejected or\n * failed (`DepositTransferError`). The execution is still valid and signed\n * server-side; nothing before the transfer is repeated.\n */\nexport const retryDeposit = async (ctx: RunnerCtx): Promise<Execution> => {\n const { machine, state, patch } = ctx;\n const { execution } = machine.context;\n const { activePlan } = state;\n\n if (!activePlan || !execution) {\n throw new Error(\n 'nothing to retry — retryDeposit() applies only after run() stopped at the deposit transfer',\n );\n }\n\n if (machine.current !== 'awaiting-deposit') {\n throw new Error(\n `retryDeposit() requires the awaiting-deposit phase (current: ${machine.current})`,\n );\n }\n\n // The failure being retried is superseded the moment the user retries —\n // a UI keys its error line and recovery controls off `context.error`, and\n // keeping it makes a running retry look still-failed. run() and resume()\n // get this for free from prepareForNewFlow(); retry keeps the machine\n // state by design, so the error is cleared explicitly.\n patch({ error: undefined });\n\n try {\n await awaitDeposit(ctx, activePlan, execution);\n\n return await settle(ctx, execution.id);\n } catch (error) {\n return fail(ctx, error);\n }\n};\n","/**\n * Settlement capture for promises that are fired early and consumed later.\n *\n * A background round-trip started before its consumer is reached must never\n * become an unhandled rejection when the flow dies elsewhere first — so both\n * outcomes are folded into a value the consumer unwraps at its own await. The\n * `ok` tag is an explicit discriminant on purpose: key-presence checks break\n * silently the day a payload legitimately carries an `error` field.\n */\nexport type Captured<T> =\n | { ok: true; value: T }\n | { ok: false; error: unknown };\n\nexport const capture = <T>(promise: Promise<T>): Promise<Captured<T>> =>\n promise.then(\n (value) => ({ ok: true as const, value }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n\n/** Rethrows a captured rejection at the consumer's own await site. */\nexport const unwrap = <T>(captured: Captured<T>): T => {\n if (!captured.ok) {\n throw captured.error;\n }\n\n return captured.value;\n};\n","import { signIntentsConnectText } from '@/signers/intentsConnect';\nimport type { RunnerCtx } from '@/runner/ctx';\n\nexport const cancel = async (ctx: RunnerCtx, executionId?: string) => {\n const { api, machine, state, getWallet, requireAddress, patch, to } = ctx;\n\n // dispose()'s contract — no further wallet or API side effect — binds\n // cancel too: a disposed runner's owner has been rebound, so prompting a\n // delete signature or deleting server-side would act for the wrong context.\n ctx.throwIfDisposed();\n\n const id = executionId ?? machine.context.executionId;\n\n if (!id) {\n throw new Error('no execution to cancel');\n }\n\n const activeWallet = getWallet();\n\n // Flagged before the wallet is touched and cleared in the `finally` below,\n // so a UI can label the prompt it is about to show — the phase alone\n // cannot say it, since cancelling interrupts whatever phase was current.\n patch({ isCancelling: true });\n\n try {\n const envelope = await signIntentsConnectText({\n text: `delete_execution:${id}`,\n standard: activeWallet.signingStandard,\n address: requireAddress(),\n providers: activeWallet.getProviders(),\n decodePublicKey: activeWallet.decodePublicKey?.bind(activeWallet),\n });\n\n // The wallet prompt can sit open across a dispose(); a signature approved\n // after it must not be turned into a server-side delete on behalf of the\n // rebound context — the same checkpoint every other stage places right\n // before its side effect.\n ctx.throwIfDisposed();\n\n // Flagged BEFORE the delete round-trip so any concurrent stage — the poll\n // loop, a pending signature submit, a pending transfer — stops at its next\n // checkpoint. Rolled back if the delete fails, so a live run is not halted\n // for an execution that still exists.\n const wasAlreadyCancelled = state.cancelledExecutionIds.has(id);\n\n state.cancelledExecutionIds.add(id);\n\n try {\n await api.deleteExecution(requireAddress(), id, envelope);\n } catch (error) {\n if (!wasAlreadyCancelled) {\n state.cancelledExecutionIds.delete(id);\n }\n\n throw error;\n }\n\n // The cancelled execution's plan must not survive it: a later resume()\n // matching on a recycled id would otherwise replay a transfer for an\n // execution that no longer exists.\n ctx.clearActivePlanFor(id);\n\n // The machine cleanup below describes THIS runner's execution — it must\n // not run when an explicit id targets some other execution (a stale one\n // from an earlier session, cancelled while this runner drives a live\n // one). The delete already happened either way; only the local state is\n // ownership-gated. An empty context.executionId counts as ownership only\n // while NO flow is in flight: then the runner never recorded one (e.g.\n // the in-flight preflight failed before create) and the cancel IS this\n // runner's recovery — but a live flow that has not reached create() yet\n // also has no id, and wiping its context mid-planning would report a run\n // as cancelled while it keeps executing.\n const ownsMachineState =\n machine.context.executionId === id ||\n (machine.context.executionId === undefined && !state.flowInFlight);\n\n if (!ownsMachineState) {\n return;\n }\n\n // The delete is final, so any polling loop can be woken to hit its\n // cancelled checkpoint right away. Only after the delete: waking earlier\n // would kill the loop for a delete that might still fail and roll back.\n ctx.wakeAllSleepers();\n\n // Nothing that DESCRIBES the deleted execution may outlive it. A UI keys\n // its recovery actions off `error` and renders `status` / `networkFee` /\n // the deposit address, all of which now refer to something that no longer\n // exists server-side — a cancelled execution reporting `status: CREATED`\n // is simply false. `executionId` stays, so a UI can still name what was\n // cancelled, as does `intermediary`, which is per wallet rather than per\n // execution. Only needed on the legal-transition path; the reset below\n // clears everything on the terminal-phase path.\n patch({\n error: undefined,\n execution: undefined,\n status: undefined,\n networkFee: undefined,\n spendable: undefined,\n bakedAmount: undefined,\n depositAddress: undefined,\n depositMemo: undefined,\n deadline: undefined,\n depositTxHash: undefined,\n hasSubmittedSignature: false,\n });\n\n // `to` refuses the move when the machine sits in a terminal phase — the\n // common case being `failed` after the EXECUTION_IN_FLIGHT guard, where\n // the execution being cancelled blocks a run this runner never started.\n // The delete succeeded either way, so the stale terminal state (and the\n // guard error a UI keys its recovery controls on) must not outlive it:\n // reset to a clean idle so the next run starts unblocked.\n if (!to('cancelled')) {\n ctx.resetToIdle();\n }\n } finally {\n patch({ isCancelling: false });\n }\n};\n","import { failGuard, isUserRejection } from '@/errors';\nimport type { Execution, Intermediary } from '@/types/execution';\nimport { isSupportedSigningStandard } from '@/types/signing';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport { cancel } from '@/runner/stages/cancel';\nimport { signAndSubmit } from '@/runner/stages/signAndSubmit';\n\n/** GET /intermediary, patched into the flow's context if it is still live. */\nexport const resolveIdentity = async (\n ctx: RunnerCtx,\n): Promise<Intermediary> => {\n const { api, machine, state, getWallet, requireAddress, to, patch } = ctx;\n\n to('resolving-identity');\n\n // capture()d by the flow, so this round-trip can outlive it when planning\n // dies before unwrapping it. Every reset installs a fresh context object,\n // so its identity pins the patch to THIS flow — a late response must not\n // write into a later flow's (or a disposed runner's) context.\n const flowContext = machine.context;\n\n const intermediary = await api.getIntermediary(requireAddress(), {\n publicKey: getWallet().getPublicKey?.(),\n });\n\n if (machine.context === flowContext && !state.disposed) {\n patch({ intermediary });\n }\n\n return intermediary;\n};\n\n/**\n * The connector's standard must be signable BEFORE anything is created: a\n * real create for a standard we cannot sign (ton_connect, tip191) would\n * strand an execution holding the in-flight lock.\n */\nexport const assertSignableStandard = (ctx: RunnerCtx) => {\n const { signingStandard } = ctx.getWallet();\n\n if (!isSupportedSigningStandard(signingStandard)) {\n failGuard(\n 'UNSUPPORTED_SIGNING_STANDARD',\n `this package cannot sign ${String(signingStandard)} yet — refusing to create an execution it could never complete`,\n );\n }\n};\n\n/**\n * `signAndSubmit`, plus the recovery for a rejected prompt.\n *\n * A rejected signing prompt means the user abandoned THIS attempt — but the\n * created execution still holds the per-wallet in-flight lock. Best effort:\n * offer the delete signature right away so the next flow starts clean instead\n * of tripping EXECUTION_IN_FLIGHT and demanding a resume-or-cancel decision.\n * Declining that second prompt (or any delete failure) falls back to the\n * normal recovery, with the ORIGINAL rejection as the recorded error either\n * way.\n */\nexport const signAndSubmitOrCancel = async (\n ctx: RunnerCtx,\n execution: Execution,\n): Promise<boolean> => {\n try {\n return await signAndSubmit(ctx, execution);\n } catch (error) {\n if (ctx.autoCancelOnSignatureRejection && isUserRejection(error)) {\n try {\n await cancel(ctx, execution.id);\n } catch (cancelError) {\n ctx.logger.warn(\n 'auto-cancel after a rejected signature failed — the execution still holds the in-flight lock',\n cancelError,\n );\n }\n }\n\n throw error;\n }\n};\n","import {\n EVM_CHAIN_IDS,\n isEvmChain,\n PUBLIC_KEY_REQUIRED_CHAINS,\n} from '@/chains';\nimport { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type {\n ExecutionType,\n FeeStrategy,\n Intermediary,\n PreparedSteps,\n SolanaStep,\n Step,\n} from '@/types/execution';\nimport type { WalletConnector } from '@/types/wallet';\nimport type { AnyRecipe, StepContext } from '@/types/recipe';\nimport type {\n CreateExecutionBody,\n CreateStepsExecutionBody,\n} from '@/api/types';\nimport { DEFAULT_QUOTE_DEADLINE_MS } from '@/runner/constants';\nimport type { ExecutionPlan, StepsPlan } from '@/runner/types';\n\n/**\n * What the recipe-level helpers below actually read. Both `ExecutionPlan` and\n * `StepsPlan` satisfy it, so one implementation serves both flows.\n */\nexport type RecipePlan<TParams> = {\n recipe: AnyRecipe<TParams>;\n params: TParams;\n};\n\n/** Post-fee input, rounded down so fixed instructions never spend the reserve. */\nexport const getSpendableAmount = (\n minimum: string,\n feeStrategy?: FeeStrategy,\n): string => {\n const reserve =\n feeStrategy?.kind === 'threeRound'\n ? (feeStrategy.amountReserveBps ?? 0)\n : 0;\n\n if (!Number.isInteger(reserve) || reserve < 0 || reserve >= 10_000) {\n return failGuard(\n 'STRATEGY_CONFLICT',\n 'amountReserveBps must be an integer between 0 and 9999',\n );\n }\n\n const amount = (BigInt(minimum) * BigInt(10_000 - reserve)) / 10_000n;\n\n if (amount <= 0n) {\n return failGuard(\n 'FEE_EXCEEDS_AMOUNT',\n 'No spendable amount remains after fees and the quote movement reserve',\n );\n }\n\n return amount.toString();\n};\n\n/**\n * Exhaustive on purpose: `Intermediary` already names more account types\n * (near, stellar, tron, ton), so when `ExecutionType` grows, this switch is a\n * compile error instead of silently handing the new type the EVM account.\n */\nconst intermediaryAccountFor = (\n type: ExecutionType,\n intermediary: Intermediary,\n): string | null => {\n switch (type) {\n case 'evm':\n return intermediary.evm;\n case 'solana':\n return intermediary.solana;\n default: {\n const unhandled: never = type;\n\n throw new Error(\n `no intermediary account mapping for execution type ${String(unhandled)}`,\n );\n }\n }\n};\n\n/**\n * The intermediary account the steps execute against is per execution TYPE:\n * solana steps need the solana account (ATA derivation requires a concrete\n * base58 address), and it may legitimately be null when the feature is off.\n */\nexport const pickIntermediaryAddress = <TParams>(\n plan: RecipePlan<TParams>,\n intermediary: Intermediary,\n): string => {\n const address = intermediaryAccountFor(plan.recipe.type, intermediary);\n\n if (!address) {\n return failGuard(\n 'NO_INTERMEDIARY',\n `the service returned no ${plan.recipe.type} intermediary account for this wallet`,\n );\n }\n\n return address;\n};\n\n/**\n * Fills in an EVM origin's chain id from the built-in registry, exactly as\n * `buildResumeDepositPlan` already does for a resume.\n *\n * `originChainId` reads as guard-only, but it is also forwarded to the deposit\n * transfer as `evmChainId`, and the EVM path REFUSES to run without one — so an\n * omitted id used to strand the execution after the signature, with\n * `retryDeposit()` replaying the identical failure forever. Defaulting it here,\n * before planning, also arms the network-mismatch guard, which turns a\n * wrong-network wallet into a failure BEFORE anything is created.\n *\n * `null` is treated as absent rather than as an opt-out, matching the `??` the\n * resume path uses: a chain the registry does not know still resolves to\n * `undefined` and skips the guard.\n */\nexport const withOriginChainId = <TParams>(\n plan: ExecutionPlan<TParams>,\n): ExecutionPlan<TParams> =>\n plan.originChainId != null || !isEvmChain(plan.originChain)\n ? plan\n : { ...plan, originChainId: EVM_CHAIN_IDS[plan.originChain] };\n\n/** The API requires `quote.deadline`; default it rather than 400. */\nexport const withQuoteDeadline = <TParams>(\n plan: ExecutionPlan<TParams>,\n): ExecutionPlan<TParams> =>\n plan.quote.deadline\n ? plan\n : {\n ...plan,\n quote: {\n ...plan.quote,\n deadline: new Date(\n Date.now() + DEFAULT_QUOTE_DEADLINE_MS,\n ).toISOString(),\n },\n };\n\nexport const buildBody = <TParams>(\n getWallet: () => WalletConnector,\n plan: ExecutionPlan<TParams>,\n prepared: PreparedSteps,\n dry: boolean,\n): CreateExecutionBody => ({\n version: '1.0',\n type: plan.recipe.type,\n quote: plan.quote,\n steps: prepared.steps,\n ...(prepared.addressLookupTables?.length\n ? { addressLookupTables: prepared.addressLookupTables }\n : {}),\n metadata: {\n title: plan.recipe.title,\n intent: plan.recipe.intent,\n ...(plan.prepared?.spendable\n ? { intentsConnectSpendable: plan.prepared.spendable }\n : {}),\n },\n dry,\n publicKey: PUBLIC_KEY_REQUIRED_CHAINS.has(plan.originChain)\n ? getWallet().getPublicKey?.()\n : undefined,\n});\n\n/**\n * Steps-only body. No quote, no origin: the intermediary already holds the\n * funds. `destinationAsset` names the token the fee is charged in.\n *\n * Two metadata markers travel with the execution so a cross-session\n * `resume()` can recognise it without the plan: `intentsConnectFlow`\n * (older deployments omit `executionMode`) and `intentsConnectFeeBudget`\n * (re-checked against the real fee before an unsigned execution is signed).\n */\nexport const buildStepsBody = <TParams>(\n plan: StepsPlan<TParams>,\n prepared: PreparedSteps,\n dry: boolean,\n extra: { feeBudget?: string } = {},\n): CreateStepsExecutionBody => ({\n version: '1.0',\n type: plan.recipe.type,\n destinationAsset: plan.recipe.destination.assetId,\n steps: prepared.steps,\n ...(prepared.addressLookupTables?.length\n ? { addressLookupTables: prepared.addressLookupTables }\n : {}),\n metadata: {\n title: plan.recipe.title,\n intent: plan.recipe.intent,\n intentsConnectFlow: 'steps-only',\n ...(extra.feeBudget ? { intentsConnectFeeBudget: extra.feeBudget } : {}),\n },\n dry,\n});\n\nexport const validateSteps = <TParams>(\n plan: RecipePlan<TParams>,\n prepared: PreparedSteps,\n): PreparedSteps => {\n const { steps, addressLookupTables } = prepared;\n\n guards.stepShapeIsLegal(steps, plan.recipe.type);\n\n if (plan.recipe.type === 'solana') {\n guards.solanaStepsAreLegal(steps as SolanaStep[], addressLookupTables);\n } else {\n guards.destinationTokenIsTouched(\n steps as Step[],\n plan.recipe.destination.tokenAddress,\n );\n\n if (addressLookupTables?.length) {\n failGuard(\n 'ILLEGAL_STEP_SHAPE',\n 'Lookup tables are only supported for Solana',\n );\n }\n }\n\n return prepared;\n};\n\nexport const prepareRecipeSteps = async <TParams>(\n plan: RecipePlan<TParams>,\n context: StepContext,\n): Promise<PreparedSteps> => {\n const prepared =\n plan.recipe.type === 'solana'\n ? await plan.recipe.buildSteps(context, plan.params)\n : { steps: plan.recipe.buildSteps(context, plan.params) };\n\n return validateSteps(plan, prepared);\n};\n","import { failGuard, GuardError, IntentsConnectApiError } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport {\n type Execution,\n IN_FLIGHT_STATUSES,\n type PreparedSteps,\n} from '@/types/execution';\nimport type { Captured } from '@/runner/capture';\nimport type { RunnerCtx } from '@/runner/ctx';\n\n/**\n * What differs between a bridge-in and a steps-only real create. Everything\n * else in `create()` — the in-flight preflight, the 409 translation, the\n * post-create bookkeeping and the guard re-wrap — is shared.\n */\nexport type CreateRequest = {\n prepared: PreparedSteps;\n /** The `dry: false` API call, body already built. */\n submit: (address: string) => Promise<Execution>;\n /**\n * Funding acceptance for the created execution, run before the signing\n * payload is checked: bridge-in compares the guaranteed amount with the\n * baked one; steps-only checks the fee against its budget.\n */\n accept?: (execution: Execution) => void;\n /** Application-level acceptance, retained for a same-session resume. */\n validateExecution?: (execution: Execution) => void | Promise<void>;\n};\n\nexport const create = async (\n ctx: RunnerCtx,\n request: CreateRequest,\n /**\n * The in-flight preflight, started by the flow alongside identity\n * resolution so it does not add a serial round-trip right before the wallet\n * prompt. Captured, so a flow that dies earlier cannot turn a lost preflight\n * into an unhandled rejection; absent, `create` lists inline.\n */\n preflight?: Promise<Captured<Execution[]>>,\n): Promise<Execution> => {\n const { api, requireAddress, to, patch, emit, machine } = ctx;\n\n to('creating');\n\n guards.stepsRequiredForRealCreate(request.prepared.steps);\n\n const address = requireAddress();\n\n const listInFlight = () =>\n api.listExecutions(address, { status: IN_FLIGHT_STATUSES });\n\n // Pre-empt the 409 in-flight lock with an actionable local error. Every\n // status the service still holds the lock for has to be queried, not just\n // CREATED — a deposited-but-unsettled execution holds it too.\n let inFlight: Execution[];\n\n if (preflight) {\n const captured = await preflight;\n\n // The captured snapshot is as old as planning took (threeRound: two dry\n // rounds). A transient failure inside it must not fail a create the\n // server would accept — list fresh instead of rethrowing a stale error.\n inFlight = captured.ok ? captured.value : await listInFlight();\n\n // Symmetrically, an execution the snapshot saw open may have reached a\n // terminal status since. Re-confirm before failing a run the server would\n // accept — the extra round-trip only ever runs on the would-fail path,\n // and best effort: a transient failure keeps the snapshot, so the\n // actionable EXECUTION_IN_FLIGHT guard (its meta.executionId drives the\n // resume-or-cancel recovery) is not replaced by a generic network error.\n if (captured.ok && inFlight.length > 0) {\n try {\n inFlight = await listInFlight();\n } catch {\n // Keep the snapshot.\n }\n }\n } else {\n inFlight = await listInFlight();\n }\n\n guards.noExecutionInFlight(inFlight);\n ctx.throwIfDisposed();\n\n let execution: Execution;\n\n try {\n execution = await request.submit(address);\n } catch (error) {\n if (error instanceof IntentsConnectApiError && error.isExecutionInFlight) {\n // The preflight raced: another create won between its check and ours.\n // Best effort, re-list and rethrow through the SAME guard the preflight\n // uses, so both EXECUTION_IN_FLIGHT paths carry the identical message\n // and `meta.executionId` — recovery (resume-or-cancel) derives from the\n // meta, and without it a UI gets a dead-end failure.\n let open: Execution | undefined;\n\n try {\n [open] = await listInFlight();\n } catch {\n // Fall through to the message-only guard error.\n }\n\n if (open) {\n guards.noExecutionInFlight([open]);\n }\n\n return failGuard('EXECUTION_IN_FLIGHT', error.message);\n }\n\n throw error;\n }\n\n // Recorded BEFORE the post-create guards: the execution now exists\n // server-side and holds the in-flight lock, so if a guard below throws,\n // the id must already be in context for `cancel()` to clear it.\n patch({\n execution,\n executionId: execution.id,\n status: execution.status,\n networkFee: execution.details.networkFee ?? machine.context.networkFee,\n });\n\n emit({ type: 'created', executionId: execution.id });\n\n if (request.validateExecution) {\n ctx.state.executionValidators.set(execution.id, request.validateExecution);\n }\n\n try {\n request.accept?.(execution);\n await request.validateExecution?.(execution);\n ctx.assertLive(execution.id);\n\n guards.mustHaveSigningPayload(execution);\n } catch (error) {\n if (error instanceof GuardError) {\n throw new GuardError(\n error.code,\n `${error.message} — execution ${execution.id} was created and holds the in-flight lock; cancel('${execution.id}') clears it`,\n // Forwarded, never rebuilt: the re-wrap only appends context to the\n // message, so dropping the original guard's structured meta would\n // silently downgrade a UI's recovery actions to prose parsing.\n error.meta,\n );\n }\n\n throw error;\n }\n\n return execution;\n};\n","import { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport {\n BACKEND_PLACEHOLDERS,\n type FeeStrategy,\n type PreparedSteps,\n} from '@/types/execution';\nimport { DEFAULT_FEE_STRATEGY } from '@/runner/constants';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport {\n buildBody,\n getSpendableAmount,\n prepareRecipeSteps,\n validateSteps,\n} from '@/runner/planHelpers';\nimport type { ExecutionPlan } from '@/runner/types';\nimport { getQuoteSpendable } from '@/runner/quoteAmounts';\n\nexport const planSteps = async <TParams>(\n ctx: RunnerCtx,\n plan: ExecutionPlan<TParams>,\n /**\n * Resolves to the intermediary address, supplied lazily so the threeRound\n * round-1 dry create (which takes no steps and no intermediary) can run\n * concurrently with the identity round-trip instead of after it.\n */\n resolveIntermediaryAddress: () => Promise<string>,\n): Promise<PreparedSteps> => {\n const { api, getWallet, requireAddress, to, patch, emit, logger } = ctx;\n\n to('planning');\n\n const { recipe } = plan;\n const feeStrategy: FeeStrategy =\n plan.feeStrategy ??\n (recipe.type === 'solana' ? { kind: 'threeRound' } : DEFAULT_FEE_STRATEGY);\n\n if (recipe.type === 'solana' && feeStrategy.kind !== 'threeRound') {\n failGuard(\n 'STRATEGY_CONFLICT',\n 'Solana bridge-in preparation requires concrete amounts (threeRound)',\n );\n }\n\n const activeWallet = getWallet();\n\n // Bound to the connector so a class-based implementation keeps its `this`\n // when the guard invokes it bare. (The synchronous plan guards run earlier,\n // in run(), before any request is fired.)\n await guards.originNetworkMatches(\n activeWallet.getChainId?.bind(activeWallet),\n plan.originChainId,\n );\n\n if (plan.prepared) {\n if (plan.quote.deadline && Date.parse(plan.quote.deadline) <= Date.now()) {\n failGuard(\n 'QUOTE_MOVED',\n 'The prepared quote has expired; prepare a new preview',\n );\n }\n\n const prepared = structuredClone(plan.prepared);\n const intermediary = await resolveIntermediaryAddress();\n\n ctx.throwIfDisposed();\n const sameQuote = Object.keys({ ...prepared.quote, ...plan.quote }).every(\n (key) =>\n prepared.quote[key as keyof typeof prepared.quote] ===\n plan.quote[key as keyof typeof plan.quote],\n );\n\n if (\n prepared.walletAddress !== requireAddress() ||\n prepared.intermediary !== intermediary ||\n !sameQuote\n ) {\n failGuard(\n 'QUOTE_MOVED',\n 'The preview belongs to a different wallet or quote; prepare a new preview',\n );\n }\n\n patch({ bakedAmount: prepared.spendable, spendable: prepared.spendable });\n guards.strategiesAreExclusive(feeStrategy, prepared.steps);\n\n return validateSteps(plan, prepared);\n }\n\n // Strategy A — one round. The service substitutes the post-fee amount.\n if (feeStrategy.kind === 'placeholder') {\n const base = {\n intermediary: await resolveIntermediaryAddress(),\n userAddress: requireAddress(),\n };\n\n const steps = await prepareRecipeSteps(plan, {\n ...base,\n amount: BACKEND_PLACEHOLDERS.minAmountOut,\n });\n\n ctx.throwIfDisposed();\n\n guards.strategiesAreExclusive(feeStrategy, steps.steps);\n\n if (!guards.stepsUsePlaceholder(steps.steps)) {\n logger.warn(\n `recipe \"${recipe.id}\" ignored ctx.amount under the placeholder fee strategy, so the service has no amount to substitute — intended only if its amounts are deliberately fixed`,\n );\n }\n\n return validateSteps(plan, steps);\n }\n\n // Strategy B — three rounds, so an exact figure can be shown pre-signature.\n // Round 1 is step-less (steps: []): gas estimation only runs with non-empty\n // steps, so this is what yields an un-carved quote. It needs no\n // intermediary either, so it races the identity round-trip.\n const [gross, intermediaryAddress] = await Promise.all([\n api.createExecution(\n requireAddress(),\n buildBody(getWallet, plan, { steps: [] }, true),\n ),\n resolveIntermediaryAddress(),\n ]);\n\n const base = {\n intermediary: intermediaryAddress,\n userAddress: requireAddress(),\n };\n\n // Round 2 — real steps at the gross amount, which measures the fee.\n ctx.throwIfDisposed();\n const probe = await prepareRecipeSteps(plan, {\n ...base,\n amount: gross.quote.minAmountOut,\n });\n\n ctx.throwIfDisposed();\n\n guards.strategiesAreExclusive(feeStrategy, probe.steps);\n\n const measured = await api.createExecution(\n requireAddress(),\n buildBody(getWallet, plan, validateSteps(plan, probe), true),\n );\n\n ctx.throwIfDisposed();\n const networkFee = guards.feeMustBeEstimated(measured);\n\n if (recipe.type !== 'solana') {\n guards.amountMustExceedFee(gross.quote.minAmountOut, networkFee);\n }\n\n // Solana returns its fee separately; EVM has already carved it from the quote.\n const spendable = getSpendableAmount(\n getQuoteSpendable(measured),\n feeStrategy,\n );\n\n patch({ networkFee, spendable, bakedAmount: spendable });\n emit({ type: 'quoted', networkFee, spendable });\n\n // Round 3 steps, rebuilt at the carved amount. The invariant now holds:\n // spendable + networkFee <= the bridge's guaranteed delivery\n const final = await prepareRecipeSteps(plan, { ...base, amount: spendable });\n\n ctx.throwIfDisposed();\n guards.strategiesAreExclusive(feeStrategy, final.steps);\n\n return validateSteps(plan, final);\n};\n","import * as guards from '@/machine/guards';\nimport { type Execution, IN_FLIGHT_STATUSES } from '@/types/execution';\nimport { capture, unwrap } from '@/runner/capture';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport {\n assertSignableStandard,\n resolveIdentity,\n signAndSubmitOrCancel,\n} from '@/runner/identity';\nimport {\n buildBody,\n pickIntermediaryAddress,\n withOriginChainId,\n withQuoteDeadline,\n} from '@/runner/planHelpers';\nimport { create } from '@/runner/stages/create';\nimport { awaitDeposit } from '@/runner/stages/deposit';\nimport { fail } from '@/runner/stages/fail';\nimport { planSteps } from '@/runner/stages/planSteps';\nimport { settle } from '@/runner/stages/settle';\nimport { validatePreparedExecution } from '@/runner/stages/validatePreparedExecution';\nimport type { ExecutionPlan } from '@/runner/types';\n\nexport const run = async <TParams>(\n ctx: RunnerCtx,\n inputPlan: ExecutionPlan<TParams>,\n): Promise<Execution> => {\n ctx.prepareForNewFlow();\n\n try {\n assertSignableStandard(ctx);\n\n // Normalised ONCE, before anything reads it: the normalised plan is what\n // planning guards against, what the deposit transfer runs on, and what\n // `setActivePlan` retains for `retryDeposit()` / a same-session `resume()`.\n const plan = withOriginChainId(withQuoteDeadline(inputPlan));\n\n // Synchronous plan validation runs BEFORE any request is fired, so a\n // misconfigured recipe costs zero API calls (and zero per retry click).\n guards.recipientOnlyOnOutOperation(plan.recipe.flow, plan.quote.recipient);\n\n // Fired now and unwrapped inside create(): the preflight needs only the\n // address, so it runs alongside identity resolution and planning instead\n // of adding a serial round-trip right before the wallet prompt. Captured,\n // so a flow that dies earlier cannot turn a lost preflight into an\n // unhandled rejection.\n const inFlightPreflight = capture(\n ctx.api.listExecutions(ctx.requireAddress(), {\n status: IN_FLIGHT_STATUSES,\n }),\n );\n\n // Captured for the same reason. Planning only needs the intermediary from\n // round 2 of the threeRound protocol onward, so the resolver lets round 1\n // race it; a rejection re-surfaces at the resolver's await, which every\n // planning path reaches.\n const identity = capture(resolveIdentity(ctx));\n\n const steps = await planSteps(ctx, plan, async () =>\n pickIntermediaryAddress(plan, unwrap(await identity)),\n );\n\n // Save the amount beside the signed instructions so an unsigned resume\n // rechecks the same funding guarantee, including after a reload.\n const executionPlan = {\n ...plan,\n prepared: {\n ...steps,\n spendable: ctx.machine.context.bakedAmount,\n walletAddress: ctx.requireAddress(),\n intermediary: pickIntermediaryAddress(plan, unwrap(await identity)),\n quote: plan.quote,\n },\n };\n\n const execution = await create(\n ctx,\n {\n prepared: steps,\n submit: (address) =>\n ctx.api.createExecution(\n address,\n buildBody(ctx.getWallet, executionPlan, steps, false),\n ),\n accept: (created) =>\n validatePreparedExecution(created, ctx.machine.context.bakedAmount),\n validateExecution: plan.validateExecution,\n },\n inFlightPreflight,\n );\n\n // Retained only once an execution exists to bind it to. Assigning any\n // earlier would let a run() that dies in the guards — most commonly the\n // in-flight preflight, on a second click while a previous execution is\n // still open — clobber the plan that resume() needs to replay THAT\n // previous execution's deposit.\n ctx.setActivePlan(plan, execution.id);\n\n const needsDeposit = await signAndSubmitOrCancel(ctx, execution);\n\n if (needsDeposit) {\n await awaitDeposit(ctx, plan, execution);\n }\n\n return await settle(ctx, execution.id);\n } catch (error) {\n return fail(ctx, error);\n }\n};\n","import { failGuard } from '@/errors';\nimport { createExecutionMachine, moveTo } from '@/machine/machine';\nimport type { RunnerCtx } from '@/runner/ctx';\n\n/**\n * Deep-freezes a preview snapshot so a caller cannot edit the prepared steps\n * it later commits.\n */\nexport const freeze = <T>(value: T): T => {\n if (value && typeof value === 'object') {\n Object.values(value).forEach(freeze);\n Object.freeze(value);\n }\n\n return value;\n};\n\n/**\n * A planning context bound to a throw-away machine: previews reuse the\n * stages, but must never move the live machine or emit runner events.\n *\n * The address is pinned at creation: a wallet switch mid-preview fails the\n * preview instead of silently mixing two accounts' steps.\n */\nexport const createIsolatedCtx = (ctx: RunnerCtx): RunnerCtx => {\n ctx.throwIfDisposed();\n const address = ctx.requireAddress();\n const machine = createExecutionMachine();\n\n const requireAddress = () => {\n ctx.throwIfDisposed();\n\n if (ctx.requireAddress() !== address) {\n failGuard(\n 'WALLET_NOT_CONNECTED',\n 'Wallet changed while preparing the preview',\n );\n }\n\n return address;\n };\n\n return {\n ...ctx,\n machine,\n requireAddress,\n patch: (values) => {\n Object.assign(machine.context, values);\n },\n emit: () => undefined,\n to: (phase) => moveTo(machine, phase, { logger: ctx.logger }),\n };\n};\n","import { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type { Execution } from '@/types/execution';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport { createIsolatedCtx, freeze } from '@/runner/isolated';\nimport {\n buildBody,\n getSpendableAmount,\n pickIntermediaryAddress,\n prepareRecipeSteps,\n withOriginChainId,\n withQuoteDeadline,\n} from '@/runner/planHelpers';\nimport { planSteps } from '@/runner/stages/planSteps';\nimport { validatePreparedExecution } from '@/runner/stages/validatePreparedExecution';\nimport type { ExecutionPlan, ExecutionPreview } from '@/runner/types';\nimport { getQuoteSpendable } from '@/runner/quoteAmounts';\n\n/** An isolated planning machine: no real create, signatures, deposit, or live runner events. */\nexport const preview = async <TParams>(\n ctx: RunnerCtx,\n input: ExecutionPlan<TParams>,\n): Promise<ExecutionPreview<TParams>> => {\n const local = createIsolatedCtx(ctx);\n const { requireAddress, machine } = local;\n const address = requireAddress();\n\n const plan = withOriginChainId(\n withQuoteDeadline({\n ...input,\n quote: { ...input.quote },\n prepared: undefined,\n }),\n );\n\n guards.recipientOnlyOnOutOperation(plan.recipe.flow, plan.quote.recipient);\n\n local.to('resolving-identity');\n const intermediary = await ctx.api.getIntermediary(requireAddress(), {\n publicKey: ctx.getWallet().getPublicKey?.(),\n });\n\n const intermediaryAddress = pickIntermediaryAddress(plan, intermediary);\n let prepared = await planSteps(local, plan, async () => intermediaryAddress);\n\n let spendable = machine.context.bakedAmount;\n\n // A dry response can move while the caller fetches concrete instructions.\n // Rebuild only unsigned previews, at most twice; run() retains the accepted\n // steps verbatim and still refuses an underfunded real execution.\n const confirm = async (rebuildsLeft: number): Promise<Execution> => {\n guards.stepsRequiredForRealCreate(prepared.steps);\n const execution = await ctx.api.createExecution(\n requireAddress(),\n buildBody(ctx.getWallet, plan, prepared, true),\n );\n\n requireAddress();\n const currentSpendable =\n plan.recipe.type === 'solana' ? getQuoteSpendable(execution) : undefined;\n\n if (\n plan.recipe.type === 'solana' &&\n spendable !== undefined &&\n currentSpendable !== undefined &&\n BigInt(currentSpendable) < BigInt(spendable)\n ) {\n if (rebuildsLeft === 0) {\n return failGuard(\n 'QUOTE_MOVED',\n 'The bridge quote kept changing while preparing the swap; get a new quote',\n );\n }\n\n spendable = getSpendableAmount(currentSpendable, plan.feeStrategy);\n prepared = await prepareRecipeSteps(plan, {\n intermediary: intermediaryAddress,\n userAddress: requireAddress(),\n amount: spendable,\n });\n requireAddress();\n guards.strategiesAreExclusive({ kind: 'threeRound' }, prepared.steps);\n\n return confirm(rebuildsLeft - 1);\n }\n\n validatePreparedExecution(execution, spendable);\n\n return execution;\n };\n\n const execution = await confirm(2);\n\n return {\n execution,\n spendable,\n plan: {\n ...plan,\n prepared: freeze(\n structuredClone({\n ...prepared,\n walletAddress: address,\n intermediary: intermediaryAddress,\n quote: plan.quote,\n spendable,\n }),\n ),\n },\n };\n};\n","import { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type { Execution, FeeStrategy, PreparedSteps } from '@/types/execution';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport {\n buildStepsBody,\n getSpendableAmount,\n prepareRecipeSteps,\n validateSteps,\n} from '@/runner/planHelpers';\nimport type { StepsPlan } from '@/runner/types';\n\nexport type PlannedSteps = PreparedSteps & {\n /**\n * The fee the dry round reported. Absent only when the plan does not carve\n * the fee from `amount` AND the service did not estimate one — the steps\n * are still committable, the caller just cannot display a figure.\n */\n networkFee?: string;\n /** The amount baked into the steps. */\n spendable: string;\n /** Cap on the real create's fee; absent means any fee is accepted. */\n feeBudget?: string;\n /** The measuring dry response; absent when a `prepared` snapshot was reused. */\n execution?: Execution;\n};\n\n/** Steps-only steps carry literal amounts: there is no quote to substitute into. */\nconst LITERAL_AMOUNTS: FeeStrategy = { kind: 'threeRound' };\n\nconst reserveStrategy = <TParams>(plan: StepsPlan<TParams>): FeeStrategy => ({\n kind: 'threeRound',\n amountReserveBps:\n typeof plan.feeFromAmount === 'object'\n ? plan.feeFromAmount.amountReserveBps\n : undefined,\n});\n\n/**\n * The spendable amount once the fee is carved from `amount`, less the reserve.\n * Only meaningful when the fee is charged in the token the steps spend.\n */\nexport const spendableAfterFee = <TParams>(\n plan: StepsPlan<TParams>,\n networkFee: string,\n): string => {\n guards.amountMustExceedFee(plan.amount, networkFee);\n\n return getSpendableAmount(\n (BigInt(plan.amount) - BigInt(networkFee)).toString(),\n reserveStrategy(plan),\n );\n};\n\n/**\n * Whether a steps-only response's fee is acceptable for `plan`.\n *\n * Carving the fee from the spent amount needs the figure, so its absence is\n * a failed estimation. Otherwise the fee comes out of what the steps produce\n * and the service appends its transfer regardless, so a missing estimate only\n * costs the caller a displayable number — unless they capped it, in which\n * case a reported fee must fit the cap.\n */\nexport const checkStepsFee = <TParams>(\n plan: StepsPlan<TParams>,\n execution: Execution,\n budget: string | undefined,\n): string | undefined => {\n if (plan.feeFromAmount) {\n const fee = guards.feeMustBeEstimated(execution);\n\n if (budget !== undefined) {\n guards.feeWithinBudget(fee, budget);\n }\n\n return fee;\n }\n\n const fee = execution.details.networkFee;\n\n if (fee === undefined) {\n return undefined;\n }\n\n if (budget !== undefined) {\n guards.feeWithinBudget(guards.feeMustBeEstimated(execution), budget);\n }\n\n return fee;\n};\n\n/**\n * Plans a steps-only execution.\n *\n * One dry round measures the fee (there is no step-less estimation round:\n * the endpoint prices the steps themselves). When the fee comes out of the\n * spent token, the steps are rebuilt at the post-fee amount; otherwise the\n * caller's amount is final and only the optional fee cap applies.\n *\n * A `prepared` snapshot from `previewSteps()` skips all of that and is\n * committed verbatim, after checking it still describes this wallet, this\n * intermediary and this amount — and has not expired.\n */\nexport const planStepsOnly = async <TParams>(\n ctx: RunnerCtx,\n plan: StepsPlan<TParams>,\n intermediary: string,\n): Promise<PlannedSteps> => {\n const { api, requireAddress, to, patch, emit, logger } = ctx;\n\n to('planning');\n\n if (plan.recipe.flow !== 'steps-only') {\n failGuard(\n 'STRATEGY_CONFLICT',\n `recipe \"${plan.recipe.id}\" is a ${plan.recipe.flow} recipe — runSteps() drives steps-only recipes`,\n );\n }\n\n if (plan.prepared) {\n const prepared = structuredClone(plan.prepared);\n\n if (Date.parse(prepared.expiresAt) <= Date.now()) {\n failGuard(\n 'QUOTE_MOVED',\n 'The prepared steps preview has expired; prepare a new preview',\n );\n }\n\n if (\n prepared.walletAddress !== requireAddress() ||\n prepared.intermediary !== intermediary ||\n prepared.amount !== plan.amount\n ) {\n failGuard(\n 'QUOTE_MOVED',\n 'The preview belongs to a different wallet, intermediary or amount; prepare a new preview',\n );\n }\n\n guards.strategiesAreExclusive(LITERAL_AMOUNTS, prepared.steps);\n patch({\n networkFee: prepared.networkFee,\n spendable: prepared.spendable,\n bakedAmount: prepared.spendable,\n });\n\n return {\n ...validateSteps(plan, prepared),\n networkFee: prepared.networkFee,\n spendable: prepared.spendable,\n feeBudget: prepared.feeBudget,\n };\n }\n\n const base = { intermediary, userAddress: requireAddress() };\n\n // Round 1 — the steps at the gross amount, which measures the fee.\n const probe = await prepareRecipeSteps(plan, {\n ...base,\n amount: plan.amount,\n });\n\n ctx.throwIfDisposed();\n guards.strategiesAreExclusive(LITERAL_AMOUNTS, probe.steps);\n guards.stepsRequiredForRealCreate(probe.steps);\n\n const measured = await api.createStepsExecution(\n requireAddress(),\n buildStepsBody(plan, probe, true),\n );\n\n ctx.throwIfDisposed();\n\n let spendable = plan.amount;\n let feeBudget = plan.maxNetworkFee;\n let final = probe;\n const networkFee = checkStepsFee(plan, measured, feeBudget);\n\n if (plan.feeFromAmount && networkFee !== undefined) {\n // Round 2 — rebuilt at the carved amount, so `spendable + fee <= amount`.\n spendable = spendableAfterFee(plan, networkFee);\n feeBudget = (BigInt(plan.amount) - BigInt(spendable)).toString();\n final = await prepareRecipeSteps(plan, { ...base, amount: spendable });\n\n ctx.throwIfDisposed();\n guards.strategiesAreExclusive(LITERAL_AMOUNTS, final.steps);\n }\n\n patch({ networkFee, spendable, bakedAmount: spendable });\n\n if (networkFee !== undefined) {\n emit({ type: 'quoted', networkFee, spendable });\n } else {\n logger.warn(\n `steps-only dry create for recipe \"${plan.recipe.id}\" reported no networkFee — the service still appends its fee transfer, but no figure can be shown`,\n );\n }\n\n return { ...final, networkFee, spendable, feeBudget, execution: measured };\n};\n","import { failGuard } from '@/errors';\nimport * as guards from '@/machine/guards';\nimport type { Execution } from '@/types/execution';\nimport { DEFAULT_PREVIEW_TTL_MS } from '@/runner/constants';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport { createIsolatedCtx, freeze } from '@/runner/isolated';\nimport {\n buildStepsBody,\n pickIntermediaryAddress,\n prepareRecipeSteps,\n} from '@/runner/planHelpers';\nimport {\n type PlannedSteps,\n planStepsOnly,\n spendableAfterFee,\n} from '@/runner/stages/planStepsOnly';\nimport type { StepsPlan, StepsPreview } from '@/runner/types';\n\n/**\n * Dry preparation of a steps-only execution on an isolated machine: no real\n * create, no signature, no live runner events.\n *\n * The returned plan carries an immutable `prepared` snapshot that\n * `runSteps()` commits verbatim until `expiresAt`.\n */\nexport const previewSteps = async <TParams>(\n ctx: RunnerCtx,\n input: StepsPlan<TParams>,\n): Promise<StepsPreview<TParams>> => {\n const local = createIsolatedCtx(ctx);\n const { requireAddress } = local;\n const plan: StepsPlan<TParams> = { ...input, prepared: undefined };\n\n local.to('resolving-identity');\n const intermediary = await ctx.api.getIntermediary(requireAddress(), {\n publicKey: ctx.getWallet().getPublicKey?.(),\n });\n\n const intermediaryAddress = pickIntermediaryAddress(plan, intermediary);\n let planned = await planStepsOnly(local, plan, intermediaryAddress);\n\n // Only a fee carved from the spent amount changes the steps, so only that\n // shape needs a confirming dry at the amount actually baked in. Rebuild at\n // the new fee at most twice; runSteps() refuses an over-budget real create\n // regardless. Every other plan was fully priced by the measuring dry.\n const confirm = async (rebuildsLeft: number): Promise<Execution> => {\n const execution = await ctx.api.createStepsExecution(\n requireAddress(),\n buildStepsBody(plan, planned, true, { feeBudget: planned.feeBudget }),\n );\n\n requireAddress();\n const fee = guards.feeMustBeEstimated(execution);\n\n if (\n planned.feeBudget !== undefined &&\n BigInt(fee) > BigInt(planned.feeBudget)\n ) {\n if (rebuildsLeft === 0) {\n return failGuard(\n 'FEE_EXCEEDS_AMOUNT',\n `network fee (${fee}) exceeds the budget the steps were sized for (${planned.feeBudget}); get a new preview`,\n );\n }\n\n const spendable = spendableAfterFee(plan, fee);\n const rebuilt = await prepareRecipeSteps(plan, {\n intermediary: intermediaryAddress,\n userAddress: requireAddress(),\n amount: spendable,\n });\n\n requireAddress();\n guards.strategiesAreExclusive({ kind: 'threeRound' }, rebuilt.steps);\n\n planned = {\n ...rebuilt,\n networkFee: fee,\n spendable,\n feeBudget: (BigInt(plan.amount) - BigInt(spendable)).toString(),\n } satisfies PlannedSteps;\n\n return confirm(rebuildsLeft - 1);\n }\n\n return execution;\n };\n\n const execution = plan.feeFromAmount\n ? await confirm(2)\n : // Never undefined here: only the `prepared` path omits it, and this\n // preview cleared `prepared` above.\n planned.execution!;\n\n const {\n networkFee,\n spendable,\n feeBudget,\n execution: _measured,\n ...prepared\n } = planned;\n\n return {\n execution,\n networkFee,\n spendable,\n plan: {\n ...plan,\n prepared: freeze(\n structuredClone({\n ...prepared,\n walletAddress: requireAddress(),\n intermediary: intermediaryAddress,\n amount: plan.amount,\n spendable,\n networkFee,\n feeBudget,\n expiresAt: new Date(\n Date.now() + (plan.previewTtlMs ?? DEFAULT_PREVIEW_TTL_MS),\n ).toISOString(),\n }),\n ),\n },\n };\n};\n","import { type Execution, IN_FLIGHT_STATUSES } from '@/types/execution';\nimport { capture } from '@/runner/capture';\nimport type { RunnerCtx } from '@/runner/ctx';\nimport {\n assertSignableStandard,\n resolveIdentity,\n signAndSubmitOrCancel,\n} from '@/runner/identity';\nimport { buildStepsBody, pickIntermediaryAddress } from '@/runner/planHelpers';\nimport { create } from '@/runner/stages/create';\nimport { fail } from '@/runner/stages/fail';\nimport { checkStepsFee, planStepsOnly } from '@/runner/stages/planStepsOnly';\nimport { settle } from '@/runner/stages/settle';\nimport type { StepsPlan } from '@/runner/types';\n\n/**\n * Steps-only lifecycle: the intermediary already holds the funds, so there is\n * no quote and no deposit leg —\n *\n * resolving-identity → planning → creating → awaiting-signature\n * → submitting → settling → success | failed\n */\nexport const runSteps = async <TParams>(\n ctx: RunnerCtx,\n plan: StepsPlan<TParams>,\n): Promise<Execution> => {\n ctx.prepareForNewFlow();\n\n try {\n assertSignableStandard(ctx);\n\n // Fired now and unwrapped inside create(): see run() for why.\n const inFlightPreflight = capture(\n ctx.api.listExecutions(ctx.requireAddress(), {\n status: IN_FLIGHT_STATUSES,\n }),\n );\n\n const intermediary = pickIntermediaryAddress(\n plan,\n await resolveIdentity(ctx),\n );\n\n const planned = await planStepsOnly(ctx, plan, intermediary);\n const { feeBudget } = planned;\n\n const execution = await create(\n ctx,\n {\n prepared: planned,\n submit: (address) =>\n ctx.api.createStepsExecution(\n address,\n buildStepsBody(plan, planned, false, { feeBudget }),\n ),\n accept: (created) => {\n checkStepsFee(plan, created, feeBudget);\n },\n validateExecution: plan.validateExecution,\n },\n inFlightPreflight,\n );\n\n // /submit answers SIGNING (or an operation status) for an execution with\n // nothing to deposit; whatever it says, there is no deposit leg here.\n await signAndSubmitOrCancel(ctx, execution);\n\n return await settle(ctx, execution.id);\n } catch (error) {\n return fail(ctx, error);\n }\n};\n","import {\n ExecutionCancelledError,\n failGuard,\n RunnerDisposedError,\n} from '@/errors';\nimport { defaultLogger } from '@/logger';\nimport type { Context } from '@/machine/context';\nimport { createExecutionMachine, moveTo } from '@/machine/machine';\nimport { isTerminalPhase, type Phase } from '@/machine/phases';\nimport type { WalletConnector } from '@/types/wallet';\nimport {\n DEFAULT_MAX_POLL_ATTEMPTS,\n DEFAULT_POLL_INTERVAL_MS,\n DOOMED_FLOW_SETTLE_TIMEOUT_MS,\n} from '@/runner/constants';\nimport type { RunnerCtx, RunnerState } from '@/runner/ctx';\nimport type { DepositPlan } from '@/runner/depositPlan';\nimport { resume } from '@/runner/flows/resume';\nimport { retryDeposit } from '@/runner/flows/retryDeposit';\nimport { run } from '@/runner/flows/run';\nimport { preview } from '@/runner/flows/preview';\nimport { previewSteps } from '@/runner/flows/previewSteps';\nimport { runSteps } from '@/runner/flows/runSteps';\nimport { cancel } from '@/runner/stages/cancel';\nimport type {\n ExecutionPlan,\n ExecutionRunner,\n ExecutionRunnerOptions,\n ResumeDepositOptions,\n RunnerEvent,\n StepsPlan,\n} from '@/runner/types';\n\n/**\n * Whether `settling` resolved before the timeout. Never rejects, and always\n * clears its timer, so a settled flow cannot leave a pending handle keeping a\n * Node/SSR event loop alive.\n */\nconst settlesWithin = async (\n settling: Promise<void> | undefined,\n timeoutMs: number,\n): Promise<boolean> => {\n if (!settling) {\n return true;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n try {\n return await Promise.race([\n settling.then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n};\n\n/**\n * Assembles the runner: defaults the options, owns the machine and the\n * mutable {@link RunnerState}, and builds the {@link RunnerCtx} every stage\n * (`stages/*`) and flow (`flows/*`) receives. All lifecycle logic lives in\n * those modules; this file is only the wiring.\n */\nexport const createExecutionRunner = (\n options: ExecutionRunnerOptions,\n): ExecutionRunner => {\n const {\n api,\n wallet,\n plugins,\n pluginOptions,\n makeTransfer: makeTransferOverride,\n autoCancelOnSignatureRejection = true,\n logger = defaultLogger,\n pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,\n maxPollAttempts = DEFAULT_MAX_POLL_ATTEMPTS,\n onEvent,\n } = options;\n\n const machine = createExecutionMachine();\n\n // Resolved per use rather than captured once, so an accessor always yields the\n // current connector and optional members (`makeTransfer`, `decodePublicKey`)\n // are detected on the live object rather than a stale snapshot.\n const getWallet = (): WalletConnector =>\n typeof wallet === 'function' ? wallet() : wallet;\n\n const state: RunnerState = {\n cancelledExecutionIds: new Set(),\n depositSentExecutionIds: new Set(),\n executionValidators: new Map(),\n disposed: false,\n flowInFlight: false,\n flowSettled: undefined,\n wakeSleepers: new Set(),\n activePlan: undefined,\n activePlanExecutionId: undefined,\n };\n\n // Copied before iterating: each resolver removes itself from the set.\n const wakeAllSleepers = () => {\n [...state.wakeSleepers].forEach((wake) => wake());\n };\n\n /**\n * One flow at a time. The phase-based check in `prepareForNewFlow` cannot\n * cover `retryDeposit()`, whose legitimate entry phase (`awaiting-deposit`)\n * is also where a live flow holds while a transfer prompt is open or the QR\n * settle loop is polling — re-entering there would double-drive the same\n * execution (two wallet prompts for the same funds, twin settle loops).\n */\n const withFlowLock = async <T>(fn: () => Promise<T>): Promise<T> => {\n while (state.flowInFlight) {\n // A flow whose execution was cancelled is already unwinding — its\n // rejection just needs to finish propagating (or its in-flight poll to\n // return) before the lock frees. `await cancel()` followed by `run()`\n // is the sanctioned recovery, so wait the unwind out instead of failing\n // it; anything else in flight is a genuine concurrent flow.\n const drivingId = machine.context.executionId;\n\n const doomed =\n drivingId !== undefined && state.cancelledExecutionIds.has(drivingId);\n\n if (!doomed) {\n failGuard(\n 'EXECUTION_IN_FLIGHT',\n 'this runner is already driving an execution — wait for it, or cancel() it',\n drivingId ? { executionId: drivingId } : undefined,\n );\n }\n\n // BOUNDED. Nothing can abort a doomed flow parked on an open wallet\n // prompt — providers keep `personal_sign` / `eth_sendTransaction`\n // pending until the popup is dismissed — so an unbounded wait would\n // hang `await cancel(); run()` with no feedback at all. A timeout turns\n // that into the same actionable guard the non-doomed branch throws.\n // eslint-disable-next-line no-await-in-loop\n const settled = await settlesWithin(\n state.flowSettled,\n DOOMED_FLOW_SETTLE_TIMEOUT_MS,\n );\n\n if (!settled) {\n failGuard(\n 'EXECUTION_IN_FLIGHT',\n 'the cancelled execution has not released this runner yet — a wallet prompt from it is probably still open; dismiss it, or use another runner',\n drivingId ? { executionId: drivingId } : undefined,\n );\n }\n }\n\n state.flowInFlight = true;\n\n let release!: () => void;\n\n state.flowSettled = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n try {\n return await fn();\n } finally {\n state.flowInFlight = false;\n state.flowSettled = undefined;\n release();\n }\n };\n\n const emit = (event: RunnerEvent) => onEvent?.(event);\n\n const patch = (values: Partial<Context>) => {\n Object.assign(machine.context, values);\n };\n\n const to = (phase: Phase) =>\n moveTo(machine, phase, {\n logger,\n onMoved: (moved) => emit({ type: 'phase', phase: moved }),\n });\n\n const resetToIdle = () => {\n machine.reset();\n emit({ type: 'phase', phase: 'idle' });\n };\n\n const throwIfDisposed = () => {\n if (state.disposed) {\n throw new RunnerDisposedError(machine.context.executionId);\n }\n };\n\n const throwIfCancelled = (executionId: string) => {\n if (state.cancelledExecutionIds.has(executionId)) {\n throw new ExecutionCancelledError(executionId);\n }\n };\n\n const assertLive = (executionId: string) => {\n throwIfCancelled(executionId);\n throwIfDisposed();\n };\n\n /**\n * Refuses re-entry while an execution is being driven, then clears the\n * previous run's machine state. Without the reset, a retry after a terminal\n * phase would run invisibly (terminal phases have no outgoing transitions)\n * against stale context — e.g. a `bakedAmount` from a previous threeRound\n * run spuriously tripping the QUOTE_MOVED guard.\n */\n const prepareForNewFlow = () => {\n throwIfDisposed();\n\n if (machine.current !== 'idle' && !isTerminalPhase(machine.current)) {\n const { executionId } = machine.context;\n\n failGuard(\n 'EXECUTION_IN_FLIGHT',\n `this runner is already driving an execution (phase: ${machine.current}) — wait for it, cancel() it, or use another runner`,\n // Carried so `deriveExecutionRecovery` can offer resume-or-cancel\n // instead of a dead end — the guard's documented contract\n // (`GuardMeta.executionId`), which only `noExecutionInFlight` honoured.\n executionId ? { executionId } : undefined,\n );\n }\n\n machine.reset();\n state.cancelledExecutionIds.clear();\n };\n\n const requireAddress = (): string => {\n const address = getWallet().getAddress();\n\n if (!address) {\n return failGuard('WALLET_NOT_CONNECTED', 'no wallet is connected');\n }\n\n return address;\n };\n\n const setActivePlan = (plan: DepositPlan, executionId: string) => {\n state.activePlan = plan;\n state.activePlanExecutionId = executionId;\n };\n\n const clearActivePlanFor = (executionId: string) => {\n if (state.activePlanExecutionId === executionId) {\n state.activePlan = undefined;\n state.activePlanExecutionId = undefined;\n }\n };\n\n const ctx: RunnerCtx = {\n machine,\n state,\n api,\n logger,\n plugins,\n pluginOptions,\n makeTransferOverride,\n autoCancelOnSignatureRejection,\n pollIntervalMs,\n maxPollAttempts,\n getWallet,\n emit,\n patch,\n to,\n resetToIdle,\n wakeAllSleepers,\n requireAddress,\n throwIfDisposed,\n throwIfCancelled,\n assertLive,\n prepareForNewFlow,\n setActivePlan,\n clearActivePlanFor,\n };\n\n return {\n preview: <TParams>(plan: ExecutionPlan<TParams>) => preview(ctx, plan),\n run: <TParams>(plan: ExecutionPlan<TParams>) =>\n withFlowLock(() => run(ctx, plan)),\n previewSteps: <TParams>(plan: StepsPlan<TParams>) =>\n previewSteps(ctx, plan),\n runSteps: <TParams>(plan: StepsPlan<TParams>) =>\n withFlowLock(() => runSteps(ctx, plan)),\n resume: (executionId: string, resumeOptions?: ResumeDepositOptions) =>\n withFlowLock(() => resume(ctx, executionId, resumeOptions)),\n retryDeposit: () => withFlowLock(() => retryDeposit(ctx)),\n cancel: (executionId?: string) => cancel(ctx, executionId),\n dispose: () => {\n state.disposed = true;\n // Wake any in-flight polling sleep so the loop hits its disposed\n // checkpoint now, not after up to a full poll interval.\n wakeAllSleepers();\n },\n isDisposed: () => state.disposed,\n getPhase: () => machine.current,\n getStore: () => machine.getStore(),\n };\n};\n","import { DepositTransferError, GuardError } from '@/errors';\n\n/**\n * A recoverable dead-end, classified so a UI renders actions instead of prose.\n *\n * This is the interpretation contract for the runner's error taxonomy — every\n * consumer would otherwise re-derive it with `instanceof` chains, and less\n * completely. Derive it from the error the hook/runner reports:\n *\n * - `resume-or-cancel`: another execution holds the per-wallet in-flight lock\n * (`EXECUTION_IN_FLIGHT`). Offer `resume(executionId)` — which re-drives\n * whatever is left of that execution, signature and deposit included — or\n * `cancel(executionId)` to release the lock.\n * - `retry-transfer`: the deposit transfer was rejected or failed in the\n * wallet, everything before it is valid and signed server-side. Offer\n * `retryDeposit()`. `cause` names what actually broke in the wallet.\n *\n * `undefined` means the error (or its absence) has no dedicated recovery\n * action — render it as a plain failure.\n */\nexport type ExecutionRecovery =\n | { kind: 'resume-or-cancel'; executionId: string }\n | { kind: 'retry-transfer'; executionId: string; cause?: Error };\n\nexport const deriveExecutionRecovery = (\n error: unknown,\n): ExecutionRecovery | undefined => {\n if (\n error instanceof GuardError &&\n error.code === 'EXECUTION_IN_FLIGHT' &&\n error.meta.executionId\n ) {\n return { kind: 'resume-or-cancel', executionId: error.meta.executionId };\n }\n\n if (error instanceof DepositTransferError) {\n return {\n kind: 'retry-transfer',\n executionId: error.executionId,\n cause: error.cause instanceof Error ? error.cause : undefined,\n };\n }\n\n return undefined;\n};\n"],"names":["TERMINAL_STATUSES","IN_FLIGHT_STATUSES","AWAITING_FUNDS_STATUSES","MAX_STEPS","MAX_FUNCTION_SIGNATURE_BYTES","STEP_KEYS","BACKEND_PLACEHOLDERS","SUPPORTED_SIGNING_STANDARDS","ED25519_STANDARDS","isSupportedSigningStandard","standard","IntentsConnectError","message","options","toError","value","outer","inner","candidate","code","USER_REJECTION_PROSE","saysRejected","isUserRejection","innerObject","IntentsConnectApiError","status","body","ExecutionCancelledError","executionId","RunnerDisposedError","ExecutionPollTimeoutError","detail","DepositTransferError","GuardError","meta","failGuard","PREFIX","defaultLogger","args","noopLogger","createInitialContext","PHASE_TRANSITIONS","TERMINAL_PHASES","isTerminalPhase","phase","IN_FLIGHT_PHASES","isInFlightPhase","createExecutionMachine","store","proxy","machine","moveTo","logger","onMoved","DEFAULT_POLL_INTERVAL_MS","DEFAULT_MAX_POLL_ATTEMPTS","DEFAULT_FEE_STRATEGY","DEFAULT_QUOTE_DEADLINE_MS","DEPOSIT_DEADLINE_GRACE_MS","MAX_CONSECUTIVE_POLL_ERRORS","HOLDING_POLL_BACKOFF_FACTOR","MAX_HOLDING_POLL_INTERVAL_MS","DOOMED_FLOW_SETTLE_TIMEOUT_MS","DEFAULT_PREVIEW_TTL_MS","amountMustExceedFee","grossAmount","networkFee","destinationTokenIsTouched","steps","destinationTokenAddress","target","step","feeMustBeEstimated","execution","fee","feeWithinBudget","budget","EVM_CHAIN_IDS","EVM_CHAINS","MEMO_MODE_CHAINS","SIGNING_STANDARD_CHAINS","MEMO_FREE_SIGNING_STANDARDS","PUBLIC_KEY_REQUIRED_CHAINS","OMFT_SUFFIX","parseOriginAsset","assetId","rest","dash","chain","tokenAddress","isEvmChain","getChainFamily","memoPresentForStellar","originChain","memo","signingStandard","mustBeSignedBeforeDeposit","hasSubmittedSignature","mustHaveSigningPayload","payload","noExecutionInFlight","openExecutions","open","originNetworkMatches","getChainId","expectedChainId","actual","publicKeyMatchesStandard","publicKey","requiresPublicKey","quoteMustNotHaveMoved","bakedAmount","returnedMinAmountOut","recipientOnlyOnOutOperation","flow","recipient","hex","intermediary","legal","condition","isAddress","base58","keysAreLegal","keys","key","validateArg","arg","bits","signed","limit","solanaStepsAreLegal","addressLookupTables","account","ALLOWED_KEYS","stepShapeIsLegal","type","max","index","stepsRequiredForRealCreate","PLACEHOLDER","parameterUsesPlaceholder","parameter","stepsUsePlaceholder","strategiesAreExclusive","strategy","buildResumeDepositPlan","depositOptions","originAsset","origin","family","decimals","originChainId","swapType","findTransfer","deps","getWallet","plugins","pluginOptions","makeTransferOverride","activeWallet","walletTransfer","plugin","familyOptions","requireTransfer","exposeDepositAddress","ctx","deadline","originChainHint","to","patch","emit","namedOrigin","guards.memoPresentForStellar","guards.mustBeSignedBeforeDeposit","depositAddress","depositMemo","validUntil","awaitDeposit","plan","api","state","assertLive","amountAtomic","transfer","hash","error","fail","failure","sleep","ms","resolve","timer","wake","reconcileSettlePhase","current","settle","requireAddress","throwIfDisposed","throwIfCancelled","pollIntervalMs","maxPollAttempts","holdingForDeposit","address","deadlineMs","attempt","consecutiveErrors","holdInterval","next","withinDepositWindow","delayMs","expired","SIGNATURE_BYTE_LENGTH_ED25519","SIGNATURE_BYTE_LENGTH_SECP256K1","RECOVERY_BYTE_INDEX","fromBase64","base64","toBase64","bytes","toBase58","fromHex","normaliseRecoveryByte","signature","normalised","recovery","assertEd25519SignatureLength","label","secp256k1Signature","ed25519Signature","ed25519PublicKeyFromBytes","ed25519PublicKeyFromBase58","signErc191","provider","expectedAddress","resolved","accounts","signingAccount","signRawEd25519","providerPublicKey","signNep413","getProvider","expectedAccountId","wallet","nonce","rawSignature","signSep53","decodePublicKey","result","inBandError","signedMessage","signerAddress","requireProvider","parseNep413Payload","payloadJson","parsed","signIntentsConnectPayload","providers","NEP413_DELETE_RECIPIENT","NEP413_NONCE_BYTES","randomNonce","signIntentsConnectText","text","nonceBytes","signPayload","guards.mustHaveSigningPayload","signAndSubmit","envelope","guards.publicKeyMatchesStandard","getQuoteSpendable","guards.feeMustBeEstimated","minimum","guards.amountMustExceedFee","validatePreparedExecution","recorded","amount","guards.quoteMustNotHaveMoved","isStepsOnlyExecution","validateStepsExecution","guards.feeWithinBudget","resume","messageSigned","needsSigning","stepsOnly","needsDeposit","drivenHere","alreadySent","needsSendPermission","depositMayBeInFlight","optedOutOfWalletDeposit","rebuilt","retryDeposit","activePlan","capture","promise","unwrap","captured","cancel","id","wasAlreadyCancelled","resolveIdentity","flowContext","assertSignableStandard","signAndSubmitOrCancel","cancelError","getSpendableAmount","feeStrategy","reserve","intermediaryAccountFor","unhandled","pickIntermediaryAddress","withOriginChainId","withQuoteDeadline","buildBody","prepared","dry","buildStepsBody","extra","validateSteps","guards.stepShapeIsLegal","guards.solanaStepsAreLegal","guards.destinationTokenIsTouched","prepareRecipeSteps","context","create","request","preflight","guards.stepsRequiredForRealCreate","listInFlight","inFlight","guards.noExecutionInFlight","planSteps","resolveIntermediaryAddress","recipe","guards.originNetworkMatches","sameQuote","guards.strategiesAreExclusive","base","guards.stepsUsePlaceholder","gross","intermediaryAddress","probe","measured","spendable","final","run","inputPlan","guards.recipientOnlyOnOutOperation","inFlightPreflight","identity","executionPlan","created","freeze","createIsolatedCtx","values","preview","input","local","confirm","rebuildsLeft","currentSpendable","LITERAL_AMOUNTS","reserveStrategy","spendableAfterFee","checkStepsFee","planStepsOnly","feeBudget","previewSteps","planned","_measured","runSteps","settlesWithin","settling","timeoutMs","createExecutionRunner","autoCancelOnSignatureRejection","onEvent","wakeAllSleepers","withFlowLock","fn","drivingId","release","event","moved","resetToIdle","resumeOptions","deriveExecutionRecovery"],"mappings":";;AAqCO,MAAMA,KAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AACF,GASaC,IAAiD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAYaC,KAAsD;AAAA,EACjE;AAAA,EACA;AACF,GA4EaC,KAAqD;AAAA,EAChE,KAAK;AAAA,EACL,QAAQ;AACV,GAEaC,KAA+B,MAE/BC,KAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAGaC,IAAuB;AAAA,EAClC,cAAc;AAAA,EACd,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,UAAU;AACZ,GC7IMC,KAAmE;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAQaC,KAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAEaC,KAA6B,CACxCC,MAECH,GAA2D;AAAA,EAC1DG;AACF;ACnDK,MAAMC,UAA4B,MAAM;AAAA,EAC7C,YAAYC,GAAiBC,GAA+B;AAC1D,UAAMD,CAAO,GACb,KAAK,OAAO,uBAERC,GAAS,UAAU,WACrB,KAAK,QAAQA,EAAQ;AAAA,EAEzB;AACF;AAaO,MAAMC,KAAU,CAACC,MAA0B;AAChD,MAAIA,aAAiB;AACnB,WAAOA;AAGT,MAAI,OAAOA,KAAU,YAAYA,MAAU,MAAM;AAC/C,UAAMC,IAAQD,GAMRE,IACJ,OAAOD,EAAM,SAAU,YAAYA,EAAM,UAAU,OAC9CA,EAAM,QACP,QAGAJ,IADW,CAACI,EAAM,SAASC,GAAO,OAAO,EACtB;AAA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mW,MAC5BP,EAAa,MAAMlG,GAAOjH,GAAKzI,GAAamW,CAAa,CAAC;AAAA,IAC5D,cAAc,MAAMP,EAAa,MAAMvF,GAAa5H,CAAG,CAAC;AAAA,IACxD,QAAQ,CAACzI,MAAyB2Q,GAAOlI,GAAKzI,CAAW;AAAA,IACzD,SAAS,MAAM;AACb,MAAAwJ,EAAM,WAAW,IAGjBmM,EAAA;AAAA,IACF;AAAA,IACA,YAAY,MAAMnM,EAAM;AAAA,IACxB,UAAU,MAAMlI,EAAQ;AAAA,IACxB,UAAU,MAAMA,EAAQ,SAAA;AAAA,EAAS;AAErC,GCtRa8U,KAA0B,CACrCvM,MACkC;AAClC,MACEA,aAAiBxJ,KACjBwJ,EAAM,SAAS,yBACfA,EAAM,KAAK;AAEX,WAAO,EAAE,MAAM,oBAAoB,aAAaA,EAAM,KAAK,YAAA;AAG7D,MAAIA,aAAiBzJ;AACnB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,aAAayJ,EAAM;AAAA,MACnB,OAAOA,EAAM,iBAAiB,QAAQA,EAAM,QAAQ;AAAA,IAAA;AAK1D;"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { I as A, a as C, b as w, d as v, f as N, c as O, m as R, e as U, g as M, n as $, o as B, p as L, q as D, r as F, s as H, h as K, i as j, j as G, k, l as q, t as J, u as W, v as Y, w as z, x as V, y as X, z as Q, A as Z, B as ee, C as te, D as se, E as ae, F as oe } from "./chunks/recovery-
|
|
2
|
-
import { a8 as Ee, ac as he, Y as Te, ad as ge, S as Ie, R as fe, Z as ye, _ as Ae, $ as _e, H as xe, a7 as be, aa as Pe, a9 as Ce, P as we, a0 as ve, ab as Ne, T as Oe, a6 as Re, J as Ue, G as Me, K as $e, a4 as Be, X as Le, a1 as De, U as Fe, V as He, L as Ke, ae as je, M as Ge, a2 as ke, N as qe, a5 as Je, W as We, O as Ye, Q as ze, a3 as Ve } from "./chunks/recovery-
|
|
1
|
+
import { I as A, a as C, b as w, d as v, f as N, c as O, m as R, e as U, g as M, n as $, o as B, p as L, q as D, r as F, s as H, h as K, i as j, j as G, k, l as q, t as J, u as W, v as Y, w as z, x as V, y as X, z as Q, A as Z, B as ee, C as te, D as se, E as ae, F as oe } from "./chunks/recovery-C4NJU6-O.js";
|
|
2
|
+
import { a8 as Ee, ac as he, Y as Te, ad as ge, S as Ie, R as fe, Z as ye, _ as Ae, $ as _e, H as xe, a7 as be, aa as Pe, a9 as Ce, P as we, a0 as ve, ab as Ne, T as Oe, a6 as Re, J as Ue, G as Me, K as $e, a4 as Be, X as Le, a1 as De, U as Fe, V as He, L as Ke, ae as je, M as Ge, a2 as ke, N as qe, a5 as Je, W as We, O as Ye, Q as ze, a3 as Ve } from "./chunks/recovery-C4NJU6-O.js";
|
|
3
3
|
const ue = (s) => {
|
|
4
4
|
const a = s.amountAtomic ?? s.amount;
|
|
5
5
|
if (a === void 0 || a === "")
|