@lifi/sdk-provider-solana 4.3.3 → 4.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +9 -0
- package/dist/cjs/actions/lookupSignatureStatus.d.ts +66 -0
- package/dist/cjs/actions/lookupSignatureStatus.js +258 -0
- package/dist/cjs/actions/lookupSignatureStatus.js.map +1 -0
- package/dist/cjs/actions/sendAndConfirmTransaction.d.ts +7 -0
- package/dist/cjs/actions/sendAndConfirmTransaction.js +1 -0
- package/dist/cjs/actions/sendAndConfirmTransaction.js.map +1 -1
- package/dist/cjs/confirmation/confirmBundle.d.ts +1 -1
- package/dist/cjs/confirmation/confirmSignature.d.ts +1 -1
- package/dist/cjs/confirmation/createConfirmationDeadline.d.ts +6 -0
- package/dist/cjs/confirmation/createConfirmationDeadline.js +24 -8
- package/dist/cjs/confirmation/createConfirmationDeadline.js.map +1 -1
- package/dist/cjs/confirmation/pollUntilDeadline.js +9 -1
- package/dist/cjs/confirmation/pollUntilDeadline.js.map +1 -1
- package/dist/cjs/confirmation/raceRpcs.d.ts +8 -0
- package/dist/cjs/confirmation/raceRpcs.js +9 -1
- package/dist/cjs/confirmation/raceRpcs.js.map +1 -1
- package/dist/cjs/confirmation/types.d.ts +3 -0
- package/dist/cjs/confirmation/types.js.map +1 -1
- package/dist/cjs/core/SolanaStepExecutor.js +2 -4
- package/dist/cjs/core/SolanaStepExecutor.js.map +1 -1
- package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js +69 -33
- package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
- package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js +13 -5
- package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
- package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js +71 -38
- package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
- package/dist/cjs/core/tasks/SolanaWaitForTransactionTask.js +13 -1
- package/dist/cjs/core/tasks/SolanaWaitForTransactionTask.js.map +1 -1
- package/dist/cjs/core/tasks/confirmationError.d.ts +29 -0
- package/dist/cjs/core/tasks/confirmationError.js +26 -0
- package/dist/cjs/core/tasks/confirmationError.js.map +1 -0
- package/dist/cjs/core/tasks/resumeFromStore.d.ts +31 -0
- package/dist/cjs/core/tasks/resumeFromStore.js +81 -0
- package/dist/cjs/core/tasks/resumeFromStore.js.map +1 -0
- package/dist/cjs/core/tasks/transactionOutcome.d.ts +107 -0
- package/dist/cjs/core/tasks/transactionOutcome.js +158 -0
- package/dist/cjs/core/tasks/transactionOutcome.js.map +1 -0
- package/dist/cjs/types.d.ts +13 -2
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/utils/storedTransactions.d.ts +36 -0
- package/dist/cjs/utils/storedTransactions.js +57 -0
- package/dist/cjs/utils/storedTransactions.js.map +1 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/actions/lookupSignatureStatus.d.ts +66 -0
- package/dist/esm/actions/lookupSignatureStatus.d.ts.map +1 -0
- package/dist/esm/actions/lookupSignatureStatus.js +252 -0
- package/dist/esm/actions/lookupSignatureStatus.js.map +1 -0
- package/dist/esm/actions/sendAndConfirmTransaction.d.ts +7 -0
- package/dist/esm/actions/sendAndConfirmTransaction.d.ts.map +1 -1
- package/dist/esm/actions/sendAndConfirmTransaction.js +1 -0
- package/dist/esm/actions/sendAndConfirmTransaction.js.map +1 -1
- package/dist/esm/confirmation/confirmBundle.d.ts +1 -1
- package/dist/esm/confirmation/confirmSignature.d.ts +1 -1
- package/dist/esm/confirmation/createConfirmationDeadline.d.ts +6 -0
- package/dist/esm/confirmation/createConfirmationDeadline.d.ts.map +1 -1
- package/dist/esm/confirmation/createConfirmationDeadline.js +24 -8
- package/dist/esm/confirmation/createConfirmationDeadline.js.map +1 -1
- package/dist/esm/confirmation/pollUntilDeadline.js +9 -1
- package/dist/esm/confirmation/pollUntilDeadline.js.map +1 -1
- package/dist/esm/confirmation/raceRpcs.d.ts +8 -0
- package/dist/esm/confirmation/raceRpcs.d.ts.map +1 -1
- package/dist/esm/confirmation/raceRpcs.js +9 -1
- package/dist/esm/confirmation/raceRpcs.js.map +1 -1
- package/dist/esm/confirmation/types.d.ts +3 -0
- package/dist/esm/confirmation/types.d.ts.map +1 -1
- package/dist/esm/confirmation/types.js.map +1 -1
- package/dist/esm/core/SolanaStepExecutor.d.ts.map +1 -1
- package/dist/esm/core/SolanaStepExecutor.js +3 -5
- package/dist/esm/core/SolanaStepExecutor.js.map +1 -1
- package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js +69 -33
- package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
- package/dist/esm/core/tasks/SolanaSignAndExecuteTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js +14 -6
- package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
- package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js +71 -38
- package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
- package/dist/esm/core/tasks/SolanaWaitForTransactionTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/SolanaWaitForTransactionTask.js +13 -1
- package/dist/esm/core/tasks/SolanaWaitForTransactionTask.js.map +1 -1
- package/dist/esm/core/tasks/confirmationError.d.ts +29 -0
- package/dist/esm/core/tasks/confirmationError.d.ts.map +1 -0
- package/dist/esm/core/tasks/confirmationError.js +25 -0
- package/dist/esm/core/tasks/confirmationError.js.map +1 -0
- package/dist/esm/core/tasks/resumeFromStore.d.ts +31 -0
- package/dist/esm/core/tasks/resumeFromStore.d.ts.map +1 -0
- package/dist/esm/core/tasks/resumeFromStore.js +80 -0
- package/dist/esm/core/tasks/resumeFromStore.js.map +1 -0
- package/dist/esm/core/tasks/transactionOutcome.d.ts +107 -0
- package/dist/esm/core/tasks/transactionOutcome.d.ts.map +1 -0
- package/dist/esm/core/tasks/transactionOutcome.js +150 -0
- package/dist/esm/core/tasks/transactionOutcome.js.map +1 -0
- package/dist/esm/types.d.ts +13 -2
- package/dist/esm/types.d.ts.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/utils/storedTransactions.d.ts +36 -0
- package/dist/esm/utils/storedTransactions.d.ts.map +1 -0
- package/dist/esm/utils/storedTransactions.js +54 -0
- package/dist/esm/utils/storedTransactions.js.map +1 -0
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/package.json +2 -2
- package/src/actions/lookupSignatureStatus.ts +444 -0
- package/src/actions/sendAndConfirmTransaction.ts +18 -0
- package/src/confirmation/createConfirmationDeadline.ts +43 -11
- package/src/confirmation/pollUntilDeadline.ts +14 -1
- package/src/confirmation/raceRpcs.ts +27 -1
- package/src/confirmation/types.ts +5 -0
- package/src/core/SolanaStepExecutor.ts +15 -8
- package/src/core/tasks/SolanaJitoWaitForTransactionTask.ts +133 -71
- package/src/core/tasks/SolanaSignAndExecuteTask.ts +50 -10
- package/src/core/tasks/SolanaStandardWaitForTransactionTask.ts +130 -76
- package/src/core/tasks/SolanaWaitForTransactionTask.ts +19 -1
- package/src/core/tasks/confirmationError.ts +60 -0
- package/src/core/tasks/resumeFromStore.ts +160 -0
- package/src/core/tasks/transactionOutcome.ts +273 -0
- package/src/types.ts +13 -1
- package/src/utils/storedTransactions.ts +88 -0
- package/src/version.ts +1 -1
- package/dist/cjs/core/tasks/unwrapConfirmation.d.ts +0 -24
- package/dist/cjs/core/tasks/unwrapConfirmation.js +0 -24
- package/dist/cjs/core/tasks/unwrapConfirmation.js.map +0 -1
- package/dist/esm/core/tasks/unwrapConfirmation.d.ts +0 -24
- package/dist/esm/core/tasks/unwrapConfirmation.d.ts.map +0 -1
- package/dist/esm/core/tasks/unwrapConfirmation.js +0 -23
- package/dist/esm/core/tasks/unwrapConfirmation.js.map +0 -1
- package/src/core/tasks/unwrapConfirmation.ts +0 -59
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createConfirmationDeadline.js","names":[],"sources":["../../../src/confirmation/createConfirmationDeadline.ts"],"sourcesContent":["import type { Blockhash } from '@solana/kit'\nimport type { SolanaRpcType } from '../rpc/types.js'\nimport type { TransactionLifetime } from '../utils/getTransactionLifetime.js'\n\n/** Give-up point for a branch's polling. Read between iterations only, so a\n * hung RPC call needs `BRANCH_TIMEOUT_MS` to close the gap. */\nexport const CONFIRMATION_TIMEOUT_MS = 90_000\n/** Head-room for the final probe after the deadline.\n * `STATUS_RETRY_BACKOFF_CAP_MS` must stay below it. */\nexport const FINAL_PROBE_MARGIN_MS = 5_000\n/** Hard bound on a branch, in-flight requests included. Above the ceiling so\n * an abort cannot pre-empt the final probe. */\nexport const BRANCH_TIMEOUT_MS: number =\n CONFIRMATION_TIMEOUT_MS + FINAL_PROBE_MARGIN_MS\n/** How long a healthy-but-lagging node may need to catch up. A premise, not a\n * knob: `isBlockhashValid` answers `false` for lag and for death alike, so no\n * verdict may land inside this window. */\nexport const NODE_LAG_WINDOW_MS = 12_000\n/** Gap between `isBlockhashValid` probes. Spacing them is what makes the\n * consecutive-`false` rule meaningful: quantized to the 400 ms tick, probes\n * land at 0.4/7.6/14.8 s, so no verdict lands inside `NODE_LAG_WINDOW_MS`. */\nexport const EXPIRY_PROBE_INTERVAL_MS = 7_000\n/** Consecutive `false` results before a blockhash is believed dead. Derived so\n * a change to either premise moves it automatically; `+ 2` keeps the\n * inequality strict when the window divides exactly. */\nexport const EXPIRY_CONFIRMATIONS: number =\n Math.floor(NODE_LAG_WINDOW_MS / EXPIRY_PROBE_INTERVAL_MS) + 2\n/** Probe failures per blockhash before that blockhash stops being probed.\n * Prober-only; the status pollers have `MAX_STATUS_READ_SILENCE_MS`. */\nexport const MAX_PROBE_ERRORS = 5\n\n/** Structural, so one implementation serves both the Solana and Jito RPC. */\nexport type BlockhashProbeRpc = Pick<SolanaRpcType, 'isBlockhashValid'>\n\nexport interface ConfirmationDeadline {\n /** Checked at the top of every poll iteration. */\n reached(): boolean\n /** Advances the policy; never throws. Probes at most once per\n * `EXPIRY_PROBE_INTERVAL_MS`. */\n tick(signal: AbortSignal): Promise<void>\n}\n\n/**\n * Owns every \"should I stop polling?\" decision.\n *\n * Never reads `getBlockHeight`: at least one default LI.FI RPC answers it with\n * the slot number, making any `lastValidBlockHeight` comparison false on its\n * first evaluation.\n */\nexport function createConfirmationDeadline(options: {\n lifetimes: TransactionLifetime[]\n rpc: BlockhashProbeRpc\n now?: () => number\n}): ConfirmationDeadline {\n const { lifetimes, rpc } = options\n const now = options.now ?? Date.now\n const startedAt = now()\n\n const blockhashLifetimes = lifetimes.filter(\n (\n lifetime\n ): lifetime is Extract<TransactionLifetime, { kind: 'blockhash' }> =>\n lifetime.kind === 'blockhash'\n )\n // A single non-blockhash lifetime disables the early exit for the whole set:\n // we cannot know when such a transaction stops being landable.\n const allProbeable =\n lifetimes.length > 0 && blockhashLifetimes.length === lifetimes.length\n const blockhashes: Blockhash[] = allProbeable\n ? [...new Set(blockhashLifetimes.map((lifetime) => lifetime.blockhash))]\n : []\n\n // Keyed by blockhash: expiry is a property of a blockhash, not of the set.\n const expiredStreaks = new Map<Blockhash, number>()\n // Keyed for the same reason: a sibling's broken probe is not evidence about\n // this blockhash, so it must not spend this blockhash's error budget.\n const errorStreaks = new Map<Blockhash, number>()\n // The blockhashes still worth asking about. One leaves this set after\n // MAX_PROBE_ERRORS failures of its own; the others keep being probed.\n const probeable = new Set<Blockhash>(blockhashes)\n let lastProbeAt: number | undefined\n\n /** Derived, not latched: a blockhash that reads valid again zeroes its\n * streak and clears the verdict with it. */\n const isExpired = (): boolean => {\n for (const streak of expiredStreaks.values()) {\n if (streak >= EXPIRY_CONFIRMATIONS) {\n return true\n }\n }\n return false\n }\n\n return {\n reached(): boolean {\n const elapsed = now() - startedAt\n if (elapsed >= CONFIRMATION_TIMEOUT_MS) {\n return true\n }\n return isExpired()\n },\n async tick(signal: AbortSignal): Promise<void> {\n if (probeable.size === 0 || signal.aborted) {\n return\n }\n // The cadence is wall-clock, not iteration count, and it uses the\n // injected `now` so the policy stays testable without timers.\n const probeAt = now()\n if (\n lastProbeAt !== undefined &&\n probeAt - lastProbeAt < EXPIRY_PROBE_INTERVAL_MS\n ) {\n return\n }\n lastProbeAt = probeAt\n // `allSettled`, not `all`: `all` rejects on the first failure and\n // discards answers the other probes already produced. All state is keyed\n // by blockhash, so one broken probe cannot disable the early exit for\n // the rest.\n const active = [...probeable]\n const probes = await Promise.allSettled(\n active.map(async (blockhash) => {\n const result = await rpc\n .isBlockhashValid(blockhash, { commitment: 'confirmed' })\n .send({ abortSignal: signal })\n return result.value\n })\n )\n\n // A read that produced no usable answer says nothing about this\n // blockhash: it must never spend the expiry streak, only the error\n // budget. Shared by a rejected probe and by a fulfilled one whose\n // response carried no boolean.\n const recordFailedProbe = (blockhash: Blockhash): void => {\n expiredStreaks.set(blockhash, 0)\n const errors = (errorStreaks.get(blockhash) ?? 0) + 1\n errorStreaks.set(blockhash, errors)\n if (errors >= MAX_PROBE_ERRORS) {\n // Degrade to ceiling-only for this blockhash.\n probeable.delete(blockhash)\n }\n }\n\n probes.forEach((probe, index) => {\n const blockhash = active[index]\n\n if (probe.status === 'rejected') {\n recordFailedProbe(blockhash)\n return\n }\n\n // `=== true` / `=== false`, never truthiness: a response carrying no\n // `value` is not a `false`, and reading it as one is the only coercion\n // here that can invent an expiry.\n if (probe.value === true) {\n errorStreaks.set(blockhash, 0)\n expiredStreaks.set(blockhash, 0)\n return\n }\n\n if (probe.value === false) {\n errorStreaks.set(blockhash, 0)\n expiredStreaks.set(\n blockhash,\n (expiredStreaks.get(blockhash) ?? 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AAC,CAAC,CACxD,KAAK,EAAE,aAAa,OAAO,CAAC,EAAA,CACjB;GAChB,CAAC,CACH;GAMA,MAAM,qBAAqB,cAA+B;IACxD,eAAe,IAAI,WAAW,CAAC;IAC/B,MAAM,UAAU,aAAa,IAAI,SAAS,KAAK,KAAK;IACpD,aAAa,IAAI,WAAW,MAAM;IAClC,IAAI,UAAA,GAEF,UAAU,OAAO,SAAS;GAE9B;GAEA,OAAO,SAAS,OAAO,UAAU;IAC/B,MAAM,YAAY,OAAO;IAEzB,IAAI,MAAM,WAAW,YAAY;KAC/B,kBAAkB,SAAS;KAC3B;IACF;IAKA,IAAI,MAAM,UAAU,MAAM;KACxB,aAAa,IAAI,WAAW,CAAC;KAC7B,eAAe,IAAI,WAAW,CAAC;KAC/B;IACF;IAEA,IAAI,MAAM,UAAU,OAAO;KACzB,aAAa,IAAI,WAAW,CAAC;KAC7B,eAAe,IACb,YACC,eAAe,IAAI,SAAS,KAAK,KAAK,CACzC;KACA;IACF;IAEA,kBAAkB,SAAS;GAC7B,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"createConfirmationDeadline.js","names":[],"sources":["../../../src/confirmation/createConfirmationDeadline.ts"],"sourcesContent":["import type { Blockhash } from '@solana/kit'\nimport type { SolanaRpcType } from '../rpc/types.js'\nimport type { TransactionLifetime } from '../utils/getTransactionLifetime.js'\n\n/** Give-up point for a branch's polling. Read between iterations only, so a\n * hung RPC call needs `BRANCH_TIMEOUT_MS` to close the gap. */\nexport const CONFIRMATION_TIMEOUT_MS = 90_000\n/** Head-room for the final probe after the deadline.\n * `STATUS_RETRY_BACKOFF_CAP_MS` must stay below it. */\nexport const FINAL_PROBE_MARGIN_MS = 5_000\n/** Hard bound on a branch, in-flight requests included. Above the ceiling so\n * an abort cannot pre-empt the final probe. */\nexport const BRANCH_TIMEOUT_MS: number =\n CONFIRMATION_TIMEOUT_MS + FINAL_PROBE_MARGIN_MS\n/** How long a healthy-but-lagging node may need to catch up. A premise, not a\n * knob: `isBlockhashValid` answers `false` for lag and for death alike, so no\n * verdict may land inside this window. */\nexport const NODE_LAG_WINDOW_MS = 12_000\n/** Gap between `isBlockhashValid` probes. Spacing them is what makes the\n * consecutive-`false` rule meaningful: quantized to the 400 ms tick, probes\n * land at 0.4/7.6/14.8 s, so no verdict lands inside `NODE_LAG_WINDOW_MS`. */\nexport const EXPIRY_PROBE_INTERVAL_MS = 7_000\n/** Consecutive `false` results before a blockhash is believed dead. Derived so\n * a change to either premise moves it automatically; `+ 2` keeps the\n * inequality strict when the window divides exactly. */\nexport const EXPIRY_CONFIRMATIONS: number =\n Math.floor(NODE_LAG_WINDOW_MS / EXPIRY_PROBE_INTERVAL_MS) + 2\n/** Probe failures per blockhash before that blockhash stops being probed.\n * Prober-only; the status pollers have `MAX_STATUS_READ_SILENCE_MS`. */\nexport const MAX_PROBE_ERRORS = 5\n\n/** Structural, so one implementation serves both the Solana and Jito RPC. */\nexport type BlockhashProbeRpc = Pick<SolanaRpcType, 'isBlockhashValid'>\n\nexport interface ConfirmationDeadline {\n /** Checked at the top of every poll iteration. */\n reached(): boolean\n /** The slot at which the blockhash probe confirmed expiry - the highest\n * `context.slot` of the `false` answers in the streak - or `undefined`\n * without a verdict. Tells the two reasons `reached()` fires apart: a dead\n * blockhash may later count as \"dropped\", the wall-clock ceiling never\n * does. */\n expiredAt(): bigint | undefined\n /** Advances the policy; never throws. Probes at most once per\n * `EXPIRY_PROBE_INTERVAL_MS`. */\n tick(signal: AbortSignal): Promise<void>\n}\n\n/**\n * Owns every \"should I stop polling?\" decision.\n *\n * Never reads `getBlockHeight`: at least one default LI.FI RPC answers it with\n * the slot number, making any `lastValidBlockHeight` comparison false on its\n * first evaluation.\n */\nexport function createConfirmationDeadline(options: {\n lifetimes: TransactionLifetime[]\n rpc: BlockhashProbeRpc\n now?: () => number\n}): ConfirmationDeadline {\n const { lifetimes, rpc } = options\n const now = options.now ?? Date.now\n const startedAt = now()\n\n const blockhashLifetimes = lifetimes.filter(\n (\n lifetime\n ): lifetime is Extract<TransactionLifetime, { kind: 'blockhash' }> =>\n lifetime.kind === 'blockhash'\n )\n // A single non-blockhash lifetime disables the early exit for the whole set:\n // we cannot know when such a transaction stops being landable.\n const allProbeable =\n lifetimes.length > 0 && blockhashLifetimes.length === lifetimes.length\n const blockhashes: Blockhash[] = allProbeable\n ? [...new Set(blockhashLifetimes.map((lifetime) => lifetime.blockhash))]\n : []\n\n // Keyed by blockhash: expiry is a property of a blockhash, not of the set.\n const expiredStreaks = new Map<Blockhash, number>()\n // The highest `context.slot` of each blockhash's current `false` streak:\n // where a dropped check has to find a node's head before it trusts a\n // `null`. A reset of the streak deletes it.\n const expiredSlots = new Map<Blockhash, bigint>()\n // Keyed for the same reason: a sibling's broken probe is not evidence about\n // this blockhash, so it must not spend this blockhash's error budget.\n const errorStreaks = new Map<Blockhash, number>()\n // The blockhashes still worth asking about. One leaves this set after\n // MAX_PROBE_ERRORS failures of its own; the others keep being probed.\n const probeable = new Set<Blockhash>(blockhashes)\n let lastProbeAt: number | undefined\n\n /** Derived, not latched: a blockhash that reads valid again zeroes its\n * streak and clears the verdict with it. The highest slot among the expired\n * blockhashes is the strictest head bound. */\n const expiredAt = (): bigint | undefined => {\n let slot: bigint | undefined\n for (const [blockhash, streak] of expiredStreaks) {\n const observedAt = expiredSlots.get(blockhash)\n if (\n streak >= EXPIRY_CONFIRMATIONS &&\n observedAt !== undefined &&\n (slot === undefined || observedAt > slot)\n ) {\n slot = observedAt\n }\n }\n return slot\n }\n\n return {\n reached(): boolean {\n const elapsed = now() - startedAt\n if (elapsed >= CONFIRMATION_TIMEOUT_MS) {\n return true\n }\n return expiredAt() !== undefined\n },\n expiredAt,\n async tick(signal: AbortSignal): Promise<void> {\n if (probeable.size === 0 || signal.aborted) {\n return\n }\n // The cadence is wall-clock, not iteration count, and it uses the\n // injected `now` so the policy stays testable without timers.\n const probeAt = now()\n if (\n lastProbeAt !== undefined &&\n probeAt - lastProbeAt < EXPIRY_PROBE_INTERVAL_MS\n ) {\n return\n }\n lastProbeAt = probeAt\n // `allSettled`, not `all`: `all` rejects on the first failure and\n // discards answers the other probes already produced. All state is keyed\n // by blockhash, so one broken probe cannot disable the early exit for\n // the rest.\n const active = [...probeable]\n const probes = await Promise.allSettled(\n active.map(async (blockhash) => {\n const result = await rpc\n .isBlockhashValid(blockhash, { commitment: 'confirmed' })\n .send({ abortSignal: signal })\n return { value: result?.value, slot: result?.context?.slot }\n })\n )\n\n // A read that produced no usable answer says nothing about this\n // blockhash: it must never spend the expiry streak, only the error\n // budget. Shared by a rejected probe and by a fulfilled one whose\n // response carried no usable verdict.\n const recordFailedProbe = (blockhash: Blockhash): void => {\n expiredStreaks.set(blockhash, 0)\n expiredSlots.delete(blockhash)\n const errors = (errorStreaks.get(blockhash) ?? 0) + 1\n errorStreaks.set(blockhash, errors)\n if (errors >= MAX_PROBE_ERRORS) {\n // Degrade to ceiling-only for this blockhash.\n probeable.delete(blockhash)\n }\n }\n\n probes.forEach((probe, index) => {\n const blockhash = active[index]\n\n if (probe.status === 'rejected') {\n recordFailedProbe(blockhash)\n return\n }\n\n const { value, slot } = probe.value\n\n // `=== true` / `=== false`, never truthiness: a response carrying no\n // `value` is not a `false`, and reading it as one is the only coercion\n // here that can invent an expiry.\n if (value === true) {\n errorStreaks.set(blockhash, 0)\n expiredStreaks.set(blockhash, 0)\n expiredSlots.delete(blockhash)\n return\n }\n\n // A `false` counts only with the slot it was observed at: a verdict\n // without one could not bound the head of the dropped check.\n if (value === false && typeof slot === 'bigint') {\n errorStreaks.set(blockhash, 0)\n expiredStreaks.set(\n blockhash,\n (expiredStreaks.get(blockhash) ?? 0) + 1\n )\n // The highest slot, not the latest: a `false` from a node whose head\n // is behind the others must not lower the bound below the slots\n // where the transaction can still land.\n const previous = expiredSlots.get(blockhash)\n expiredSlots.set(\n blockhash,\n previous === undefined || slot > previous ? slot : previous\n )\n return\n }\n\n recordFailedProbe(blockhash)\n })\n },\n }\n}\n"],"mappings":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AAQ,WAC3B,OAAO,IAAI,OAAO,cAAc;IAC9B,MAAM,SAAS,MAAM,IAClB,iBAAiB,WAAW,EAAE,YAAY,YAAY,CAAC,CAAC,CACxD,KAAK,EAAE,aAAa,OAAO,CAAC;IAC/B,OAAO;KAAE,OAAO,QAAQ;KAAO,MAAM,QAAQ,SAAS;IAAK;GAC7D,CAAC,CACH;GAMA,MAAM,qBAAqB,cAA+B;IACxD,eAAe,IAAI,WAAW,CAAC;IAC/B,aAAa,OAAO,SAAS;IAC7B,MAAM,UAAU,aAAa,IAAI,SAAS,KAAK,KAAK;IACpD,aAAa,IAAI,WAAW,MAAM;IAClC,IAAI,UAAA,GAEF,UAAU,OAAO,SAAS;GAE9B;GAEA,OAAO,SAAS,OAAO,UAAU;IAC/B,MAAM,YAAY,OAAO;IAEzB,IAAI,MAAM,WAAW,YAAY;KAC/B,kBAAkB,SAAS;KAC3B;IACF;IAEA,MAAM,EAAE,OAAO,SAAS,MAAM;IAK9B,IAAI,UAAU,MAAM;KAClB,aAAa,IAAI,WAAW,CAAC;KAC7B,eAAe,IAAI,WAAW,CAAC;KAC/B,aAAa,OAAO,SAAS;KAC7B;IACF;IAIA,IAAI,UAAU,SAAS,OAAO,SAAS,UAAU;KAC/C,aAAa,IAAI,WAAW,CAAC;KAC7B,eAAe,IACb,YACC,eAAe,IAAI,SAAS,KAAK,KAAK,CACzC;KAIA,MAAM,WAAW,aAAa,IAAI,SAAS;KAC3C,aAAa,IACX,WACA,aAAa,KAAA,KAAa,OAAO,WAAW,OAAO,QACrD;KACA;IACF;IAEA,kBAAkB,SAAS;GAC7B,CAAC;EACH;CACF;AACF"}
|
|
@@ -51,9 +51,11 @@ async function pollUntilDeadline(options) {
|
|
|
51
51
|
let probeSucceeded = false;
|
|
52
52
|
let lastAnswerAt = now();
|
|
53
53
|
let deadlineReached = false;
|
|
54
|
+
let expiredAtDeadline;
|
|
54
55
|
while (!signal.aborted) {
|
|
55
56
|
if (deadline.reached()) {
|
|
56
57
|
deadlineReached = true;
|
|
58
|
+
expiredAtDeadline = deadline.expiredAt();
|
|
57
59
|
break;
|
|
58
60
|
}
|
|
59
61
|
try {
|
|
@@ -80,7 +82,13 @@ async function pollUntilDeadline(options) {
|
|
|
80
82
|
value
|
|
81
83
|
};
|
|
82
84
|
} catch (_) {}
|
|
83
|
-
if (probeSucceeded && deadlineReached)
|
|
85
|
+
if (probeSucceeded && deadlineReached) {
|
|
86
|
+
const expiredAt = expiredAtDeadline === void 0 ? void 0 : deadline.expiredAt();
|
|
87
|
+
return expiredAt === void 0 ? { kind: "not-confirmed" } : {
|
|
88
|
+
kind: "expired",
|
|
89
|
+
slot: expiredAt
|
|
90
|
+
};
|
|
91
|
+
}
|
|
84
92
|
if (options.neverBroadcast?.()) throw new Error(`Every ${subject} send to this RPC failed.`);
|
|
85
93
|
if (!probeSucceeded) throw new Error(`No ${read} against this RPC ever completed.`);
|
|
86
94
|
throw new Error(`This RPC stopped answering before a final ${read} could run.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pollUntilDeadline.js","names":["abortableSleep"],"sources":["../../../src/confirmation/pollUntilDeadline.ts"],"sourcesContent":["import { abortableSleep } from './abortableSleep.js'\nimport type { ConfirmationDeadline } from './createConfirmationDeadline.js'\nimport type { ConfirmationOutcome } from './types.js'\n\n/** Cadence of the detached deadline-advance loop. Independent of the\n * status-poll interval, which each caller sets for its own rate limits. */\nexport const DEADLINE_TICK_INTERVAL_MS = 400\n/** How long an endpoint may go without answering a status read before its\n * branch gives up. Measured in wall-clock time, not in failures: a count is\n * coupled to the backoff curve, and ten failures spanned only ~16.4 s, so a\n * routine 20 s throttling window ended the branch 74 s inside the 90 s ceiling\n * and reported an already-broadcast transaction as an outage. */\nexport const MAX_STATUS_READ_SILENCE_MS = 30_000\n/** Ceiling on one backoff sleep. Squeezed between two bounds:\n * - Above `BUNDLE_POLL_INTERVAL_MS`, the largest base interval any caller\n * uses. At 2 s the two were equal, so `Math.max(pollIntervalMs, ...)` below\n * returned the base interval for every failure count and the bundle path\n * never backed off at all.\n * - Far enough below `FINAL_PROBE_MARGIN_MS` to leave the final probe a\n * usable window. A sleep straddling the ceiling delays that probe by up to\n * the cap, so the window is the margin minus this value - 2 s here. `cap <\n * margin` alone is not the constraint: 4 s satisfied it and left the probe\n * 1 s, on the failing endpoints where the cap is reached and reads are\n * slowest.\n *\n * The gap between the two bounds fits one doubling, so the bundle path's\n * backoff is a single step rather than a curve. Widening it means raising\n * `FINAL_PROBE_MARGIN_MS`, which lengthens the branch bound the SDK\n * documents. */\nexport const STATUS_RETRY_BACKOFF_CAP_MS = 3_000\n\n/**\n * Polls one probe against one RPC until the deadline, and owns the verdict\n * rules shared by the signature and bundle branches.\n *\n * `probe` resolves non-`null` for a confirmation, `null` for \"answered, saw\n * nothing\", and rejects for a failed read. The deadline advances on a detached\n * loop so a hung blockhash probe cannot stop status polling.\n */\nexport async function pollUntilDeadline<T>(options: {\n deadline: ConfirmationDeadline\n signal: AbortSignal\n /** Sleep between two status reads that answered. */\n pollIntervalMs: number\n /** One status read. `null` means it answered but saw no confirmation. */\n probe: () => Promise<T | null>\n /** Names the read in error messages, e.g. 'signature status read'. */\n read: string\n /** Names the thing being confirmed in error messages, e.g. 'transaction'. */\n subject: string\n /** `true` when this RPC never accepted the broadcast. Read at verdict time,\n * and only when the observation did not complete. */\n neverBroadcast?: () => boolean\n /** Injectable clock, so the silence budget is testable without timers.\n * Mirrors `createConfirmationDeadline`. */\n now?: () => number\n}): Promise<ConfirmationOutcome<T>> {\n const { deadline, signal, pollIntervalMs, probe, read, subject } = options\n const now = options.now ?? Date.now\n\n let settled = false\n\n // Advances the deadline independently of the status reads.\n const advancing = (async () => {\n while (!settled && !signal.aborted) {\n await abortableSleep(DEADLINE_TICK_INTERVAL_MS, signal)\n if (settled || signal.aborted) {\n break\n }\n await deadline.tick(signal)\n }\n })()\n advancing.catch(() => {})\n\n try {\n let failures = 0\n // Did this RPC ever answer? A `null` read still answered. Separates\n // \"polled and saw nothing\" from \"never got a word out of this endpoint\".\n let probeSucceeded = false\n // When a read last answered; the branch start until one does. A `null` read\n // counts as an answer - the endpoint is alive and says nothing.\n let lastAnswerAt = now()\n\n // Records WHY the loop ended, because the two reasons earn different\n // verdicts. Reaching the deadline is a complete observation; being aborted\n // mid-read is not. The final probe below is a bonus on top of a complete\n // observation, so losing it must not downgrade the verdict.\n let deadlineReached = false\n while (!signal.aborted) {\n if (deadline.reached()) {\n deadlineReached = true\n break\n }\n try {\n const value = await probe()\n failures = 0\n lastAnswerAt = now()\n probeSucceeded = true\n if (value !== null) {\n return { kind: 'confirmed', value }\n }\n } catch (error) {\n // `failures` still drives the backoff below; only the give-up rule is\n // time-based.\n failures += 1\n if (now() - lastAnswerAt >= MAX_STATUS_READ_SILENCE_MS) {\n throw error\n }\n }\n // Exponential backoff, so a throttling burst meets a falling rate. The\n // outer `max` stops the cap inverting it for a caller whose base\n // interval already exceeds the cap.\n const delay =\n failures === 0\n ? pollIntervalMs\n : Math.max(\n pollIntervalMs,\n Math.min(\n pollIntervalMs * 2 ** failures,\n STATUS_RETRY_BACKOFF_CAP_MS\n )\n )\n await abortableSleep(delay, signal)\n }\n\n // The status may have flipped between the last poll and the deadline\n // being reached.\n if (!signal.aborted) {\n try {\n const value = await probe()\n probeSucceeded = true\n if (value !== null) {\n return { kind: 'confirmed', value }\n }\n } catch (_) {\n // The loop already ran. One failed final probe is not evidence that\n // this RPC is unusable.\n }\n }\n\n // A completed observation outranks everything below: polled to its own\n // deadline and saw nothing. It stays ahead of the send-failure signal on\n // purpose - a throw here is bucketed as `rpc-unavailable` by `raceRpcs`,\n // which would discard a real observation and misreport a genuinely expired\n // transaction as an outage. The never-broadcast case is answered one level\n // up, in the actions, which know whether ANY branch accepted the send.\n //\n // Keyed on `deadlineReached`, not on `!signal.aborted`: the final probe is\n // a bonus on top of the observation, and the shared BRANCH_TIMEOUT_MS timer\n // can abort that probe in every branch at once. Reading the abort here\n // would discard every observation and report a fleet-wide expiry as an\n // outage.\n if (probeSucceeded && deadlineReached) {\n return { kind: 'not-confirmed' }\n }\n\n if (options.neverBroadcast?.()) {\n throw new Error(`Every ${subject} send to this RPC failed.`)\n }\n\n // Every read hung until the abort: an in-flight read never answers, so it\n // never renews `lastAnswerAt` and never throws either - the abort arrives\n // first. `not-confirmed` here would report a hung endpoint as an expiry.\n if (!probeSucceeded) {\n throw new Error(`No ${read} against this RPC ever completed.`)\n }\n\n // Exiting via `signal.aborted` means the final observation never\n // happened — an in-flight read held the loop until the abort cut it off.\n // An answer received early in the window must not stand in for one near\n // the deadline: a branch that answered once and then went dark has no\n // basis to call the subject of the read expired. (A branch aborted because another\n // RPC already confirmed also throws here; `raceRpcs` drops a losing\n // branch's error once its controller has aborted, so nothing is\n // misreported.)\n throw new Error(\n `This RPC stopped answering before a final ${read} could run.`\n )\n } finally {\n settled = true\n }\n}\n"],"mappings":";;;;;AAMA,MAAa,4BAA4B;;;;;;AAMzC,MAAa,6BAA6B;;;;;;;;;;;;;;;;;AAiB1C,MAAa,8BAA8B;;;;;;;;;AAU3C,eAAsB,kBAAqB,SAiBP;CAClC,MAAM,EAAE,UAAU,QAAQ,gBAAgB,OAAO,MAAM,YAAY;CACnE,MAAM,MAAM,QAAQ,OAAO,KAAK;CAEhC,IAAI,UAAU;CAYd,CATmB,YAAY;EAC7B,OAAO,CAAC,WAAW,CAAC,OAAO,SAAS;GAClC,MAAMA,oCAAAA,eAAAA,KAA0C,MAAM;GACtD,IAAI,WAAW,OAAO,SACpB;GAEF,MAAM,SAAS,KAAK,MAAM;EAC5B;CACF,EAAA,CACQ,CAAC,CAAC,YAAY,CAAC,CAAC;CAExB,IAAI;EACF,IAAI,WAAW;EAGf,IAAI,iBAAiB;EAGrB,IAAI,eAAe,IAAI;EAMvB,IAAI,kBAAkB;EACtB,OAAO,CAAC,OAAO,SAAS;GACtB,IAAI,SAAS,QAAQ,GAAG;IACtB,kBAAkB;IAClB;GACF;GACA,IAAI;IACF,MAAM,QAAQ,MAAM,MAAM;IAC1B,WAAW;IACX,eAAe,IAAI;IACnB,iBAAiB;IACjB,IAAI,UAAU,MACZ,OAAO;KAAE,MAAM;KAAa;IAAM;GAEtC,SAAS,OAAO;IAGd,YAAY;IACZ,IAAI,IAAI,IAAI,gBAAA,KACV,MAAM;GAEV;GAIA,MAAM,QACJ,aAAa,IACT,iBACA,KAAK,IACH,gBACA,KAAK,IACH,iBAAiB,KAAK,UACtB,2BACF,CACF;GACN,MAAMA,oCAAAA,eAAe,OAAO,MAAM;EACpC;EAIA,IAAI,CAAC,OAAO,SACV,IAAI;GACF,MAAM,QAAQ,MAAM,MAAM;GAC1B,iBAAiB;GACjB,IAAI,UAAU,MACZ,OAAO;IAAE,MAAM;IAAa;GAAM;EAEtC,SAAS,GAAG,CAGZ;EAeF,IAAI,kBAAkB,iBACpB,OAAO,EAAE,MAAM,gBAAgB;EAGjC,IAAI,QAAQ,iBAAiB,GAC3B,MAAM,IAAI,MAAM,SAAS,QAAQ,0BAA0B;EAM7D,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,MAAM,KAAK,kCAAkC;EAW/D,MAAM,IAAI,MACR,6CAA6C,KAAK,YACpD;CACF,UAAU;EACR,UAAU;CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"pollUntilDeadline.js","names":["abortableSleep"],"sources":["../../../src/confirmation/pollUntilDeadline.ts"],"sourcesContent":["import { abortableSleep } from './abortableSleep.js'\nimport type { ConfirmationDeadline } from './createConfirmationDeadline.js'\nimport type { ConfirmationOutcome } from './types.js'\n\n/** Cadence of the detached deadline-advance loop. Independent of the\n * status-poll interval, which each caller sets for its own rate limits. */\nexport const DEADLINE_TICK_INTERVAL_MS = 400\n/** How long an endpoint may go without answering a status read before its\n * branch gives up. Measured in wall-clock time, not in failures: a count is\n * coupled to the backoff curve, and ten failures spanned only ~16.4 s, so a\n * routine 20 s throttling window ended the branch 74 s inside the 90 s ceiling\n * and reported an already-broadcast transaction as an outage. */\nexport const MAX_STATUS_READ_SILENCE_MS = 30_000\n/** Ceiling on one backoff sleep. Squeezed between two bounds:\n * - Above `BUNDLE_POLL_INTERVAL_MS`, the largest base interval any caller\n * uses. At 2 s the two were equal, so `Math.max(pollIntervalMs, ...)` below\n * returned the base interval for every failure count and the bundle path\n * never backed off at all.\n * - Far enough below `FINAL_PROBE_MARGIN_MS` to leave the final probe a\n * usable window. A sleep straddling the ceiling delays that probe by up to\n * the cap, so the window is the margin minus this value - 2 s here. `cap <\n * margin` alone is not the constraint: 4 s satisfied it and left the probe\n * 1 s, on the failing endpoints where the cap is reached and reads are\n * slowest.\n *\n * The gap between the two bounds fits one doubling, so the bundle path's\n * backoff is a single step rather than a curve. Widening it means raising\n * `FINAL_PROBE_MARGIN_MS`, which lengthens the branch bound the SDK\n * documents. */\nexport const STATUS_RETRY_BACKOFF_CAP_MS = 3_000\n\n/**\n * Polls one probe against one RPC until the deadline, and owns the verdict\n * rules shared by the signature and bundle branches.\n *\n * `probe` resolves non-`null` for a confirmation, `null` for \"answered, saw\n * nothing\", and rejects for a failed read. The deadline advances on a detached\n * loop so a hung blockhash probe cannot stop status polling.\n */\nexport async function pollUntilDeadline<T>(options: {\n deadline: ConfirmationDeadline\n signal: AbortSignal\n /** Sleep between two status reads that answered. */\n pollIntervalMs: number\n /** One status read. `null` means it answered but saw no confirmation. */\n probe: () => Promise<T | null>\n /** Names the read in error messages, e.g. 'signature status read'. */\n read: string\n /** Names the thing being confirmed in error messages, e.g. 'transaction'. */\n subject: string\n /** `true` when this RPC never accepted the broadcast. Read at verdict time,\n * and only when the observation did not complete. */\n neverBroadcast?: () => boolean\n /** Injectable clock, so the silence budget is testable without timers.\n * Mirrors `createConfirmationDeadline`. */\n now?: () => number\n}): Promise<ConfirmationOutcome<T>> {\n const { deadline, signal, pollIntervalMs, probe, read, subject } = options\n const now = options.now ?? Date.now\n\n let settled = false\n\n // Advances the deadline independently of the status reads.\n const advancing = (async () => {\n while (!settled && !signal.aborted) {\n await abortableSleep(DEADLINE_TICK_INTERVAL_MS, signal)\n if (settled || signal.aborted) {\n break\n }\n await deadline.tick(signal)\n }\n })()\n advancing.catch(() => {})\n\n try {\n let failures = 0\n // Did this RPC ever answer? A `null` read still answered. Separates\n // \"polled and saw nothing\" from \"never got a word out of this endpoint\".\n let probeSucceeded = false\n // When a read last answered; the branch start until one does. A `null` read\n // counts as an answer - the endpoint is alive and says nothing.\n let lastAnswerAt = now()\n\n // Records WHY the loop ended, because the two reasons earn different\n // verdicts. Reaching the deadline is a complete observation; being aborted\n // mid-read is not. The final probe below is a bonus on top of a complete\n // observation, so losing it must not downgrade the verdict.\n let deadlineReached = false\n // Latched when the loop ends: did the blockhash verdict end it, or the\n // ceiling? Only the verdict may later count as \"dropped\".\n let expiredAtDeadline: bigint | undefined\n while (!signal.aborted) {\n if (deadline.reached()) {\n deadlineReached = true\n expiredAtDeadline = deadline.expiredAt()\n break\n }\n try {\n const value = await probe()\n failures = 0\n lastAnswerAt = now()\n probeSucceeded = true\n if (value !== null) {\n return { kind: 'confirmed', value }\n }\n } catch (error) {\n // `failures` still drives the backoff below; only the give-up rule is\n // time-based.\n failures += 1\n if (now() - lastAnswerAt >= MAX_STATUS_READ_SILENCE_MS) {\n throw error\n }\n }\n // Exponential backoff, so a throttling burst meets a falling rate. The\n // outer `max` stops the cap inverting it for a caller whose base\n // interval already exceeds the cap.\n const delay =\n failures === 0\n ? pollIntervalMs\n : Math.max(\n pollIntervalMs,\n Math.min(\n pollIntervalMs * 2 ** failures,\n STATUS_RETRY_BACKOFF_CAP_MS\n )\n )\n await abortableSleep(delay, signal)\n }\n\n // The status may have flipped between the last poll and the deadline\n // being reached.\n if (!signal.aborted) {\n try {\n const value = await probe()\n probeSucceeded = true\n if (value !== null) {\n return { kind: 'confirmed', value }\n }\n } catch (_) {\n // The loop already ran. One failed final probe is not evidence that\n // this RPC is unusable.\n }\n }\n\n // A completed observation outranks everything below: polled to its own\n // deadline and saw nothing. It stays ahead of the send-failure signal on\n // purpose - a throw here is bucketed as `rpc-unavailable` by `raceRpcs`,\n // which would discard a real observation and misreport a genuinely expired\n // transaction as an outage. The never-broadcast case is answered one level\n // up, in the actions, which know whether ANY branch accepted the send.\n //\n // Keyed on `deadlineReached`, not on `!signal.aborted`: the final probe is\n // a bonus on top of the observation, and the shared BRANCH_TIMEOUT_MS timer\n // can abort that probe in every branch at once. Reading the abort here\n // would discard every observation and report a fleet-wide expiry as an\n // outage.\n if (probeSucceeded && deadlineReached) {\n // `expired` needs the verdict both when the loop ended and now. The\n // detached loop keeps probing through the final probe, and a blockhash\n // that reads valid again withdraws the verdict. A withdrawn verdict and\n // one that arrived only after the ceiling are both no expiry. The slot\n // is the one the deadline reports now.\n const expiredAt =\n expiredAtDeadline === undefined ? undefined : deadline.expiredAt()\n return expiredAt === undefined\n ? { kind: 'not-confirmed' }\n : { kind: 'expired', slot: expiredAt }\n }\n\n if (options.neverBroadcast?.()) {\n throw new Error(`Every ${subject} send to this RPC failed.`)\n }\n\n // Every read hung until the abort: an in-flight read never answers, so it\n // never renews `lastAnswerAt` and never throws either - the abort arrives\n // first. `not-confirmed` here would report a hung endpoint as an expiry.\n if (!probeSucceeded) {\n throw new Error(`No ${read} against this RPC ever completed.`)\n }\n\n // Exiting via `signal.aborted` means the final observation never\n // happened — an in-flight read held the loop until the abort cut it off.\n // An answer received early in the window must not stand in for one near\n // the deadline: a branch that answered once and then went dark has no\n // basis to call the subject of the read expired. (A branch aborted because another\n // RPC already confirmed also throws here; `raceRpcs` drops a losing\n // branch's error once its controller has aborted, so nothing is\n // misreported.)\n throw new Error(\n `This RPC stopped answering before a final ${read} could run.`\n )\n } finally {\n settled = true\n }\n}\n"],"mappings":";;;;;AAMA,MAAa,4BAA4B;;;;;;AAMzC,MAAa,6BAA6B;;;;;;;;;;;;;;;;;AAiB1C,MAAa,8BAA8B;;;;;;;;;AAU3C,eAAsB,kBAAqB,SAiBP;CAClC,MAAM,EAAE,UAAU,QAAQ,gBAAgB,OAAO,MAAM,YAAY;CAC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,MAAM,IAAI,MAAM,SAAS,QAAQ,0BAA0B;EAM7D,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,MAAM,KAAK,kCAAkC;EAW/D,MAAM,IAAI,MACR,6CAA6C,KAAK,YACpD;CACF,UAAU;EACR,UAAU;CACZ;AACF"}
|
|
@@ -3,6 +3,10 @@ import { ConfirmationOutcome } from "./types.js";
|
|
|
3
3
|
export type RaceResult<T> = {
|
|
4
4
|
kind: "confirmed";
|
|
5
5
|
value: T;
|
|
6
|
+
} | {
|
|
7
|
+
kind: "expired";
|
|
8
|
+
slot: bigint;
|
|
9
|
+
errors: Error[];
|
|
6
10
|
} | {
|
|
7
11
|
kind: "not-confirmed";
|
|
8
12
|
errors: Error[];
|
|
@@ -10,6 +14,10 @@ export type RaceResult<T> = {
|
|
|
10
14
|
kind: "rpc-unavailable";
|
|
11
15
|
errors: Error[];
|
|
12
16
|
};
|
|
17
|
+
/** Every result that is not a confirmation. Independent of the value type. */
|
|
18
|
+
export type UnconfirmedRaceResult = Exclude<RaceResult<unknown>, {
|
|
19
|
+
kind: "confirmed";
|
|
20
|
+
}>;
|
|
13
21
|
/**
|
|
14
22
|
* Runs `run` against every RPC in parallel and reports the first confirmation.
|
|
15
23
|
*
|
|
@@ -54,6 +54,7 @@ async function raceRpcs(rpcs, run, options) {
|
|
|
54
54
|
return outcome;
|
|
55
55
|
}));
|
|
56
56
|
const classify = (results) => {
|
|
57
|
+
let expiredAtSlot;
|
|
57
58
|
let sawNotConfirmed = false;
|
|
58
59
|
const errors = [];
|
|
59
60
|
for (const entry of results) {
|
|
@@ -62,7 +63,9 @@ async function raceRpcs(rpcs, run, options) {
|
|
|
62
63
|
kind: "confirmed",
|
|
63
64
|
value: entry.value.value
|
|
64
65
|
};
|
|
65
|
-
|
|
66
|
+
if (entry.value.kind === "expired") {
|
|
67
|
+
if (expiredAtSlot === void 0 || entry.value.slot > expiredAtSlot) expiredAtSlot = entry.value.slot;
|
|
68
|
+
} else sawNotConfirmed = true;
|
|
66
69
|
continue;
|
|
67
70
|
}
|
|
68
71
|
if (controller.signal.aborted) continue;
|
|
@@ -72,6 +75,11 @@ async function raceRpcs(rpcs, run, options) {
|
|
|
72
75
|
kind: "not-confirmed",
|
|
73
76
|
errors
|
|
74
77
|
};
|
|
78
|
+
if (expiredAtSlot !== void 0) return {
|
|
79
|
+
kind: "expired",
|
|
80
|
+
slot: expiredAtSlot,
|
|
81
|
+
errors
|
|
82
|
+
};
|
|
75
83
|
return {
|
|
76
84
|
kind: "rpc-unavailable",
|
|
77
85
|
errors
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raceRpcs.js","names":[],"sources":["../../../src/confirmation/raceRpcs.ts"],"sourcesContent":["import type { ConfirmationOutcome } from './types.js'\n\nexport type RaceResult<T> =\n | { kind: 'confirmed'; value: T }\n | { kind: 'not-confirmed'; errors: Error[] }\n | { kind: 'rpc-unavailable'; errors: Error[] }\n\nconst toError = (reason: unknown): Error =>\n reason instanceof Error ? reason : new Error(String(reason))\n\n/**\n * Aborts when `signal` aborts or `timeoutMs` elapses, whichever is first.\n *\n * Not `AbortSignal.any` + `AbortSignal.timeout`: both are Baseline March 2024,\n * and a published SDK should not raise its runtime floor for a convenience one\n * controller and one timer already cover. The caller's signal is never aborted\n * here, so \"caller aborted\" and \"timeout fired\" stay distinguishable.\n */\nfunction abortAfter(\n signal: AbortSignal,\n timeoutMs: number\n): { signal: AbortSignal; dispose: () => void } {\n const linked = new AbortController()\n const forward = (): void => linked.abort(signal.reason)\n\n const timer = setTimeout(() => {\n linked.abort(new Error(`This RPC did not answer within ${timeoutMs}ms.`))\n }, timeoutMs)\n // A pending timer keeps Node's event loop alive. `dispose` clears it; the\n // unref only covers a path that skips `dispose`.\n const handle = timer as unknown as { unref?: () => void }\n handle.unref?.()\n\n if (signal.aborted) {\n forward()\n } else {\n signal.addEventListener('abort', forward, { once: true })\n }\n\n return {\n signal: linked.signal,\n dispose: (): void => {\n clearTimeout(timer)\n signal.removeEventListener('abort', forward)\n },\n }\n}\n\n/**\n * Runs `run` against every RPC in parallel and reports the first confirmation.\n *\n * Not `Promise.any`: it turns \"polled and saw nothing\" into a thrown sentinel,\n * collapsing the difference between an expired transaction and an RPC that\n * never answered - the defect that reported live swaps as `TransactionExpired`.\n * `timeoutMs` is the caller's; this module holds no confirmation policy.\n */\nexport async function raceRpcs<Rpc, T>(\n rpcs: Rpc[],\n run: (rpc: Rpc, signal: AbortSignal) => Promise<ConfirmationOutcome<T>>,\n options: { timeoutMs: number }\n): Promise<RaceResult<T>> {\n if (rpcs.length === 0) {\n return { kind: 'rpc-unavailable', errors: [] }\n }\n\n const controller = new AbortController()\n // Kept distinct: `controller` means \"another branch confirmed\", the timeout\n // means \"this endpoint never answered\". The timeout aborts the linked signal\n // only.\n const branch = abortAfter(controller.signal, options.timeoutMs)\n\n let resolveConfirmed: ((value: T) => void) | undefined\n const firstConfirmation = new Promise<T>((resolve) => {\n resolveConfirmed = resolve\n })\n\n const settled = Promise.allSettled(\n rpcs.map(async (rpc) => {\n const outcome = await run(rpc, branch.signal)\n if (outcome.kind === 'confirmed') {\n resolveConfirmed?.(outcome.value)\n controller.abort()\n }\n return outcome\n })\n )\n\n const classify = (\n results: PromiseSettledResult<ConfirmationOutcome<T>>[]\n ): RaceResult<T> => {\n let sawNotConfirmed = false\n const errors: Error[] = []\n\n for (const entry of results) {\n if (entry.status === 'fulfilled') {\n // Unreachable today - `firstConfirmation` always wins - but keeps\n // `classify` correct if that structure changes.\n if (entry.value.kind === 'confirmed') {\n return { kind: 'confirmed', value: entry.value.value }\n }\n sawNotConfirmed = true\n continue\n }\n // Cancelled branches are not failures. A branch the timeout killed is,\n // so its error is collected.\n if (controller.signal.aborted) {\n continue\n }\n errors.push(toError(entry.reason))\n }\n\n // A completed observation outranks a thrown error, but the collected\n // errors still travel with it as the expiry's `cause`.\n if (sawNotConfirmed) {\n return { kind: 'not-confirmed', errors }\n }\n return { kind: 'rpc-unavailable', errors }\n }\n\n try {\n const result = await Promise.race([\n firstConfirmation.then(\n (value): RaceResult<T> => ({ kind: 'confirmed', value })\n ),\n settled.then(classify),\n ])\n\n return result\n } finally {\n // Cancels every in-flight branch on every path out, rejections included.\n // Must run before `dispose`, which detaches the listener carrying it.\n controller.abort()\n branch.dispose()\n }\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"raceRpcs.js","names":[],"sources":["../../../src/confirmation/raceRpcs.ts"],"sourcesContent":["import type { ConfirmationOutcome } from './types.js'\n\nexport type RaceResult<T> =\n | { kind: 'confirmed'; value: T }\n /** `slot`: the highest verdict slot of the branches. The transaction can\n * no longer land after it. */\n | { kind: 'expired'; slot: bigint; errors: Error[] }\n | { kind: 'not-confirmed'; errors: Error[] }\n | { kind: 'rpc-unavailable'; errors: Error[] }\n\n/** Every result that is not a confirmation. Independent of the value type. */\nexport type UnconfirmedRaceResult = Exclude<\n RaceResult<unknown>,\n { kind: 'confirmed' }\n>\n\nconst toError = (reason: unknown): Error =>\n reason instanceof Error ? reason : new Error(String(reason))\n\n/**\n * Aborts when `signal` aborts or `timeoutMs` elapses, whichever is first.\n *\n * Not `AbortSignal.any` + `AbortSignal.timeout`: both are Baseline March 2024,\n * and a published SDK should not raise its runtime floor for a convenience one\n * controller and one timer already cover. The caller's signal is never aborted\n * here, so \"caller aborted\" and \"timeout fired\" stay distinguishable.\n */\nfunction abortAfter(\n signal: AbortSignal,\n timeoutMs: number\n): { signal: AbortSignal; dispose: () => void } {\n const linked = new AbortController()\n const forward = (): void => linked.abort(signal.reason)\n\n const timer = setTimeout(() => {\n linked.abort(new Error(`This RPC did not answer within ${timeoutMs}ms.`))\n }, timeoutMs)\n // A pending timer keeps Node's event loop alive. `dispose` clears it; the\n // unref only covers a path that skips `dispose`.\n const handle = timer as unknown as { unref?: () => void }\n handle.unref?.()\n\n if (signal.aborted) {\n forward()\n } else {\n signal.addEventListener('abort', forward, { once: true })\n }\n\n return {\n signal: linked.signal,\n dispose: (): void => {\n clearTimeout(timer)\n signal.removeEventListener('abort', forward)\n },\n }\n}\n\n/**\n * Runs `run` against every RPC in parallel and reports the first confirmation.\n *\n * Not `Promise.any`: it turns \"polled and saw nothing\" into a thrown sentinel,\n * collapsing the difference between an expired transaction and an RPC that\n * never answered - the defect that reported live swaps as `TransactionExpired`.\n * `timeoutMs` is the caller's; this module holds no confirmation policy.\n */\nexport async function raceRpcs<Rpc, T>(\n rpcs: Rpc[],\n run: (rpc: Rpc, signal: AbortSignal) => Promise<ConfirmationOutcome<T>>,\n options: { timeoutMs: number }\n): Promise<RaceResult<T>> {\n if (rpcs.length === 0) {\n return { kind: 'rpc-unavailable', errors: [] }\n }\n\n const controller = new AbortController()\n // Kept distinct: `controller` means \"another branch confirmed\", the timeout\n // means \"this endpoint never answered\". The timeout aborts the linked signal\n // only.\n const branch = abortAfter(controller.signal, options.timeoutMs)\n\n let resolveConfirmed: ((value: T) => void) | undefined\n const firstConfirmation = new Promise<T>((resolve) => {\n resolveConfirmed = resolve\n })\n\n const settled = Promise.allSettled(\n rpcs.map(async (rpc) => {\n const outcome = await run(rpc, branch.signal)\n if (outcome.kind === 'confirmed') {\n resolveConfirmed?.(outcome.value)\n controller.abort()\n }\n return outcome\n })\n )\n\n const classify = (\n results: PromiseSettledResult<ConfirmationOutcome<T>>[]\n ): RaceResult<T> => {\n let expiredAtSlot: bigint | undefined\n let sawNotConfirmed = false\n const errors: Error[] = []\n\n for (const entry of results) {\n if (entry.status === 'fulfilled') {\n // Unreachable today - `firstConfirmation` always wins - but keeps\n // `classify` correct if that structure changes.\n if (entry.value.kind === 'confirmed') {\n return { kind: 'confirmed', value: entry.value.value }\n }\n if (entry.value.kind === 'expired') {\n // The highest verdict slot: the strictest head a dropped check can\n // demand.\n if (expiredAtSlot === undefined || entry.value.slot > expiredAtSlot) {\n expiredAtSlot = entry.value.slot\n }\n } else {\n sawNotConfirmed = true\n }\n continue\n }\n // Cancelled branches are not failures. A branch the timeout killed is,\n // so its error is collected.\n if (controller.signal.aborted) {\n continue\n }\n errors.push(toError(entry.reason))\n }\n\n // A completed observation outranks a thrown error, but the collected\n // errors still travel with it as the expiry's `cause`.\n //\n // Among the observations, the ceiling outranks an expiry: `expired` may\n // end in a final \"dropped\", so every branch that observed has to agree\n // on it. A stale node alone must not drop a transaction that another\n // endpoint still watched to its ceiling.\n if (sawNotConfirmed) {\n return { kind: 'not-confirmed', errors }\n }\n if (expiredAtSlot !== undefined) {\n return { kind: 'expired', slot: expiredAtSlot, errors }\n }\n return { kind: 'rpc-unavailable', errors }\n }\n\n try {\n const result = await Promise.race([\n firstConfirmation.then(\n (value): RaceResult<T> => ({ kind: 'confirmed', value })\n ),\n settled.then(classify),\n ])\n\n return result\n } finally {\n // Cancels every in-flight branch on every path out, rejections included.\n // Must run before `dispose`, which detaches the listener carrying it.\n controller.abort()\n branch.dispose()\n }\n}\n"],"mappings":";;AAgBA,MAAM,WAAW,WACf,kBAAkB,QAAQ,SAAS,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;;;;AAU7D,SAAS,WACP,QACA,WAC8C;CAC9C,MAAM,SAAS,IAAI,gBAAgB;CACnC,MAAM,gBAAsB,OAAO,MAAM,OAAO,MAAM;CAEtD,MAAM,QAAQ,iBAAiB;EAC7B,OAAO,sBAAM,IAAI,MAAM,kCAAkC,UAAU,IAAI,CAAC;CAC1E,GAAG,SAAS;CAIZ,MAAO,QAAQ;CAEf,IAAI,OAAO,SACT,QAAQ;MAER,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAG1D,OAAO;EACL,QAAQ,OAAO;EACf,eAAqB;GACnB,aAAa,KAAK;GAClB,OAAO,oBAAoB,SAAS,OAAO;EAC7C;CACF;AACF;;;;;;;;;AAUA,eAAsB,SACpB,MACA,KACA,SACwB;CACxB,IAAI,KAAK,WAAW,GAClB,OAAO;EAAE,MAAM;EAAmB,QAAQ,CAAC;CAAE;CAG/C,MAAM,aAAa,IAAI,gBAAgB;CAIvC,MAAM,SAAS,WAA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["import type { Commitment } from '@solana/kit'\nimport type { SolanaRpcType } from '../rpc/types.js'\n\ntype SignatureStatusesResponse = Awaited<\n ReturnType<ReturnType<SolanaRpcType['getSignatureStatuses']>['send']>\n>\n\n/** Derived from the RPC type rather than hand-written, which removes every\n * `as SignatureStatus` cast. A `JitoRpcType` response assigns without one. */\nexport type SignatureStatus = NonNullable<\n SignatureStatusesResponse['value'][number]\n>\n\n/** What a single RPC branch is allowed to report. Failure is a throw. */\nexport type ConfirmationOutcome<T> =\n | { kind: 'confirmed'; value: T }\n | { kind: 'not-confirmed' }\n\nexport function isConfirmedCommitment(\n status: Commitment | string | null | undefined\n): boolean {\n return status === 'confirmed' || status === 'finalized'\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../src/confirmation/types.ts"],"sourcesContent":["import type { Commitment } from '@solana/kit'\nimport type { SolanaRpcType } from '../rpc/types.js'\n\ntype SignatureStatusesResponse = Awaited<\n ReturnType<ReturnType<SolanaRpcType['getSignatureStatuses']>['send']>\n>\n\n/** Derived from the RPC type rather than hand-written, which removes every\n * `as SignatureStatus` cast. A `JitoRpcType` response assigns without one. */\nexport type SignatureStatus = NonNullable<\n SignatureStatusesResponse['value'][number]\n>\n\n/** What a single RPC branch is allowed to report. Failure is a throw. */\nexport type ConfirmationOutcome<T> =\n | { kind: 'confirmed'; value: T }\n /** The blockhash probe confirmed expiry: the transaction can no longer\n * land after `slot`, the `isBlockhashValid` context slot of the verdict.\n * The only outcome that may end in a final \"dropped\". */\n | { kind: 'expired'; slot: bigint }\n /** The wall-clock ceiling ended the observation without a verdict. */\n | { kind: 'not-confirmed' }\n\nexport function isConfirmedCommitment(\n status: Commitment | string | null | undefined\n): boolean {\n return status === 'confirmed' || status === 'finalized'\n}\n"],"mappings":";;AAuBA,SAAgB,sBACd,QACS;CACT,OAAO,WAAW,eAAe,WAAW;AAC9C"}
|
|
@@ -19,12 +19,10 @@ var SolanaStepExecutor = class extends _lifi_sdk.BaseStepExecutor {
|
|
|
19
19
|
};
|
|
20
20
|
parseErrors = (error, step, action) => require_errors_parseSolanaErrors.parseSolanaErrors(error, step, action);
|
|
21
21
|
createContext = async (baseContext) => {
|
|
22
|
-
const { step } = baseContext;
|
|
23
|
-
const walletAccount = this.getWalletAccount(step);
|
|
24
22
|
return {
|
|
25
23
|
...baseContext,
|
|
26
24
|
wallet: this.wallet,
|
|
27
|
-
|
|
25
|
+
getWalletAccount: this.getWalletAccount,
|
|
28
26
|
skipSimulation: this.skipSimulation
|
|
29
27
|
};
|
|
30
28
|
};
|
|
@@ -38,7 +36,7 @@ var SolanaStepExecutor = class extends _lifi_sdk.BaseStepExecutor {
|
|
|
38
36
|
new _lifi_sdk.WaitForTransactionStatusTask(isBridgeExecution ? "RECEIVING_CHAIN" : "SWAP")
|
|
39
37
|
];
|
|
40
38
|
const swapOrBridgeAction = this.statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
|
|
41
|
-
const firstTask = swapOrBridgeAction
|
|
39
|
+
const firstTask = (0, _lifi_sdk.hasOpenTransaction)(swapOrBridgeAction) ? swapOrBridgeAction?.status === "DONE" ? _lifi_sdk.WaitForTransactionStatusTask : require_core_tasks_SolanaWaitForTransactionTask.SolanaWaitForTransactionTask : _lifi_sdk.CheckBalanceTask;
|
|
42
40
|
const firstTaskIndex = tasks.findIndex((task) => task.constructor === firstTask);
|
|
43
41
|
if (firstTaskIndex === -1) throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.InternalError, "SolanaStepExecutor.createPipeline: first task not found");
|
|
44
42
|
const tasksToRun = tasks.slice(firstTaskIndex);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SolanaStepExecutor.js","names":["BaseStepExecutor","TransactionError","LiFiErrorCode","parseSolanaErrors","CheckBalanceTask","PrepareTransactionTask","SolanaSignAndExecuteTask","SolanaWaitForTransactionTask","WaitForTransactionStatusTask","TaskPipeline"],"sources":["../../../src/core/SolanaStepExecutor.ts"],"sourcesContent":["import {\n BaseStepExecutor,\n CheckBalanceTask,\n type ExecutionAction,\n LiFiErrorCode,\n type LiFiStepExtended,\n PrepareTransactionTask,\n type SDKError,\n type StepExecutorBaseContext,\n TaskPipeline,\n TransactionError,\n WaitForTransactionStatusTask,\n} from '@lifi/sdk'\nimport type { Wallet, WalletAccount } from '@wallet-standard/base'\nimport { parseSolanaErrors } from '../errors/parseSolanaErrors.js'\nimport type {\n SolanaStepExecutorContext,\n SolanaStepExecutorOptions,\n} from '../types.js'\nimport { SolanaSignAndExecuteTask } from './tasks/SolanaSignAndExecuteTask.js'\nimport { SolanaWaitForTransactionTask } from './tasks/SolanaWaitForTransactionTask.js'\n\nexport class SolanaStepExecutor extends BaseStepExecutor {\n private wallet: Wallet\n private skipSimulation: boolean\n\n constructor(options: SolanaStepExecutorOptions) {\n super(options)\n this.wallet = options.wallet\n this.skipSimulation = options.skipSimulation ?? false\n }\n\n getWalletAccount = (step: LiFiStepExtended): WalletAccount => {\n const account = this.wallet.accounts.find(\n (account) => account.address === step.action.fromAddress\n )\n\n if (!account) {\n throw new TransactionError(\n LiFiErrorCode.WalletChangedDuringExecution,\n 'The wallet address that requested the quote does not match the wallet address attempting to sign the transaction.'\n )\n }\n\n return account\n }\n\n override parseErrors = (\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction\n ): Promise<SDKError> => parseSolanaErrors(error, step, action)\n\n override createContext = async (\n baseContext: StepExecutorBaseContext\n ): Promise<SolanaStepExecutorContext> => {\n
|
|
1
|
+
{"version":3,"file":"SolanaStepExecutor.js","names":["BaseStepExecutor","TransactionError","LiFiErrorCode","parseSolanaErrors","CheckBalanceTask","PrepareTransactionTask","SolanaSignAndExecuteTask","SolanaWaitForTransactionTask","WaitForTransactionStatusTask","hasOpenTransaction","TaskPipeline"],"sources":["../../../src/core/SolanaStepExecutor.ts"],"sourcesContent":["import {\n BaseStepExecutor,\n CheckBalanceTask,\n type ExecutionAction,\n hasOpenTransaction,\n LiFiErrorCode,\n type LiFiStepExtended,\n PrepareTransactionTask,\n type SDKError,\n type StepExecutorBaseContext,\n TaskPipeline,\n TransactionError,\n WaitForTransactionStatusTask,\n} from '@lifi/sdk'\nimport type { Wallet, WalletAccount } from '@wallet-standard/base'\nimport { parseSolanaErrors } from '../errors/parseSolanaErrors.js'\nimport type {\n SolanaStepExecutorContext,\n SolanaStepExecutorOptions,\n} from '../types.js'\nimport { SolanaSignAndExecuteTask } from './tasks/SolanaSignAndExecuteTask.js'\nimport { SolanaWaitForTransactionTask } from './tasks/SolanaWaitForTransactionTask.js'\n\nexport class SolanaStepExecutor extends BaseStepExecutor {\n private wallet: Wallet\n private skipSimulation: boolean\n\n constructor(options: SolanaStepExecutorOptions) {\n super(options)\n this.wallet = options.wallet\n this.skipSimulation = options.skipSimulation ?? false\n }\n\n getWalletAccount = (step: LiFiStepExtended): WalletAccount => {\n const account = this.wallet.accounts.find(\n (account) => account.address === step.action.fromAddress\n )\n\n if (!account) {\n throw new TransactionError(\n LiFiErrorCode.WalletChangedDuringExecution,\n 'The wallet address that requested the quote does not match the wallet address attempting to sign the transaction.'\n )\n }\n\n return account\n }\n\n override parseErrors = (\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction\n ): Promise<SDKError> => parseSolanaErrors(error, step, action)\n\n override createContext = async (\n baseContext: StepExecutorBaseContext\n ): Promise<SolanaStepExecutorContext> => {\n // The account is resolved by the sign task, not here: a resume that only\n // waits must not fail because the wallet has not reconnected yet.\n return {\n ...baseContext,\n wallet: this.wallet,\n getWalletAccount: this.getWalletAccount,\n skipSimulation: this.skipSimulation,\n }\n }\n\n override createPipeline = (\n context: SolanaStepExecutorContext\n ): TaskPipeline => {\n const { step, isBridgeExecution } = context\n\n const tasks = [\n new CheckBalanceTask(),\n new PrepareTransactionTask(),\n new SolanaSignAndExecuteTask(),\n new SolanaWaitForTransactionTask(),\n new WaitForTransactionStatusTask(\n isBridgeExecution ? 'RECEIVING_CHAIN' : 'SWAP'\n ),\n ]\n\n const swapOrBridgeAction = this.statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n // Three-way, as Stellar and Bitcoin do. An open transaction - a broadcast\n // signature, or signed bytes that may have been sent - resumes at the\n // wait task, which looks it up and resends the same bytes. Starting at\n // CheckBalanceTask would fetch a new quote and sign a second transaction\n // while the first can still land. A same-chain swap stays PENDING with\n // its signature until the LI.FI status is DONE, so this is the common\n // reload.\n const firstTask = hasOpenTransaction(swapOrBridgeAction)\n ? swapOrBridgeAction?.status === 'DONE'\n ? WaitForTransactionStatusTask\n : SolanaWaitForTransactionTask\n : CheckBalanceTask\n\n // Compare classes, not names: a minifier can give two task classes the\n // same name.\n const firstTaskIndex = tasks.findIndex(\n (task) => task.constructor === firstTask\n )\n if (firstTaskIndex === -1) {\n throw new TransactionError(\n LiFiErrorCode.InternalError,\n 'SolanaStepExecutor.createPipeline: first task not found'\n )\n }\n\n const tasksToRun = tasks.slice(firstTaskIndex)\n\n return new TaskPipeline(tasksToRun)\n }\n}\n"],"mappings":";;;;;;AAuBA,IAAa,qBAAb,cAAwCA,UAAAA,iBAAiB;CACvD;CACA;CAEA,YAAY,SAAoC;EAC9C,MAAM,OAAO;EACb,KAAK,SAAS,QAAQ;EACtB,KAAK,iBAAiB,QAAQ,kBAAkB;CAClD;CAEA,oBAAoB,SAA0C;EAC5D,MAAM,UAAU,KAAK,OAAO,SAAS,MAClC,YAAY,QAAQ,YAAY,KAAK,OAAO,WAC/C;EAEA,IAAI,CAAC,SACH,MAAM,IAAIC,UAAAA,iBACRC,UAAAA,cAAc,8BACd,mHACF;EAGF,OAAO;CACT;CAEA,eACE,OACA,MACA,WACsBC,iCAAAA,kBAAkB,OAAO,MAAM,MAAM;CAE7D,gBAAyB,OACvB,gBACuC;EAGvC,OAAO;GACL,GAAG;GACH,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB,gBAAgB,KAAK;EACvB;CACF;CAEA,kBACE,YACiB;EACjB,MAAM,EAAE,MAAM,sBAAsB;EAEpC,MAAM,QAAQ;GACZ,IAAIC,UAAAA,iBAAiB;GACrB,IAAIC,UAAAA,uBAAuB;GAC3B,IAAIC,4CAAAA,yBAAyB;GAC7B,IAAIC,gDAAAA,6BAA6B;GACjC,IAAIC,UAAAA,6BACF,oBAAoB,oBAAoB,MAC1C;EACF;EAEA,MAAM,qBAAqB,KAAK,cAAc,WAC5C,MACA,oBAAoB,gBAAgB,MACtC;EASA,MAAM,aAAA,GAAYC,UAAAA,mBAAAA,CAAmB,kBAAkB,IACnD,oBAAoB,WAAW,SAC7BD,UAAAA,+BACAD,gDAAAA,+BACFH,UAAAA;EAIJ,MAAM,iBAAiB,MAAM,WAC1B,SAAS,KAAK,gBAAgB,SACjC;EACA,IAAI,mBAAmB,IACrB,MAAM,IAAIH,UAAAA,iBACRC,UAAAA,cAAc,eACd,yDACF;EAGF,MAAM,aAAa,MAAM,MAAM,cAAc;EAE7C,OAAO,IAAIQ,UAAAA,aAAa,UAAU;CACpC;AACF"}
|
|
@@ -1,55 +1,91 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_actions_sendAndConfirmBundle = require("../../actions/sendAndConfirmBundle.js");
|
|
3
|
-
const require_utils_solanaErrorCause = require("../../utils/solanaErrorCause.js");
|
|
4
2
|
const require_core_tasks_readSignature = require("./readSignature.js");
|
|
5
|
-
const
|
|
3
|
+
const require_utils_getTransactionLifetime = require("../../utils/getTransactionLifetime.js");
|
|
4
|
+
const require_actions_sendAndConfirmBundle = require("../../actions/sendAndConfirmBundle.js");
|
|
5
|
+
const require_core_tasks_transactionOutcome = require("./transactionOutcome.js");
|
|
6
|
+
const require_core_tasks_resumeFromStore = require("./resumeFromStore.js");
|
|
6
7
|
let _lifi_sdk = require("@lifi/sdk");
|
|
7
8
|
//#region src/core/tasks/SolanaJitoWaitForTransactionTask.ts
|
|
9
|
+
const MESSAGES = {
|
|
10
|
+
rpcUnavailable: "Unable to confirm bundle: every configured Jito RPC failed.",
|
|
11
|
+
notConfirmed: "Bundle was not confirmed before the SDK stopped waiting.",
|
|
12
|
+
allRpcsFailed: "All Jito RPCs failed",
|
|
13
|
+
someRpcsFailed: "Some Jito RPCs failed while the confirmation window was open"
|
|
14
|
+
};
|
|
8
15
|
/** Jito encodes `err` as a Rust `Result`: a landed bundle carries
|
|
9
16
|
* `{ Ok: null }`, so only an explicit `{ Err: … }` counts as a failure. */
|
|
10
17
|
function getBundleFailure(err) {
|
|
11
18
|
if (typeof err !== "object" || err === null || !("Err" in err)) return;
|
|
12
19
|
return { failure: err.Err };
|
|
13
20
|
}
|
|
21
|
+
/** The failure of a landed bundle, if any. A `null` in `signatureResults` is
|
|
22
|
+
* indexing lag, never failure. The bundle-level `err` is checked first: it
|
|
23
|
+
* survives a failed `getSignatureStatuses` read. */
|
|
24
|
+
function bundleFailureOf(confirmation) {
|
|
25
|
+
const bundleFailure = getBundleFailure(confirmation.bundleErr);
|
|
26
|
+
if (bundleFailure) return { err: bundleFailure.failure };
|
|
27
|
+
const failedResult = confirmation.signatureResults.find((signatureResult) => signatureResult?.err);
|
|
28
|
+
return failedResult?.err ? { err: failedResult.err } : void 0;
|
|
29
|
+
}
|
|
14
30
|
var SolanaJitoWaitForTransactionTask = class extends _lifi_sdk.BaseStepExecutionTask {
|
|
15
31
|
async run(context) {
|
|
16
|
-
const {
|
|
17
|
-
const signedTransactions = contextSignedTransactions ?? [];
|
|
32
|
+
const { step, statusManager, isBridgeExecution, signedTransactions } = context;
|
|
18
33
|
const action = statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
|
|
19
34
|
if (!action) throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionUnprepared, "Unable to prepare transaction. Action not found.");
|
|
20
|
-
if (!signedTransactions
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
})
|
|
28
|
-
} });
|
|
29
|
-
const bundleResult = require_core_tasks_unwrapConfirmation.unwrapConfirmation(result, {
|
|
30
|
-
rpcUnavailable: "Unable to confirm bundle: every configured Jito RPC failed.",
|
|
31
|
-
notConfirmed: "Bundle was not confirmed before the SDK stopped waiting.",
|
|
32
|
-
allRpcsFailed: "All Jito RPCs failed",
|
|
33
|
-
someRpcsFailed: "Some Jito RPCs failed while the confirmation window was open"
|
|
35
|
+
if (!signedTransactions) return require_core_tasks_resumeFromStore.resumeFromStore(context, action, {
|
|
36
|
+
messages: MESSAGES,
|
|
37
|
+
send: (stored, lifetimes) => sendSigned(context, action, {
|
|
38
|
+
transactions: stored.transactions,
|
|
39
|
+
signature: stored.signature,
|
|
40
|
+
lifetimes,
|
|
41
|
+
resuming: true
|
|
42
|
+
})
|
|
34
43
|
});
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const cause = new require_utils_solanaErrorCause.SolanaTransactionDetailsError(failedResult.err);
|
|
43
|
-
throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionFailed, `Transaction failed: ${cause.message}`, cause);
|
|
44
|
+
if (!signedTransactions.length) throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionUnprepared, "Unable to prepare transaction. Signed transactions are not found.");
|
|
45
|
+
let txSignature;
|
|
46
|
+
try {
|
|
47
|
+
txSignature = require_core_tasks_readSignature.readSignature(signedTransactions[0]);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
require_core_tasks_transactionOutcome.clearStoredTransactions(context, action);
|
|
50
|
+
throw error;
|
|
44
51
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
52
|
+
const lifetimes = await Promise.all(signedTransactions.map((transaction) => require_utils_getTransactionLifetime.getTransactionLifetime(transaction)));
|
|
53
|
+
return sendSigned(context, action, {
|
|
54
|
+
transactions: signedTransactions,
|
|
55
|
+
signature: txSignature,
|
|
56
|
+
lifetimes,
|
|
57
|
+
resuming: false
|
|
48
58
|
});
|
|
49
|
-
if (isBridgeExecution) statusManager.updateAction(step, action.type, "DONE");
|
|
50
|
-
return { status: "COMPLETED" };
|
|
51
59
|
}
|
|
52
60
|
};
|
|
61
|
+
/**
|
|
62
|
+
* Submits the signed bundle once, confirms it and applies the result rules
|
|
63
|
+
* of `sendAndSettle`, on the first run and on a resume alike. A bundle lands
|
|
64
|
+
* whole or not at all, so the first transaction's signature stands for it.
|
|
65
|
+
*/
|
|
66
|
+
function sendSigned(context, action, options) {
|
|
67
|
+
const { client, step, statusManager } = context;
|
|
68
|
+
const { transactions, signature, lifetimes, resuming } = options;
|
|
69
|
+
const txLink = require_core_tasks_transactionOutcome.getTxLink(context, signature);
|
|
70
|
+
return require_core_tasks_transactionOutcome.sendAndSettle(context, action, {
|
|
71
|
+
signature,
|
|
72
|
+
send: async () => {
|
|
73
|
+
if (!require_core_tasks_transactionOutcome.canResendStored(lifetimes, step.execution?.signedAt)) return {
|
|
74
|
+
kind: "not-confirmed",
|
|
75
|
+
errors: [/* @__PURE__ */ new Error("The resend age cap has passed; the stored bundle is not sent.")]
|
|
76
|
+
};
|
|
77
|
+
return require_actions_sendAndConfirmBundle.sendAndConfirmBundle(client, transactions, { onBroadcast: () => {
|
|
78
|
+
statusManager.updateAction(step, action.type, "PENDING", {
|
|
79
|
+
txHash: signature,
|
|
80
|
+
txLink
|
|
81
|
+
});
|
|
82
|
+
} });
|
|
83
|
+
},
|
|
84
|
+
confirmedFailure: bundleFailureOf,
|
|
85
|
+
resuming,
|
|
86
|
+
messages: MESSAGES
|
|
87
|
+
});
|
|
88
|
+
}
|
|
53
89
|
//#endregion
|
|
54
90
|
exports.SolanaJitoWaitForTransactionTask = SolanaJitoWaitForTransactionTask;
|
|
55
91
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SolanaJitoWaitForTransactionTask.js","names":["BaseStepExecutionTask","TransactionError","LiFiErrorCode","readSignature","
|
|
1
|
+
{"version":3,"file":"SolanaJitoWaitForTransactionTask.js","names":["BaseStepExecutionTask","TransactionError","LiFiErrorCode","resumeFromStore","readSignature","getTransactionLifetime","getTxLink","sendAndSettle","canResendStored","sendAndConfirmBundle"],"sources":["../../../../src/core/tasks/SolanaJitoWaitForTransactionTask.ts"],"sourcesContent":["import {\n BaseStepExecutionTask,\n type ExecutionAction,\n LiFiErrorCode,\n type TaskResult,\n TransactionError,\n} from '@lifi/sdk'\nimport type { Signature, Transaction } from '@solana/kit'\nimport { sendAndConfirmBundle } from '../../actions/sendAndConfirmBundle.js'\nimport type { BundleConfirmation } from '../../confirmation/confirmBundle.js'\nimport type { RaceResult } from '../../confirmation/raceRpcs.js'\nimport type { SolanaStepExecutorContext } from '../../types.js'\nimport {\n getTransactionLifetime,\n type TransactionLifetime,\n} from '../../utils/getTransactionLifetime.js'\nimport type { ConfirmationMessages } from './confirmationError.js'\nimport { readSignature } from './readSignature.js'\nimport { resumeFromStore } from './resumeFromStore.js'\nimport {\n canResendStored,\n clearStoredTransactions,\n getTxLink,\n sendAndSettle,\n} from './transactionOutcome.js'\n\n// The `rpc-unavailable` message is distinct from the empty-list throw inside\n// `sendAndConfirmBundle`: RPCs were configured and every one of them failed.\n// That is an outage, and the collected branch errors say what each endpoint\n// did.\nconst MESSAGES: ConfirmationMessages = {\n rpcUnavailable: 'Unable to confirm bundle: every configured Jito RPC failed.',\n notConfirmed: 'Bundle was not confirmed before the SDK stopped waiting.',\n allRpcsFailed: 'All Jito RPCs failed',\n someRpcsFailed:\n 'Some Jito RPCs failed while the confirmation window was open',\n}\n\n/** Jito encodes `err` as a Rust `Result`: a landed bundle carries\n * `{ Ok: null }`, so only an explicit `{ Err: … }` counts as a failure. */\nfunction getBundleFailure(err: unknown): { failure: unknown } | undefined {\n if (typeof err !== 'object' || err === null || !('Err' in err)) {\n return undefined\n }\n return { failure: (err as { Err: unknown }).Err }\n}\n\n/** The failure of a landed bundle, if any. A `null` in `signatureResults` is\n * indexing lag, never failure. The bundle-level `err` is checked first: it\n * survives a failed `getSignatureStatuses` read. */\nfunction bundleFailureOf(\n confirmation: BundleConfirmation\n): { err: unknown } | undefined {\n const bundleFailure = getBundleFailure(confirmation.bundleErr)\n if (bundleFailure) {\n return { err: bundleFailure.failure }\n }\n const failedResult = confirmation.signatureResults.find(\n (signatureResult) => signatureResult?.err\n )\n return failedResult?.err ? { err: failedResult.err } : undefined\n}\n\nexport class SolanaJitoWaitForTransactionTask extends BaseStepExecutionTask {\n async run(context: SolanaStepExecutorContext): Promise<TaskResult> {\n const { step, statusManager, isBridgeExecution, signedTransactions } =\n context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n // Resume mode: the sign task did not run in this session, so the signed\n // bundle comes from `txHex`, or only the first hash from `txHash`.\n if (!signedTransactions) {\n return resumeFromStore(context, action, {\n messages: MESSAGES,\n // Submitted once, as on the first run.\n send: (stored, lifetimes) =>\n sendSigned(context, action, {\n transactions: stored.transactions,\n signature: stored.signature,\n lifetimes,\n resuming: true,\n }),\n })\n }\n\n if (!signedTransactions.length) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Signed transactions are not found.'\n )\n }\n\n let txSignature: Signature\n try {\n txSignature = readSignature(signedTransactions[0])\n } catch (error) {\n // Nothing left the SDK: the bytes go, so \"Try again\" signs again.\n clearStoredTransactions(context, action)\n throw error\n }\n\n const lifetimes = await Promise.all(\n signedTransactions.map((transaction) =>\n getTransactionLifetime(transaction)\n )\n )\n\n return sendSigned(context, action, {\n transactions: signedTransactions,\n signature: txSignature,\n lifetimes,\n resuming: false,\n })\n }\n}\n\n/**\n * Submits the signed bundle once, confirms it and applies the result rules\n * of `sendAndSettle`, on the first run and on a resume alike. A bundle lands\n * whole or not at all, so the first transaction's signature stands for it.\n */\nfunction sendSigned(\n context: SolanaStepExecutorContext,\n action: ExecutionAction,\n options: {\n transactions: Transaction[]\n signature: Signature\n lifetimes: TransactionLifetime[]\n /** An earlier run may already have submitted this bundle. */\n resuming: boolean\n }\n): Promise<TaskResult> {\n const { client, step, statusManager } = context\n const { transactions, signature, lifetimes, resuming } = options\n const txLink = getTxLink(context, signature)\n\n return sendAndSettle(context, action, {\n signature,\n send: async (): Promise<RaceResult<BundleConfirmation>> => {\n // Read right before the one submission: a bundle without its own\n // expiry goes out only inside the resend age cap. Past it nothing is\n // sent, and the outcome stays unknown until the dropped rule holds.\n if (!canResendStored(lifetimes, step.execution?.signedAt)) {\n return {\n kind: 'not-confirmed',\n errors: [\n new Error(\n 'The resend age cap has passed; the stored bundle is not sent.'\n ),\n ],\n }\n }\n // An empty Jito RPC list - the configuration gap, as opposed to an\n // outage - throws inside `sendAndConfirmBundle` with its own message,\n // before anything is submitted.\n return sendAndConfirmBundle(client, transactions, {\n onBroadcast: () => {\n // The earliest honest point for both: an RPC has accepted the\n // transaction, so the signature now resolves on chain.\n statusManager.updateAction(step, action.type, 'PENDING', {\n txHash: signature,\n txLink,\n })\n },\n })\n },\n confirmedFailure: bundleFailureOf,\n resuming,\n messages: MESSAGES,\n })\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,WAAiC;CACrC,gBAAgB;CAChB,cAAc;CACd,eAAe;CACf,gBACE;AACJ;;;AAIA,SAAS,iBAAiB,KAAgD;CACxE,IAAI,OAAO,QAAQ,YAAY,QAAQ,QAAQ,EAAE,SAAS,MACxD;CAEF,OAAO,EAAE,SAAU,IAAyB,IAAI;AAClD;;;;AAKA,SAAS,gBACP,cAC8B;CAC9B,MAAM,gBAAgB,iBAAiB,aAAa,SAAS;CAC7D,IAAI,eACF,OAAO,EAAE,KAAK,cAAc,QAAQ;CAEtC,MAAM,eAAe,aAAa,iBAAiB,MAChD,oBAAoB,iBAAiB,G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AM;IACN,QAAQ,iBACN,IAAI,MACF,+DACF,CACF;GACF;GAKF,OAAOC,qCAAAA,qBAAqB,QAAQ,cAAc,EAChD,mBAAmB;IAGjB,cAAc,aAAa,MAAM,OAAO,MAAM,WAAW;KACvD,QAAQ;KACR;IACF,CAAC;GACH,EACF,CAAC;EACH;EACA,kBAAkB;EAClB;EACA,UAAU;CACZ,CAAC;AACH"}
|
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_utils_base64ToUint8Array = require("../../utils/base64ToUint8Array.js");
|
|
3
3
|
const require_utils_getWalletFeature = require("../../utils/getWalletFeature.js");
|
|
4
|
+
const require_utils_storedTransactions = require("../../utils/storedTransactions.js");
|
|
5
|
+
const require_core_tasks_readSignature = require("./readSignature.js");
|
|
4
6
|
let _lifi_sdk = require("@lifi/sdk");
|
|
5
7
|
let _solana_kit = require("@solana/kit");
|
|
6
8
|
let _solana_wallet_standard_features = require("@solana/wallet-standard-features");
|
|
7
9
|
//#region src/core/tasks/SolanaSignAndExecuteTask.ts
|
|
8
10
|
var SolanaSignAndExecuteTask = class extends _lifi_sdk.BaseStepExecutionTask {
|
|
9
11
|
async run(context) {
|
|
10
|
-
const { step, wallet,
|
|
12
|
+
const { step, wallet, getWalletAccount, statusManager, executionOptions, isBridgeExecution } = context;
|
|
11
13
|
const action = statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
|
|
14
|
+
(0, _lifi_sdk.assertNoOpenTransaction)(action);
|
|
12
15
|
if (!action) throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionUnprepared, "Unable to prepare transaction. Action not found.");
|
|
16
|
+
const walletAccount = getWalletAccount(step);
|
|
13
17
|
const transactionRequestData = await (0, _lifi_sdk.getTransactionRequestData)(step, executionOptions);
|
|
14
18
|
const isBundleExecution = Array.isArray(transactionRequestData);
|
|
15
19
|
const transactionBytesArray = (isBundleExecution ? transactionRequestData : [transactionRequestData]).map((data) => require_utils_base64ToUint8Array.base64ToUint8Array(data));
|
|
20
|
+
(0, _lifi_sdk.assertNoOpenTransaction)(statusManager.findAction(step, action.type));
|
|
16
21
|
const signedTransactionOutputs = await (0, _lifi_sdk.withTimeout)(async () => {
|
|
17
22
|
const { signTransaction } = require_utils_getWalletFeature.getWalletFeature(wallet, _solana_wallet_standard_features.SolanaSignTransaction);
|
|
18
23
|
return signTransaction(...transactionBytesArray.map((transaction) => ({
|
|
@@ -23,17 +28,20 @@ var SolanaSignAndExecuteTask = class extends _lifi_sdk.BaseStepExecutionTask {
|
|
|
23
28
|
timeout: 12e4,
|
|
24
29
|
errorInstance: new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionExpired, "Transaction has expired: blockhash is no longer recent enough.")
|
|
25
30
|
});
|
|
31
|
+
(0, _lifi_sdk.assertNoOpenTransaction)(statusManager.findAction(step, action.type));
|
|
26
32
|
if (signedTransactionOutputs.length === 0) throw new _lifi_sdk.TransactionError(_lifi_sdk.LiFiErrorCode.TransactionUnprepared, "No signed transaction returned from signer.");
|
|
27
33
|
statusManager.updateAction(step, action.type, "PENDING", {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
txLink: void 0
|
|
34
|
+
..._lifi_sdk.CLEARED_TRANSACTION_FIELDS,
|
|
35
|
+
signedAt: Date.now()
|
|
31
36
|
});
|
|
32
37
|
const transactionCodec = (0, _solana_kit.getTransactionCodec)();
|
|
38
|
+
const signedTransactions = signedTransactionOutputs.map((output) => transactionCodec.decode(output.signedTransaction));
|
|
39
|
+
for (const signedTransaction of signedTransactions) require_core_tasks_readSignature.readSignature(signedTransaction);
|
|
40
|
+
statusManager.updateAction(step, action.type, "PENDING", { txHex: require_utils_storedTransactions.encodeStoredTransactions(signedTransactionOutputs.map((output) => output.signedTransaction), isBundleExecution) });
|
|
33
41
|
return {
|
|
34
42
|
status: "COMPLETED",
|
|
35
43
|
context: {
|
|
36
|
-
signedTransactions
|
|
44
|
+
signedTransactions,
|
|
37
45
|
isBundleExecution
|
|
38
46
|
}
|
|
39
47
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SolanaSignAndExecuteTask.js","names":["BaseStepExecutionTask","TransactionError","LiFiErrorCode","getTransactionRequestData","base64ToUint8Array","withTimeout","getWalletFeature","SolanaSignTransaction","getTransactionCodec"],"sources":["../../../../src/core/tasks/SolanaSignAndExecuteTask.ts"],"sourcesContent":["import {\n BaseStepExecutionTask,\n getTransactionRequestData,\n LiFiErrorCode,\n type TaskResult,\n TransactionError,\n withTimeout,\n} from '@lifi/sdk'\nimport { getTransactionCodec } from '@solana/kit'\nimport { SolanaSignTransaction } from '@solana/wallet-standard-features'\nimport type { SolanaStepExecutorContext } from '../../types.js'\nimport { base64ToUint8Array } from '../../utils/base64ToUint8Array.js'\nimport { getWalletFeature } from '../../utils/getWalletFeature.js'\n\nexport class SolanaSignAndExecuteTask extends BaseStepExecutionTask {\n async run(context: SolanaStepExecutorContext): Promise<TaskResult> {\n const {\n step,\n wallet,\n
|
|
1
|
+
{"version":3,"file":"SolanaSignAndExecuteTask.js","names":["BaseStepExecutionTask","TransactionError","LiFiErrorCode","getTransactionRequestData","base64ToUint8Array","withTimeout","getWalletFeature","SolanaSignTransaction","CLEARED_TRANSACTION_FIELDS","getTransactionCodec","encodeStoredTransactions"],"sources":["../../../../src/core/tasks/SolanaSignAndExecuteTask.ts"],"sourcesContent":["import {\n assertNoOpenTransaction,\n BaseStepExecutionTask,\n CLEARED_TRANSACTION_FIELDS,\n getTransactionRequestData,\n LiFiErrorCode,\n type TaskResult,\n TransactionError,\n withTimeout,\n} from '@lifi/sdk'\nimport { getTransactionCodec } from '@solana/kit'\nimport { SolanaSignTransaction } from '@solana/wallet-standard-features'\nimport type { SolanaStepExecutorContext } from '../../types.js'\nimport { base64ToUint8Array } from '../../utils/base64ToUint8Array.js'\nimport { getWalletFeature } from '../../utils/getWalletFeature.js'\nimport { encodeStoredTransactions } from '../../utils/storedTransactions.js'\nimport { readSignature } from './readSignature.js'\n\nexport class SolanaSignAndExecuteTask extends BaseStepExecutionTask {\n async run(context: SolanaStepExecutorContext): Promise<TaskResult> {\n const {\n step,\n wallet,\n getWalletAccount,\n statusManager,\n executionOptions,\n isBridgeExecution,\n } = context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n // Defence in depth: the selector sends an action with an open\n // transaction to the wait task. Signing here could put a second\n // transaction on chain while the first can still land.\n assertNoOpenTransaction(action)\n\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n // Resolved here and not in `createContext`: a resume that only waits\n // never signs, so it must not fail because the wallet has not\n // reconnected yet.\n const walletAccount = getWalletAccount(step)\n\n const transactionRequestData = (await getTransactionRequestData(\n step,\n executionOptions\n )) as string | string[]\n\n // The backend returns an array when it produced a Jito bundle and a string\n // for a single transaction. The shape determines how we submit it later:\n // array -> sendBundle, string -> sendTransaction.\n const isBundleExecution = Array.isArray(transactionRequestData)\n\n const transactionDataArray = isBundleExecution\n ? transactionRequestData\n : [transactionRequestData]\n\n const transactionBytesArray = transactionDataArray.map((data) =>\n base64ToUint8Array(data)\n )\n\n // Checked again right before the wallet: a late write of an older run\n // can merge its transaction into this action during the await above.\n assertNoOpenTransaction(statusManager.findAction(step, action.type))\n\n const signedTransactionOutputs = await withTimeout(\n async () => {\n const { signTransaction } = getWalletFeature(\n wallet,\n SolanaSignTransaction\n )\n // Spread the inputs to sign all transactions at once\n return signTransaction(\n ...transactionBytesArray.map((transaction) => ({\n account: walletAccount,\n transaction,\n }))\n )\n },\n {\n // https://solana.com/docs/advanced/confirmation#transaction-expiration\n // Use 2 minutes to account for fluctuations\n timeout: 120_000,\n errorInstance: new TransactionError(\n LiFiErrorCode.TransactionExpired,\n 'Transaction has expired: blockhash is no longer recent enough.'\n ),\n }\n )\n\n // Checked once more after the wallet: a stopped run's late write can\n // merge its transaction into this action while the prompt is open.\n // Nothing awaits from here to the two writes below, so no late write can\n // land between this check and either of them.\n assertNoOpenTransaction(statusManager.findAction(step, action.type))\n\n if (signedTransactionOutputs.length === 0) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'No signed transaction returned from signer.'\n )\n }\n\n // Neither `txHash` nor `txLink` is written here. A signature is fixed at\n // signing, but the transaction does not exist yet: `getTransaction`\n // returns `null` for it, and simulation, the empty-Jito-RPC throw and\n // every send failure all sit between this task and the first broadcast.\n // The wait tasks write both on `onBroadcast`, when an RPC has accepted it.\n //\n // The previous transaction's fields (`CLEARED_TRANSACTION_FIELDS`) are\n // cleared explicitly. Only a final failure reaches this task with them\n // set, and a stale hash would look open again once its `txFinal` is gone.\n // This write runs BEFORE the decode below, which can throw on a malformed\n // wallet output and would otherwise strand the old fields.\n statusManager.updateAction(step, action.type, 'PENDING', {\n ...CLEARED_TRANSACTION_FIELDS,\n signedAt: Date.now(),\n })\n\n const transactionCodec = getTransactionCodec()\n\n // Decode all signed transactions\n const signedTransactions = signedTransactionOutputs.map((output) =>\n transactionCodec.decode(output.signedTransaction)\n )\n\n // Every transaction must carry its fee payer signature before its bytes\n // are stored: an unreadable value would fail every resume the same way.\n // Nothing has been sent yet, so the `TransactionUnprepared` this throws\n // leaves \"Try again\" free to sign again.\n for (const signedTransaction of signedTransactions) {\n readSignature(signedTransaction)\n }\n\n // Stored before any send: a reload from here on resends these bytes\n // instead of asking the wallet again. A bundle stays a JSON array, which\n // is how a resume knows to submit it with `sendBundle`.\n statusManager.updateAction(step, action.type, 'PENDING', {\n txHex: encodeStoredTransactions(\n signedTransactionOutputs.map((output) => output.signedTransaction),\n isBundleExecution\n ),\n })\n\n return {\n status: 'COMPLETED',\n context: { signedTransactions, isBundleExecution },\n }\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,IAAa,2BAAb,cAA8CA,UAAAA,sBAAsB;CAClE,MAAM,IAAI,S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