@aurora-is-near/intents-connect 7.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +176 -0
  2. package/dist/api/createIntentsConnectApi.d.ts +31 -0
  3. package/dist/api/index.d.ts +3 -0
  4. package/dist/api/types.d.ts +93 -0
  5. package/dist/chains.d.ts +27 -0
  6. package/dist/chunks/recovery-BBQaAcqE.js +1034 -0
  7. package/dist/chunks/recovery-BBQaAcqE.js.map +1 -0
  8. package/dist/errors.d.ts +94 -0
  9. package/dist/index.d.ts +11 -0
  10. package/dist/index.js +197 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/logger.d.ts +7 -0
  13. package/dist/machine/context.d.ts +39 -0
  14. package/dist/machine/guards/checks/amountMustExceedFee.d.ts +2 -0
  15. package/dist/machine/guards/checks/destinationTokenIsTouched.d.ts +12 -0
  16. package/dist/machine/guards/checks/feeMustBeEstimated.d.ts +9 -0
  17. package/dist/machine/guards/checks/memoPresentForStellar.d.ts +6 -0
  18. package/dist/machine/guards/checks/mustBeSignedBeforeDeposit.d.ts +8 -0
  19. package/dist/machine/guards/checks/mustHaveSigningPayload.d.ts +7 -0
  20. package/dist/machine/guards/checks/noExecutionInFlight.d.ts +7 -0
  21. package/dist/machine/guards/checks/originNetworkMatches.d.ts +5 -0
  22. package/dist/machine/guards/checks/publicKeyMatchesStandard.d.ts +7 -0
  23. package/dist/machine/guards/checks/quoteMustNotHaveMoved.d.ts +8 -0
  24. package/dist/machine/guards/checks/recipientOnlyOnOutOperation.d.ts +11 -0
  25. package/dist/machine/guards/checks/round1MustBeStepless.d.ts +8 -0
  26. package/dist/machine/guards/checks/stepShapeIsLegal.d.ts +7 -0
  27. package/dist/machine/guards/checks/stepsRequiredForRealCreate.d.ts +6 -0
  28. package/dist/machine/guards/checks/strategiesAreExclusive.d.ts +17 -0
  29. package/dist/machine/guards/index.d.ts +19 -0
  30. package/dist/machine/index.d.ts +4 -0
  31. package/dist/machine/machine.d.ts +50 -0
  32. package/dist/machine/phases.d.ts +48 -0
  33. package/dist/react/IntentsConnectProvider.d.ts +12 -0
  34. package/dist/react/context.d.ts +12 -0
  35. package/dist/react/index.d.ts +3 -0
  36. package/dist/react/index.js +149 -0
  37. package/dist/react/index.js.map +1 -0
  38. package/dist/react/useExecution.d.ts +42 -0
  39. package/dist/recovery.d.ts +27 -0
  40. package/dist/runner/createExecutionRunner.d.ts +2 -0
  41. package/dist/runner/index.d.ts +2 -0
  42. package/dist/runner/types.d.ts +146 -0
  43. package/dist/signers/index.d.ts +2 -0
  44. package/dist/signers/intentsConnect.d.ts +43 -0
  45. package/dist/signers/standards/encoding.d.ts +15 -0
  46. package/dist/signers/standards/erc191.d.ts +18 -0
  47. package/dist/signers/standards/index.d.ts +12 -0
  48. package/dist/signers/standards/nep413.d.ts +22 -0
  49. package/dist/signers/standards/rawEd25519.d.ts +20 -0
  50. package/dist/signers/standards/sep53.d.ts +22 -0
  51. package/dist/types/execution.d.ts +133 -0
  52. package/dist/types/index.d.ts +6 -0
  53. package/dist/types/providers.d.ts +63 -0
  54. package/dist/types/recipe.d.ts +38 -0
  55. package/dist/types/signing.d.ts +70 -0
  56. package/dist/types/transfer.d.ts +60 -0
  57. package/dist/types/wallet.d.ts +53 -0
  58. package/package.json +54 -0
  59. package/react/package.json +8 -0
  60. package/src/api/createIntentsConnectApi.test.ts +146 -0
  61. package/src/api/createIntentsConnectApi.ts +263 -0
  62. package/src/api/generated/conformance.ts +233 -0
  63. package/src/api/generated/openapi.ts +995 -0
  64. package/src/api/index.ts +17 -0
  65. package/src/api/types.ts +138 -0
  66. package/src/chains.ts +103 -0
  67. package/src/errors.ts +234 -0
  68. package/src/index.ts +73 -0
  69. package/src/logger.ts +21 -0
  70. package/src/machine/context.ts +56 -0
  71. package/src/machine/guards/checks/amountMustExceedFee.ts +14 -0
  72. package/src/machine/guards/checks/destinationTokenIsTouched.ts +31 -0
  73. package/src/machine/guards/checks/feeMustBeEstimated.ts +22 -0
  74. package/src/machine/guards/checks/memoPresentForStellar.ts +20 -0
  75. package/src/machine/guards/checks/mustBeSignedBeforeDeposit.ts +17 -0
  76. package/src/machine/guards/checks/mustHaveSigningPayload.ts +19 -0
  77. package/src/machine/guards/checks/noExecutionInFlight.ts +19 -0
  78. package/src/machine/guards/checks/originNetworkMatches.ts +23 -0
  79. package/src/machine/guards/checks/publicKeyMatchesStandard.ts +28 -0
  80. package/src/machine/guards/checks/quoteMustNotHaveMoved.ts +20 -0
  81. package/src/machine/guards/checks/recipientOnlyOnOutOperation.ts +23 -0
  82. package/src/machine/guards/checks/round1MustBeStepless.ts +17 -0
  83. package/src/machine/guards/checks/stepShapeIsLegal.ts +79 -0
  84. package/src/machine/guards/checks/stepsRequiredForRealCreate.ts +12 -0
  85. package/src/machine/guards/checks/strategiesAreExclusive.ts +35 -0
  86. package/src/machine/guards/guards.test.ts +317 -0
  87. package/src/machine/guards/index.ts +22 -0
  88. package/src/machine/index.ts +15 -0
  89. package/src/machine/machine.test.ts +131 -0
  90. package/src/machine/machine.ts +113 -0
  91. package/src/machine/phases.ts +81 -0
  92. package/src/react/IntentsConnectProvider.tsx +61 -0
  93. package/src/react/context.ts +34 -0
  94. package/src/react/index.ts +14 -0
  95. package/src/react/useExecution.test.tsx +281 -0
  96. package/src/react/useExecution.ts +246 -0
  97. package/src/recovery.test.ts +44 -0
  98. package/src/recovery.ts +45 -0
  99. package/src/runner/createExecutionRunner.test.ts +1388 -0
  100. package/src/runner/createExecutionRunner.ts +1156 -0
  101. package/src/runner/index.ts +9 -0
  102. package/src/runner/types.ts +148 -0
  103. package/src/signers/index.ts +7 -0
  104. package/src/signers/intentsConnect.ts +210 -0
  105. package/src/signers/signers.test.ts +415 -0
  106. package/src/signers/standards/encoding.ts +89 -0
  107. package/src/signers/standards/erc191.ts +61 -0
  108. package/src/signers/standards/index.ts +20 -0
  109. package/src/signers/standards/nep413.ts +84 -0
  110. package/src/signers/standards/rawEd25519.ts +46 -0
  111. package/src/signers/standards/sep53.ts +74 -0
  112. package/src/tests/setup.ts +4 -0
  113. package/src/types/execution.ts +177 -0
  114. package/src/types/index.ts +6 -0
  115. package/src/types/providers.ts +71 -0
  116. package/src/types/recipe.ts +41 -0
  117. package/src/types/signing.ts +99 -0
  118. package/src/types/transfer.ts +90 -0
  119. package/src/types/wallet.ts +60 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recovery-BBQaAcqE.js","sources":["../../src/types/execution.ts","../../src/types/signing.ts","../../src/errors.ts","../../src/chains.ts","../../src/logger.ts","../../src/machine/context.ts","../../src/machine/phases.ts","../../src/machine/machine.ts","../../src/machine/guards/checks/amountMustExceedFee.ts","../../src/machine/guards/checks/destinationTokenIsTouched.ts","../../src/machine/guards/checks/feeMustBeEstimated.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/round1MustBeStepless.ts","../../src/machine/guards/checks/stepShapeIsLegal.ts","../../src/machine/guards/checks/stepsRequiredForRealCreate.ts","../../src/machine/guards/checks/strategiesAreExclusive.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/createExecutionRunner.ts","../../src/recovery.ts"],"sourcesContent":["import type { SigningPayload, SigningStandard } from '@/types/signing';\n\nexport type Chain = string;\n\n/** Which endpoint shape an execution uses. v1 implements `bridge-in` only. */\nexport type FlowShape = 'bridge-in';\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/** 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 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 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 /** Already post-fee once a fee was estimated — do not subtract again. */\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: Step[];\n type?: ExecutionType;\n version?: string;\n transaction?: { evmTxHash?: 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 | { kind: 'threeRound' };\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\nexport const SUPPORTED_SIGNING_STANDARDS: readonly SupportedSigningStandard[] =\n ['erc191', 'raw_ed25519', 'nep413', 'sep53'];\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 * 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 */\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\n if (\n inner &&\n typeof inner === 'object' &&\n (inner as { code?: unknown }).code === 4001\n ) {\n return true;\n }\n\n return (\n typeof outer.message === 'string' &&\n /user (rejected|denied|cancell?ed)/i.test(outer.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 | 'ROUND1_MUST_BE_STEPLESS'\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","/**\n * Chain-family routing. Mirrors `packages/intents-swap-widget/src/utils/chains`\n * but carries only what deposit routing needs — no chain SDKs.\n */\nexport const EVM_CHAINS = new Set([\n 'eth',\n 'arb',\n 'base',\n 'bsc',\n 'op',\n 'pol',\n 'avax',\n 'scroll',\n 'gnosis',\n 'xlayer',\n 'bera',\n 'monad',\n 'plasma',\n 'adi',\n 'aurora',\n]);\n\n/**\n * Numeric EVM chain ids for the chains above. Used by `resume()` to rebuild a\n * deposit transfer from an execution alone — the EVM transfer path refuses to\n * run without a target chain id. Mirrors the widget's `EVM_CHAIN_IDS_MAP`.\n */\nexport const EVM_CHAIN_IDS: 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 aurora: 1313161554,\n};\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","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';\nimport type { Phase } from '@/machine/phases';\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 phase: Phase;\n\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 phase: 'idle',\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 * - `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', 'expired', 'cancelled', 'failed'],\n settling: ['success', 'failed', 'expired', 'cancelled'],\n expired: ['settling', '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","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 /** Refuses an illegal transition; check `current` to see whether it moved. */\n moveTo: (phase: Phase) => ExecutionMachine;\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 store.state = phase;\n }\n\n return machine;\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.canMoveTo(phase)) {\n logger.error(\n `invalid transition requested (from ${machine.current} to ${phase})`,\n );\n\n return false;\n }\n\n const { current, context } = machine.moveTo(phase);\n\n if (current !== phase) {\n return false;\n }\n\n context.phase = phase;\n onMoved?.(phase);\n\n return true;\n};\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 (!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\nconst MEMO_MODE_CHAINS = new Set(['stellar']);\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 */\nexport const memoPresentForStellar = (\n originChain: string,\n memo?: string | null,\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 { failGuard } from '@/errors';\nimport type { Step } from '@/types/execution';\n\n/**\n * Round 1 of the three-round flow must send no steps.\n *\n * Gas estimation only runs when `steps` is non-empty, so an empty array is what\n * yields a quote with no fee deducted. It must therefore also be `dry: true`.\n */\nexport const round1MustBeStepless = (steps: Step[]) => {\n if (steps.length > 0) {\n failGuard(\n 'ROUND1_MUST_BE_STEPLESS',\n 'three-round flow: round 1 must send steps: []',\n );\n }\n};\n","import { failGuard } from '@/errors';\nimport {\n type ExecutionType,\n MAX_FUNCTION_SIGNATURE_BYTES,\n MAX_STEPS,\n type Step,\n STEP_KEYS,\n} from '@/types/execution';\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 = (steps: Step[], type: ExecutionType) => {\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.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 { Step } 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: Step[], dry: boolean) => {\n if (!dry && steps.length === 0) {\n failGuard('STEPS_REQUIRED', 'dry: false requires a non-empty steps array');\n }\n};\n","import { failGuard } from '@/errors';\nimport {\n BACKEND_PLACEHOLDERS,\n type FeeStrategy,\n type Step,\n} from '@/types/execution';\n\n/** True when the steps embed the `{MIN_AMOUNT_OUT}` placeholder. */\nexport const stepsUsePlaceholder = (steps: Step[]): boolean =>\n JSON.stringify(steps).includes(BACKEND_PLACEHOLDERS.minAmountOut);\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: Step[],\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 { base58, base64 } 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\nexport const fromHex = (value: string): Uint8Array => {\n const normalised = value.replace(/^0x/i, '').toLowerCase();\n\n if (normalised.length % 2 !== 0) {\n throw new Error('Hex string has an odd length');\n }\n\n // Without this, `Number.parseInt('zz', 16)` yields NaN, which a Uint8Array\n // stores as 0 — turning a malformed wallet signature into a well-formed\n // all-zero one that only fails later, server-side, with an opaque message.\n if (!/^[0-9a-f]*$/.test(normalised)) {\n throw new Error('Hex string contains non-hexadecimal characters');\n }\n\n const bytes = new Uint8Array(normalised.length / 2);\n\n for (let i = 0; i < bytes.length; i += 1) {\n bytes[i] = Number.parseInt(normalised.slice(i * 2, i * 2 + 2), 16);\n }\n\n return bytes;\n};\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 ed25519Signature,\n fromBase64,\n toBase58,\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 = signed.publicKey.startsWith('ed25519:')\n ? signed.publicKey\n : `ed25519:${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\n/** Exported for adapters that need to re-encode a raw key. */\nexport const encodePublicKey = (bytes: Uint8Array): string =>\n `ed25519:${toBase58(bytes)}`;\n","import 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 const inBandError = (result as { error?: { message?: string } | string })\n ?.error;\n\n if (inBandError) {\n throw new Error(\n typeof inBandError === 'string'\n ? inBandError\n : (inBandError.message ?? 'Stellar wallet refused to sign'),\n );\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 { EVM_CHAIN_IDS, getChainFamily, parseOriginAsset } from '@/chains';\nimport {\n DepositTransferError,\n ExecutionCancelledError,\n ExecutionPollTimeoutError,\n failGuard,\n GuardError,\n IntentsConnectApiError,\n isUserRejection,\n RunnerDisposedError,\n toError,\n} from '@/errors';\nimport { defaultLogger } from '@/logger';\nimport { createExecutionMachine, moveTo } from '@/machine/machine';\nimport * as guards from '@/machine/guards';\nimport type { Context } from '@/machine/context';\nimport { isTerminalPhase, type Phase } from '@/machine/phases';\nimport {\n signIntentsConnectPayload,\n signIntentsConnectText,\n} from '@/signers/intentsConnect';\nimport {\n BACKEND_PLACEHOLDERS,\n type Execution,\n type FeeStrategy,\n IN_FLIGHT_STATUSES,\n type Intermediary,\n type Step,\n type SwapType,\n TERMINAL_STATUSES,\n} from '@/types/execution';\nimport {\n isSupportedSigningStandard,\n type SignatureEnvelope,\n type SigningStandard,\n} from '@/types/signing';\nimport type { MakeTransferArgs, TransferResult } from '@/types/transfer';\nimport type { WalletConnector } from '@/types/wallet';\nimport type { CreateExecutionBody } from '@/api/types';\nimport type {\n ExecutionPlan,\n ExecutionRunner,\n ExecutionRunnerOptions,\n OriginToken,\n ResumeDepositOptions,\n RunnerEvent,\n} from '@/runner/types';\n\nconst DEFAULT_POLL_INTERVAL_MS = 3_000;\nconst DEFAULT_MAX_POLL_ATTEMPTS = 240;\nconst DEFAULT_FEE_STRATEGY: FeeStrategy = { kind: 'placeholder' };\n/** Applied when the caller supplies no `quote.deadline` — the API requires one. */\nconst 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 */\nconst 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 */\nconst MAX_CONSECUTIVE_POLL_ERRORS = 5;\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 */\ntype DepositPlan = {\n originChain: string;\n originToken: OriginToken;\n originChainId?: number | null;\n depositViaWallet: boolean;\n quote: { swapType: SwapType; deadline?: string };\n};\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\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 /** Set by `cancel()`; observed at every wallet-interaction boundary and by the polling loop. */\n let cancelledExecutionId: string | undefined;\n\n /**\n * Set by `dispose()`. A disposed runner must stop touching the wallet and\n * the API: its owner has been rebound (typically to another account), so any\n * further side effect would act on behalf of the wrong context.\n */\n let disposed = false;\n\n /** The deposit leg of the current run, kept so `retryDeposit()` can replay the transfer. */\n let activePlan: DepositPlan | undefined;\n\n /**\n * The id of the execution `activePlan` was created FOR. `resume()` needs it\n * to tell a same-session resume (safe to replay the plan's transfer) from a\n * cross-session one that merely reuses a runner still holding an unrelated\n * plan — context.executionId cannot be used for that, because resume patches\n * it to the resumed id before the check.\n */\n let activePlanExecutionId: string | undefined;\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 throwIfDisposed = () => {\n if (disposed) {\n throw new RunnerDisposedError(machine.context.executionId);\n }\n };\n\n const throwIfCancelled = (executionId: string) => {\n if (cancelledExecutionId === executionId) {\n throw new ExecutionCancelledError(executionId);\n }\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 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 );\n }\n\n machine.reset();\n cancelledExecutionId = undefined;\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 /**\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 */\n const signPayload = async (\n execution: Execution,\n ): Promise<{ envelope: SignatureEnvelope; standard: SigningStandard }> => {\n const { payload, standard } = guards.mustHaveSigningPayload(execution);\n const activeWallet = getWallet();\n\n const envelope = await signIntentsConnectPayload({\n payload,\n standard,\n address: requireAddress(),\n providers: activeWallet.getProviders(),\n decodePublicKey: activeWallet.decodePublicKey,\n });\n\n return { envelope, standard };\n };\n\n /* ── 1. Identity ─────────────────────────────────────────────────────────\n * Deterministic and stable per wallet, so it is fetched once per run and\n * everything downstream acts \"on behalf of\" the intermediary. */\n const resolveIdentity = async () => {\n to('resolving-identity');\n\n const intermediary = await api.getIntermediary(requireAddress(), {\n publicKey: getWallet().getPublicKey?.(),\n });\n\n patch({ intermediary });\n\n return intermediary;\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 */\n const pickIntermediaryAddress = <TParams>(\n plan: ExecutionPlan<TParams>,\n intermediary: Intermediary,\n ): string => {\n const address =\n plan.recipe.type === 'solana' ? intermediary.solana : intermediary.evm;\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 /** The API requires `quote.deadline`; default it rather than 400. */\n 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\n const buildBody = <TParams>(\n plan: ExecutionPlan<TParams>,\n steps: Step[],\n dry: boolean,\n ): CreateExecutionBody => ({\n version: '1.0',\n type: plan.recipe.type,\n quote: plan.quote,\n steps,\n metadata: { title: plan.recipe.title, intent: plan.recipe.intent },\n dry,\n publicKey:\n plan.originChain === 'ton' ? getWallet().getPublicKey?.() : undefined,\n });\n\n const validateSteps = <TParams>(\n plan: ExecutionPlan<TParams>,\n steps: Step[],\n ): Step[] => {\n guards.stepShapeIsLegal(steps, plan.recipe.type);\n guards.destinationTokenIsTouched(\n steps,\n plan.recipe.destination.tokenAddress,\n );\n\n return steps;\n };\n\n /* ── 2. Plan ─────────────────────────────────────────────────────────────\n * Sizes the spendable amount against the fee the service carves.\n *\n * The circularity: the amount depends on the fee, the fee depends on the\n * steps, the steps depend on the amount. Two ways out. */\n const planSteps = async <TParams>(\n plan: ExecutionPlan<TParams>,\n intermediaryAddress: string,\n ): Promise<Step[]> => {\n to('planning');\n\n const { recipe, params, quote } = plan;\n const feeStrategy = plan.feeStrategy ?? DEFAULT_FEE_STRATEGY;\n\n guards.recipientOnlyOnOutOperation(recipe.flow, quote.recipient);\n await guards.originNetworkMatches(\n getWallet().getChainId,\n plan.originChainId,\n );\n\n const base = {\n intermediary: intermediaryAddress,\n userAddress: requireAddress(),\n };\n\n // Strategy A — one round. The service substitutes the post-fee amount.\n if (feeStrategy.kind === 'placeholder') {\n const steps = recipe.buildSteps(\n { ...base, amount: BACKEND_PLACEHOLDERS.minAmountOut },\n params,\n );\n\n guards.strategiesAreExclusive(feeStrategy, steps);\n\n if (!guards.stepsUsePlaceholder(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: gas estimation only runs with non-empty steps, so\n // this is what yields an un-carved quote.\n guards.round1MustBeStepless([]);\n\n const gross = await api.createExecution(\n requireAddress(),\n buildBody(plan, [], true),\n );\n\n // Round 2 — real steps at the gross amount, which measures the fee.\n const probe = recipe.buildSteps(\n { ...base, amount: gross.quote.minAmountOut },\n params,\n );\n\n guards.strategiesAreExclusive(feeStrategy, probe);\n\n const measured = await api.createExecution(\n requireAddress(),\n buildBody(plan, validateSteps(plan, probe), true),\n );\n\n const networkFee = guards.feeMustBeEstimated(measured);\n\n guards.amountMustExceedFee(gross.quote.minAmountOut, networkFee);\n\n // Already post-fee — do NOT subtract again.\n const spendable = measured.quote.minAmountOut;\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 = recipe.buildSteps({ ...base, amount: spendable }, params);\n\n return validateSteps(plan, final);\n };\n\n /* ── 3. Create ─────────────────────────────────────────────────────────── */\n const create = async <TParams>(\n plan: ExecutionPlan<TParams>,\n steps: Step[],\n ): Promise<Execution> => {\n to('creating');\n\n guards.stepsRequiredForRealCreate(steps, false);\n\n const address = requireAddress();\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 guards.noExecutionInFlight(\n await api.listExecutions(address, { status: IN_FLIGHT_STATUSES }),\n );\n\n let execution: Execution;\n\n try {\n execution = await api.createExecution(\n address,\n buildBody(plan, steps, false),\n );\n } catch (error) {\n if (\n error instanceof IntentsConnectApiError &&\n error.isExecutionInFlight\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 try {\n const { bakedAmount } = machine.context;\n\n if (bakedAmount) {\n guards.quoteMustNotHaveMoved(bakedAmount, execution.quote.minAmountOut);\n }\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 );\n }\n\n throw error;\n }\n\n return execution;\n };\n\n /* ── 4/5. Sign, then submit ──────────────────────────────────────────────\n * Deliberately before the deposit: the service holds the pre-signed batch and\n * fires it the moment the bridge settles.\n *\n * Returns whether a user deposit is still required. */\n const signAndSubmit = async (execution: Execution): Promise<boolean> => {\n to('awaiting-signature');\n\n const { envelope, standard } = await signPayload(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 throwIfCancelled(execution.id);\n throwIfDisposed();\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\n const resolveTransfer = (\n originChain: string,\n ): ((args: MakeTransferArgs) => Promise<Pick<TransferResult, 'hash'>>) => {\n if (makeTransferOverride) {\n return (args) => makeTransferOverride(args, undefined as void);\n }\n\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 // Thrown at resolution rather than invocation: a missing implementation\n // is a configuration error, not a retryable transfer failure.\n return 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 }\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 /* ── 6. Deposit ──────────────────────────────────────────────────────────\n * The only place a deposit address is exposed, and only post-signature. */\n const exposeDepositAddress = (execution: Execution, deadline?: string) => {\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\n const awaitDeposit = async (plan: DepositPlan, execution: Execution) => {\n guards.memoPresentForStellar(plan.originChain, execution.quote.depositMemo);\n\n const { depositAddress, depositMemo } = exposeDepositAddress(\n execution,\n plan.quote.deadline,\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 throwIfCancelled(execution.id);\n throwIfDisposed();\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 = resolveTransfer(plan.originChain);\n\n let hash: string;\n\n try {\n ({ hash } = await transfer({\n 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 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\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. */\n const settle = async (executionId: string): Promise<Execution> => {\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. Every other entry settles at once.\n const holdingForDeposit = () =>\n machine.current === 'awaiting-deposit' &&\n machine.context.status === 'CREATED' &&\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\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 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 // A terminal status can arrive while the phase sits at `expired` or\n // `awaiting-deposit`, neither of which has a direct edge to `success`.\n if (\n machine.current === 'expired' ||\n machine.current === 'awaiting-deposit'\n ) {\n to('settling');\n }\n\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 // EXPIRED is soft-terminal: reflect it in the phase and keep polling,\n // because a late deposit revives the execution. Held rather than flipped\n // back each iteration, so the phase mirrors the observed state instead of\n // emitting two events per poll.\n if (execution.status === 'EXPIRED') {\n to('expired');\n } else if (machine.current === 'expired') {\n to('settling');\n } else if (\n machine.current === 'awaiting-deposit' &&\n execution.status !== 'CREATED'\n ) {\n // The watcher observed the deposit — the waiting-for-funds hold ends.\n to('settling');\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 // eslint-disable-next-line no-await-in-loop\n await sleep(pollIntervalMs);\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\n /** Shared failure handling: record it, announce it, then rethrow. */\n const fail = (error: unknown): never => {\n const failure = toError(error);\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\n const cancel = async (executionId?: string) => {\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,\n });\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 previous = cancelledExecutionId;\n\n cancelledExecutionId = id;\n\n try {\n await api.deleteExecution(requireAddress(), id, envelope);\n } catch (error) {\n cancelledExecutionId = previous;\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 if (activePlanExecutionId === id) {\n activePlan = undefined;\n activePlanExecutionId = undefined;\n }\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 machine.reset();\n emit({ type: 'phase', phase: 'idle' });\n }\n } finally {\n patch({ isCancelling: false });\n }\n };\n\n const run = async <TParams>(\n inputPlan: ExecutionPlan<TParams>,\n ): Promise<Execution> => {\n prepareForNewFlow();\n\n try {\n // The connector's standard must be signable BEFORE anything is created:\n // a real create for a standard we cannot sign (ton_connect, tip191)\n // would strand an execution holding the in-flight lock.\n const { signingStandard } = 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 const plan = withQuoteDeadline(inputPlan);\n\n const intermediary = await resolveIdentity();\n const steps = await planSteps(\n plan,\n pickIntermediaryAddress(plan, intermediary),\n );\n\n const execution = await create(plan, steps);\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 activePlan = plan;\n activePlanExecutionId = execution.id;\n\n let needsDeposit: boolean;\n\n try {\n needsDeposit = await signAndSubmit(execution);\n } catch (error) {\n // A rejected signing prompt means the user abandoned THIS attempt —\n // but the created execution still holds the per-wallet in-flight\n // lock. Best effort: offer the delete signature right away so the\n // next run() starts clean instead of tripping EXECUTION_IN_FLIGHT\n // and demanding a resume-or-cancel decision. Declining that second\n // prompt (or any delete failure) falls back to the normal recovery,\n // with the ORIGINAL rejection as the recorded error either way.\n if (autoCancelOnSignatureRejection && isUserRejection(error)) {\n try {\n await cancel(execution.id);\n } catch (cancelError) {\n 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 if (needsDeposit) {\n await awaitDeposit(plan, execution);\n }\n\n return await settle(execution.id);\n } catch (error) {\n return fail(error);\n }\n };\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 */\n const retryDeposit = async (): Promise<Execution> => {\n const { execution } = machine.context;\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(activePlan, execution);\n\n return await settle(execution.id);\n } catch (error) {\n return fail(error);\n }\n };\n\n /**\n * Whether `resolveTransfer` would find an implementation for this chain —\n * checked WITHOUT the guard throw, so `resume()` can fall back to surfacing\n * the deposit address instead of failing a resumable execution.\n */\n const hasTransferImplementation = (originChain: string): boolean => {\n if (makeTransferOverride !== undefined) {\n return true;\n }\n\n if (getWallet().makeTransfer !== undefined) {\n return true;\n }\n\n const family = getChainFamily(originChain);\n\n return Boolean(family && plugins?.[family]);\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 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 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: execution.quote.swapType ?? 'EXACT_INPUT',\n deadline: execution.quote.deadline,\n },\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 */\n const resume = async (\n executionId: string,\n depositOptions?: ResumeDepositOptions,\n ): Promise<Execution> => {\n 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 (\n execution.status === 'CREATED' &&\n messageSigned !== true &&\n !payload\n ) {\n guards.mustHaveSigningPayload(execution);\n }\n\n patch({\n execution,\n executionId: execution.id,\n status: execution.status,\n hasSubmittedSignature: !needsSigning,\n });\n\n // CREATED is still waiting on funds; DEPOSIT_PENDING is SIGNED and\n // still waiting on funds (the /submit response names the same state\n // SIGNED_PENDING_DEPOSIT) — the single most common resume case, since a\n // failed transfer leg strands an execution exactly there; EXPIRED may be\n // revived by a late deposit — the package's own design — which requires\n // re-surfacing the address, or the user has no means to effect the\n // revival. From DEPOSIT_PROCESSING onward the funds have been observed,\n // so prompting another transfer would double-spend.\n let needsDeposit =\n execution.status === 'CREATED' ||\n execution.status === 'DEPOSIT_PENDING' ||\n execution.status === 'EXPIRED';\n\n if (needsSigning) {\n needsDeposit = await signAndSubmit(execution);\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 isOwnRun = !!activePlan && activePlanExecutionId === execution.id;\n\n let plan: DepositPlan | undefined;\n\n if (isOwnRun && activePlan) {\n plan = activePlan;\n } else {\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 && hasTransferImplementation(rebuilt.originChain)) {\n plan = rebuilt;\n }\n }\n\n if (plan) {\n // Retained so a failed transfer stays retryable via retryDeposit().\n activePlan = plan;\n activePlanExecutionId = execution.id;\n\n await awaitDeposit(plan, execution);\n } else {\n // resume() has no plan to read the origin chain from, but a sep53\n // connector IS a Stellar origin — and a Stellar deposit without a\n // memo is unattributable on the shared deposit address.\n if (getWallet().signingStandard === 'sep53') {\n guards.memoPresentForStellar(\n 'stellar',\n execution.quote.depositMemo,\n );\n }\n\n exposeDepositAddress(execution);\n }\n }\n\n return await settle(execution.id);\n } catch (error) {\n return fail(error);\n }\n };\n\n return {\n run,\n resume,\n retryDeposit,\n cancel,\n dispose: () => {\n disposed = true;\n },\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","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","isUserRejection","IntentsConnectApiError","status","body","ExecutionCancelledError","executionId","RunnerDisposedError","ExecutionPollTimeoutError","detail","DepositTransferError","GuardError","meta","failGuard","EVM_CHAINS","EVM_CHAIN_IDS","OMFT_SUFFIX","parseOriginAsset","assetId","rest","dash","chain","tokenAddress","isEvmChain","getChainFamily","PREFIX","defaultLogger","args","noopLogger","createInitialContext","PHASE_TRANSITIONS","TERMINAL_PHASES","isTerminalPhase","phase","createExecutionMachine","store","proxy","machine","moveTo","logger","onMoved","current","context","amountMustExceedFee","grossAmount","networkFee","destinationTokenIsTouched","steps","destinationTokenAddress","target","step","feeMustBeEstimated","execution","fee","MEMO_MODE_CHAINS","memoPresentForStellar","originChain","memo","mustBeSignedBeforeDeposit","hasSubmittedSignature","mustHaveSigningPayload","payload","signingStandard","noExecutionInFlight","openExecutions","open","originNetworkMatches","getChainId","expectedChainId","actual","publicKeyMatchesStandard","publicKey","requiresPublicKey","quoteMustNotHaveMoved","bakedAmount","returnedMinAmountOut","recipientOnlyOnOutOperation","flow","recipient","round1MustBeStepless","ALLOWED_KEYS","stepShapeIsLegal","type","max","index","key","stepsRequiredForRealCreate","dry","stepsUsePlaceholder","strategiesAreExclusive","strategy","SIGNATURE_BYTE_LENGTH_ED25519","SIGNATURE_BYTE_LENGTH_SECP256K1","RECOVERY_BYTE_INDEX","fromBase64","base64","toBase64","bytes","toBase58","base58","fromHex","normalised","i","normaliseRecoveryByte","signature","recovery","assertEd25519SignatureLength","label","secp256k1Signature","ed25519Signature","ed25519PublicKeyFromBytes","ed25519PublicKeyFromBase58","signErc191","provider","expectedAddress","resolved","accounts","signingAccount","account","signRawEd25519","providerPublicKey","signNep413","getProvider","expectedAccountId","wallet","nonce","signed","rawSignature","encodePublicKey","signSep53","decodePublicKey","result","inBandError","signedMessage","signerAddress","requireProvider","parseNep413Payload","payloadJson","parsed","signIntentsConnectPayload","address","providers","NEP413_DELETE_RECIPIENT","NEP413_NONCE_BYTES","randomNonce","signIntentsConnectText","text","nonceBytes","DEFAULT_POLL_INTERVAL_MS","DEFAULT_MAX_POLL_ATTEMPTS","DEFAULT_FEE_STRATEGY","DEFAULT_QUOTE_DEADLINE_MS","DEPOSIT_DEADLINE_GRACE_MS","MAX_CONSECUTIVE_POLL_ERRORS","sleep","ms","resolve","createExecutionRunner","api","plugins","pluginOptions","makeTransferOverride","autoCancelOnSignatureRejection","pollIntervalMs","maxPollAttempts","onEvent","getWallet","cancelledExecutionId","disposed","activePlan","activePlanExecutionId","emit","event","patch","values","to","moved","throwIfDisposed","throwIfCancelled","prepareForNewFlow","requireAddress","signPayload","guards.mustHaveSigningPayload","activeWallet","resolveIdentity","intermediary","pickIntermediaryAddress","plan","withQuoteDeadline","buildBody","validateSteps","guards.stepShapeIsLegal","guards.destinationTokenIsTouched","planSteps","intermediaryAddress","recipe","params","quote","feeStrategy","guards.recipientOnlyOnOutOperation","guards.originNetworkMatches","base","guards.strategiesAreExclusive","guards.stepsUsePlaceholder","guards.round1MustBeStepless","gross","probe","measured","guards.feeMustBeEstimated","guards.amountMustExceedFee","spendable","final","create","guards.stepsRequiredForRealCreate","guards.noExecutionInFlight","error","guards.quoteMustNotHaveMoved","signAndSubmit","envelope","guards.publicKeyMatchesStandard","resolveTransfer","walletTransfer","family","plugin","familyOptions","exposeDepositAddress","deadline","guards.mustBeSignedBeforeDeposit","depositAddress","depositMemo","validUntil","awaitDeposit","guards.memoPresentForStellar","amountAtomic","transfer","hash","settle","holdingForDeposit","deadlineMs","attempt","consecutiveErrors","expired","fail","failure","cancel","id","previous","run","inputPlan","needsDeposit","cancelError","retryDeposit","hasTransferImplementation","buildResumeDepositPlan","depositOptions","originAsset","origin","decimals","originChainId","messageSigned","needsSigning","isOwnRun","rebuilt","deriveExecutionRecovery"],"mappings":";;AA4BO,MAAMA,KAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AACF,GASaC,KAAiD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAgCaC,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,KAAuB;AAAA,EAClC,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,UAAU;AACZ,GCxEaC,KACX,CAAC,UAAU,eAAe,UAAU,OAAO,GAQhCC,KAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAEaC,KAA6B,CACxCC,MAECH,GAA2D;AAAA,EAC1DG;AACF;AC/CK,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;AAAA,MACvB,CAACC,MAAm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AAA,MACN,aAAa6M,EAAM;AAAA,MACnB,OAAOA,EAAM,iBAAiB,QAAQA,EAAM,QAAQ;AAAA,IAAA;AAK1D;"}
@@ -0,0 +1,94 @@
1
+ /** Base class for every error this package throws. */
2
+ export declare class IntentsConnectError extends Error {
3
+ constructor(message: string, options?: {
4
+ cause?: unknown;
5
+ });
6
+ }
7
+ /**
8
+ * Normalises an arbitrary thrown value into an `Error` with a readable
9
+ * message.
10
+ *
11
+ * Needed because wallet providers routinely reject with PLAIN OBJECTS rather
12
+ * than `Error` instances — an EIP-1193 rejection travels as
13
+ * `{ code: 4001, message: 'User rejected the request.' }`, and some connectors
14
+ * nest it one level down as `{ error: { code, message } }`. `String(...)` on
15
+ * those renders "[object Object]", which is what a UI would end up showing.
16
+ * The original value is preserved on `cause`.
17
+ */
18
+ export declare const toError: (value: unknown) => Error;
19
+ /**
20
+ * Whether a thrown value is the user declining a wallet prompt.
21
+ *
22
+ * EIP-1193 names it `userRejectedRequest` = 4001, and the major Solana wallets
23
+ * reuse the same code. The code may sit on the value itself, nested one level
24
+ * (`{ error: { code } }`), or on a wrapping Error's `cause`; older providers
25
+ * only say it in prose, hence the message fallback.
26
+ */
27
+ export declare const isUserRejection: (value: unknown) => boolean;
28
+ /** A non-2xx response from the Intents Connect API. */
29
+ export declare class IntentsConnectApiError extends IntentsConnectError {
30
+ readonly status: number;
31
+ readonly body?: unknown | undefined;
32
+ constructor(message: string, status: number, body?: unknown | undefined);
33
+ /**
34
+ * A `dry: false` create is already live for this (intermediary, chain). The
35
+ * caller must wait for a terminal status or delete the open execution.
36
+ */
37
+ get isExecutionInFlight(): boolean;
38
+ }
39
+ /**
40
+ * The execution was cancelled through `runner.cancel()`. Distinct from a guard
41
+ * violation: nothing went wrong, the caller asked to stop.
42
+ */
43
+ export declare class ExecutionCancelledError extends IntentsConnectError {
44
+ readonly executionId: string;
45
+ constructor(executionId: string);
46
+ }
47
+ /**
48
+ * The runner was disposed (typically because the bound wallet or account
49
+ * changed) while an execution was still in flight. The execution itself is
50
+ * untouched server-side — reattach with `resume()` from a runner bound to the
51
+ * owning wallet.
52
+ */
53
+ export declare class RunnerDisposedError extends IntentsConnectError {
54
+ readonly executionId?: string | undefined;
55
+ constructor(executionId?: string | undefined);
56
+ }
57
+ /**
58
+ * Polling stopped without observing a terminal status. NOT a verdict on the
59
+ * execution — it is still live server-side and may yet succeed. Reattach with
60
+ * `resume(executionId)` to keep watching it.
61
+ */
62
+ export declare class ExecutionPollTimeoutError extends IntentsConnectError {
63
+ readonly executionId: string;
64
+ constructor(executionId: string, detail: string);
65
+ }
66
+ /**
67
+ * The deposit transfer was rejected or failed in the wallet. The execution is
68
+ * still valid and signed server-side; call `runner.retryDeposit()` to prompt
69
+ * the transfer again.
70
+ */
71
+ export declare class DepositTransferError extends IntentsConnectError {
72
+ readonly executionId: string;
73
+ constructor(executionId: string, options?: {
74
+ cause?: unknown;
75
+ });
76
+ }
77
+ /**
78
+ * A precondition of the Intents Connect protocol was violated. Every code
79
+ * corresponds to one named guard under `machine/guards/checks`.
80
+ */
81
+ export type GuardCode = 'STEPS_REQUIRED' | 'ROUND1_MUST_BE_STEPLESS' | 'FEE_NOT_ESTIMATED' | 'FEE_EXCEEDS_AMOUNT' | 'QUOTE_MOVED' | 'ILLEGAL_STEP_SHAPE' | 'DESTINATION_TOKEN_UNTOUCHED' | 'RECIPIENT_NOT_ALLOWED' | 'STRATEGY_CONFLICT' | 'EXECUTION_IN_FLIGHT' | 'NO_INTERMEDIARY' | 'NETWORK_MISMATCH' | 'MEMO_REQUIRED' | 'DEPOSIT_BEFORE_SIGNATURE' | 'PUBLIC_KEY_MISMATCH' | 'NO_SIGNING_PAYLOAD' | 'UNSUPPORTED_SIGNING_STANDARD' | 'NO_TRANSFER_IMPLEMENTATION' | 'WALLET_NOT_CONNECTED';
82
+ export type GuardMeta = {
83
+ /** Set by EXECUTION_IN_FLIGHT: the execution holding the lock. */
84
+ executionId?: string;
85
+ };
86
+ export declare class GuardError extends IntentsConnectError {
87
+ readonly code: GuardCode;
88
+ /** Structured context, so UIs can act on the error instead of parsing prose. */
89
+ readonly meta: GuardMeta;
90
+ constructor(code: GuardCode, message: string,
91
+ /** Structured context, so UIs can act on the error instead of parsing prose. */
92
+ meta?: GuardMeta);
93
+ }
94
+ export declare const failGuard: (code: GuardCode, message: string, meta?: GuardMeta) => never;
@@ -0,0 +1,11 @@
1
+ export * from './types';
2
+ export { createIntentsConnectApi } from './api';
3
+ export type { CreateExecutionBody, CreateStepsExecutionBody, ExecutionMetadata, FetchLike, IntentsConnectApi, IntentsConnectApiOptions, ListExecutionsQuery, RecordDepositBody, SubmitSignatureBody, SupportedToken, SupportedTokensFlow, SupportedTokensResult, } from './api';
4
+ export { createExecutionRunner } from './runner';
5
+ export type { ExecutionPlan, ExecutionRunner, ExecutionRunnerOptions, OriginToken, ResumeDepositOptions, RunnerEvent, } from './runner';
6
+ export { PHASE_TRANSITIONS, TERMINAL_PHASES, createExecutionMachine, createInitialContext, guards, isTerminalPhase, moveTo, type Context, type ExecutionMachine, type Phase, } from './machine';
7
+ export { signIntentsConnectPayload, signIntentsConnectText, standards, type SignPayloadArgs, type SignTextArgs, } from './signers';
8
+ export { EVM_CHAIN_IDS, EVM_CHAINS, getChainFamily, isEvmChain, parseOriginAsset, type ChainFamily, } from './chains';
9
+ export { deriveExecutionRecovery, type ExecutionRecovery } from './recovery';
10
+ export { DepositTransferError, ExecutionCancelledError, ExecutionPollTimeoutError, GuardError, IntentsConnectApiError, IntentsConnectError, RunnerDisposedError, failGuard, type GuardCode, } from './errors';
11
+ export { defaultLogger, noopLogger, type Logger } from './logger';