@lifi/sdk-provider-solana 4.0.7 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/dist/cjs/actions/sendAndConfirmBundle.d.ts +18 -25
  3. package/dist/cjs/actions/sendAndConfirmBundle.js +33 -54
  4. package/dist/cjs/actions/sendAndConfirmBundle.js.map +1 -1
  5. package/dist/cjs/actions/sendAndConfirmTransaction.d.ts +14 -22
  6. package/dist/cjs/actions/sendAndConfirmTransaction.js +38 -55
  7. package/dist/cjs/actions/sendAndConfirmTransaction.js.map +1 -1
  8. package/dist/cjs/confirmation/abortableSleep.d.ts +19 -0
  9. package/dist/cjs/confirmation/abortableSleep.js +32 -0
  10. package/dist/cjs/confirmation/abortableSleep.js.map +1 -0
  11. package/dist/cjs/confirmation/confirmBundle.d.ts +43 -0
  12. package/dist/cjs/confirmation/confirmBundle.js +57 -0
  13. package/dist/cjs/confirmation/confirmBundle.js.map +1 -0
  14. package/dist/cjs/confirmation/confirmSignature.d.ts +29 -0
  15. package/dist/cjs/confirmation/confirmSignature.js +66 -0
  16. package/dist/cjs/confirmation/confirmSignature.js.map +1 -0
  17. package/dist/cjs/confirmation/createConfirmationDeadline.d.ts +51 -0
  18. package/dist/cjs/confirmation/createConfirmationDeadline.js +101 -0
  19. package/dist/cjs/confirmation/createConfirmationDeadline.js.map +1 -0
  20. package/dist/cjs/confirmation/pollUntilDeadline.d.ts +58 -0
  21. package/dist/cjs/confirmation/pollUntilDeadline.js +97 -0
  22. package/dist/cjs/confirmation/pollUntilDeadline.js.map +1 -0
  23. package/dist/cjs/confirmation/raceRpcs.d.ts +26 -0
  24. package/dist/cjs/confirmation/raceRpcs.js +93 -0
  25. package/dist/cjs/confirmation/raceRpcs.js.map +1 -0
  26. package/dist/cjs/confirmation/types.d.ts +18 -0
  27. package/dist/cjs/confirmation/types.js +9 -0
  28. package/dist/cjs/confirmation/types.js.map +1 -0
  29. package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js +30 -9
  30. package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
  31. package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js +5 -1
  32. package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
  33. package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js +20 -7
  34. package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
  35. package/dist/cjs/core/tasks/readSignature.d.ts +17 -0
  36. package/dist/cjs/core/tasks/readSignature.js +26 -0
  37. package/dist/cjs/core/tasks/readSignature.js.map +1 -0
  38. package/dist/cjs/core/tasks/unwrapConfirmation.d.ts +25 -0
  39. package/dist/cjs/core/tasks/unwrapConfirmation.js +24 -0
  40. package/dist/cjs/core/tasks/unwrapConfirmation.js.map +1 -0
  41. package/dist/cjs/rpc/jito/api/getBundleStatuses.d.ts +4 -2
  42. package/dist/cjs/rpc/registry.d.ts +37 -11
  43. package/dist/cjs/rpc/registry.js +103 -18
  44. package/dist/cjs/rpc/registry.js.map +1 -1
  45. package/dist/cjs/rpc/utils.js +1 -1
  46. package/dist/cjs/rpc/utils.js.map +1 -1
  47. package/dist/cjs/utils/KeypairWalletAdapter.js +10 -4
  48. package/dist/cjs/utils/KeypairWalletAdapter.js.map +1 -1
  49. package/dist/cjs/utils/getTransactionLifetime.d.ts +21 -0
  50. package/dist/cjs/utils/getTransactionLifetime.js +28 -0
  51. package/dist/cjs/utils/getTransactionLifetime.js.map +1 -0
  52. package/dist/cjs/version.d.ts +1 -1
  53. package/dist/cjs/version.js +1 -1
  54. package/dist/cjs/version.js.map +1 -1
  55. package/dist/esm/actions/sendAndConfirmBundle.d.ts +18 -25
  56. package/dist/esm/actions/sendAndConfirmBundle.d.ts.map +1 -1
  57. package/dist/esm/actions/sendAndConfirmBundle.js +34 -55
  58. package/dist/esm/actions/sendAndConfirmBundle.js.map +1 -1
  59. package/dist/esm/actions/sendAndConfirmTransaction.d.ts +14 -22
  60. package/dist/esm/actions/sendAndConfirmTransaction.d.ts.map +1 -1
  61. package/dist/esm/actions/sendAndConfirmTransaction.js +38 -55
  62. package/dist/esm/actions/sendAndConfirmTransaction.js.map +1 -1
  63. package/dist/esm/confirmation/abortableSleep.d.ts +19 -0
  64. package/dist/esm/confirmation/abortableSleep.d.ts.map +1 -0
  65. package/dist/esm/confirmation/abortableSleep.js +31 -0
  66. package/dist/esm/confirmation/abortableSleep.js.map +1 -0
  67. package/dist/esm/confirmation/confirmBundle.d.ts +43 -0
  68. package/dist/esm/confirmation/confirmBundle.d.ts.map +1 -0
  69. package/dist/esm/confirmation/confirmBundle.js +55 -0
  70. package/dist/esm/confirmation/confirmBundle.js.map +1 -0
  71. package/dist/esm/confirmation/confirmSignature.d.ts +29 -0
  72. package/dist/esm/confirmation/confirmSignature.d.ts.map +1 -0
  73. package/dist/esm/confirmation/confirmSignature.js +64 -0
  74. package/dist/esm/confirmation/confirmSignature.js.map +1 -0
  75. package/dist/esm/confirmation/createConfirmationDeadline.d.ts +51 -0
  76. package/dist/esm/confirmation/createConfirmationDeadline.d.ts.map +1 -0
  77. package/dist/esm/confirmation/createConfirmationDeadline.js +93 -0
  78. package/dist/esm/confirmation/createConfirmationDeadline.js.map +1 -0
  79. package/dist/esm/confirmation/pollUntilDeadline.d.ts +58 -0
  80. package/dist/esm/confirmation/pollUntilDeadline.d.ts.map +1 -0
  81. package/dist/esm/confirmation/pollUntilDeadline.js +93 -0
  82. package/dist/esm/confirmation/pollUntilDeadline.js.map +1 -0
  83. package/dist/esm/confirmation/raceRpcs.d.ts +26 -0
  84. package/dist/esm/confirmation/raceRpcs.d.ts.map +1 -0
  85. package/dist/esm/confirmation/raceRpcs.js +92 -0
  86. package/dist/esm/confirmation/raceRpcs.js.map +1 -0
  87. package/dist/esm/confirmation/types.d.ts +18 -0
  88. package/dist/esm/confirmation/types.d.ts.map +1 -0
  89. package/dist/esm/confirmation/types.js +8 -0
  90. package/dist/esm/confirmation/types.js.map +1 -0
  91. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.d.ts.map +1 -1
  92. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js +30 -9
  93. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
  94. package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js +5 -1
  95. package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
  96. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.d.ts.map +1 -1
  97. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js +20 -7
  98. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
  99. package/dist/esm/core/tasks/readSignature.d.ts +17 -0
  100. package/dist/esm/core/tasks/readSignature.d.ts.map +1 -0
  101. package/dist/esm/core/tasks/readSignature.js +25 -0
  102. package/dist/esm/core/tasks/readSignature.js.map +1 -0
  103. package/dist/esm/core/tasks/unwrapConfirmation.d.ts +25 -0
  104. package/dist/esm/core/tasks/unwrapConfirmation.d.ts.map +1 -0
  105. package/dist/esm/core/tasks/unwrapConfirmation.js +23 -0
  106. package/dist/esm/core/tasks/unwrapConfirmation.js.map +1 -0
  107. package/dist/esm/rpc/jito/api/getBundleStatuses.d.ts +4 -2
  108. package/dist/esm/rpc/jito/api/getBundleStatuses.d.ts.map +1 -1
  109. package/dist/esm/rpc/registry.d.ts +37 -11
  110. package/dist/esm/rpc/registry.d.ts.map +1 -1
  111. package/dist/esm/rpc/registry.js +102 -19
  112. package/dist/esm/rpc/registry.js.map +1 -1
  113. package/dist/esm/rpc/utils.js +1 -1
  114. package/dist/esm/rpc/utils.js.map +1 -1
  115. package/dist/esm/utils/KeypairWalletAdapter.d.ts.map +1 -1
  116. package/dist/esm/utils/KeypairWalletAdapter.js +11 -5
  117. package/dist/esm/utils/KeypairWalletAdapter.js.map +1 -1
  118. package/dist/esm/utils/getTransactionLifetime.d.ts +21 -0
  119. package/dist/esm/utils/getTransactionLifetime.d.ts.map +1 -0
  120. package/dist/esm/utils/getTransactionLifetime.js +27 -0
  121. package/dist/esm/utils/getTransactionLifetime.js.map +1 -0
  122. package/dist/esm/version.d.ts +1 -1
  123. package/dist/esm/version.js +1 -1
  124. package/dist/esm/version.js.map +1 -1
  125. package/package.json +4 -4
  126. package/src/actions/sendAndConfirmBundle.ts +82 -142
  127. package/src/actions/sendAndConfirmTransaction.ts +82 -134
  128. package/src/confirmation/abortableSleep.ts +30 -0
  129. package/src/confirmation/confirmBundle.ts +121 -0
  130. package/src/confirmation/confirmSignature.ts +113 -0
  131. package/src/confirmation/createConfirmationDeadline.ts +174 -0
  132. package/src/confirmation/pollUntilDeadline.ts +182 -0
  133. package/src/confirmation/raceRpcs.ts +135 -0
  134. package/src/confirmation/types.ts +23 -0
  135. package/src/core/tasks/SolanaJitoWaitForTransactionTask.ts +49 -16
  136. package/src/core/tasks/SolanaSignAndExecuteTask.ts +15 -0
  137. package/src/core/tasks/SolanaStandardWaitForTransactionTask.ts +28 -17
  138. package/src/core/tasks/readSignature.ts +29 -0
  139. package/src/core/tasks/unwrapConfirmation.ts +59 -0
  140. package/src/rpc/jito/api/getBundleStatuses.ts +4 -2
  141. package/src/rpc/registry.ts +183 -25
  142. package/src/rpc/utils.ts +5 -2
  143. package/src/utils/KeypairWalletAdapter.ts +34 -9
  144. package/src/utils/getTransactionLifetime.ts +38 -0
  145. package/src/version.ts +1 -1
@@ -0,0 +1,121 @@
1
+ import type { Signature } from '@solana/kit'
2
+ import type { JitoRpcType } from '../rpc/types.js'
3
+ import type { TransactionLifetime } from '../utils/getTransactionLifetime.js'
4
+ import { createConfirmationDeadline } from './createConfirmationDeadline.js'
5
+ import { pollUntilDeadline } from './pollUntilDeadline.js'
6
+ import {
7
+ type ConfirmationOutcome,
8
+ isConfirmedCommitment,
9
+ type SignatureStatus,
10
+ } from './types.js'
11
+
12
+ /** Slower than the signature poller's 400 ms: Jito documents 1 req/s per IP
13
+ * per region. At 2 s this holds 0.5 req/s, leaving room for the deadline's
14
+ * blockhash probes on the same endpoint. */
15
+ export const BUNDLE_POLL_INTERVAL_MS = 2_000
16
+
17
+ export type BundleConfirmation = {
18
+ /** The submission's own id, carried for diagnostics. */
19
+ bundleId: string
20
+ /** Never read for a `txHash` - its order is Jito's to choose. Kept so the
21
+ * reversed-list regression stays expressible in the wait-task spec. */
22
+ txSignatures: Signature[]
23
+ signatureResults: readonly (SignatureStatus | null)[]
24
+ /** Bundle-level `err`, verbatim. Jito encodes it as a Rust `Result`, so a
25
+ * landed bundle carries `{ Ok: null }` - never truthiness-check it. */
26
+ bundleErr: unknown
27
+ }
28
+
29
+ /**
30
+ * Confirms one Jito bundle against one Jito RPC.
31
+ *
32
+ * Bundles submit once, so there is no resend loop. `send` is owned here so the
33
+ * deadline starts before submission rather than after it. A `send` failure
34
+ * throws, which `raceRpcs` buckets as `rpc-unavailable`.
35
+ */
36
+ export async function confirmBundle(options: {
37
+ rpc: JitoRpcType
38
+ signal: AbortSignal
39
+ lifetimes: TransactionLifetime[]
40
+ send: () => Promise<string>
41
+ /**
42
+ * Reports that this RPC accepted the bundle submission. Must not throw -
43
+ * `sendAndConfirmBundle` contains any throw from the integrator callback it
44
+ * wraps, because a throw here would reject a branch whose bundle Jito had
45
+ * already accepted.
46
+ */
47
+ onBroadcast?: () => void
48
+ }): Promise<ConfirmationOutcome<BundleConfirmation>> {
49
+ const { rpc, signal, lifetimes, send } = options
50
+ const deadline = createConfirmationDeadline({ lifetimes, rpc })
51
+
52
+ const bundleId = await send()
53
+ // Guarded like `confirmSignature`'s send sites: the caller's once-guard
54
+ // latches only after the callback returns, so a throwing integrator hook
55
+ // leaves it open and a late `sendBundle` fulfilment would re-write a
56
+ // finalized action back to PENDING.
57
+ if (!signal.aborted) {
58
+ options.onBroadcast?.()
59
+ }
60
+
61
+ const readBundle = async (): Promise<BundleConfirmation | null> => {
62
+ const statusResponse = await rpc
63
+ .getBundleStatuses([bundleId])
64
+ .send({ abortSignal: signal })
65
+ // A `{ value: null }` answer responded but said nothing - poll again
66
+ // rather than throw a `TypeError` into the read-failure budget.
67
+ const bundleStatus = statusResponse?.value?.[0]
68
+ if (
69
+ !bundleStatus ||
70
+ !isConfirmedCommitment(bundleStatus.confirmation_status)
71
+ ) {
72
+ return null
73
+ }
74
+
75
+ // Unvalidated wire data: without this guard a confirmed status carrying
76
+ // no `transactions` makes every `.map` below a `TypeError`, and a landed
77
+ // bundle would report as `rpc-unavailable`.
78
+ // `Array.isArray`, not `??`: the wire data is unvalidated, and a truthy
79
+ // non-array keeps the declared array type while throwing out of `.map`.
80
+ const txSignatures = Array.isArray(bundleStatus.transactions)
81
+ ? bundleStatus.transactions
82
+ : []
83
+
84
+ // The bundle status is the atomic fact: a bundle lands whole or not at
85
+ // all. `getSignatureStatuses` only enriches it with per-transaction `err`
86
+ // detail, so an unusable response degrades to all-`null` and must never
87
+ // veto a confirmation the status already made.
88
+ let signatureResults: BundleConfirmation['signatureResults']
89
+ if (txSignatures.length === 0) {
90
+ // Nothing to enrich; the status already confirmed the bundle.
91
+ signatureResults = []
92
+ } else {
93
+ try {
94
+ const sigResponse = await rpc
95
+ .getSignatureStatuses(txSignatures)
96
+ .send({ abortSignal: signal })
97
+ signatureResults = Array.isArray(sigResponse?.value)
98
+ ? sigResponse.value
99
+ : txSignatures.map(() => null)
100
+ } catch (_) {
101
+ signatureResults = txSignatures.map(() => null)
102
+ }
103
+ }
104
+
105
+ return {
106
+ bundleId,
107
+ txSignatures,
108
+ signatureResults,
109
+ bundleErr: bundleStatus.err,
110
+ }
111
+ }
112
+
113
+ return pollUntilDeadline({
114
+ deadline,
115
+ signal,
116
+ pollIntervalMs: BUNDLE_POLL_INTERVAL_MS,
117
+ probe: readBundle,
118
+ read: 'bundle status read',
119
+ subject: 'bundle',
120
+ })
121
+ }
@@ -0,0 +1,113 @@
1
+ import type { Signature } from '@solana/kit'
2
+ import type { SolanaRpcType } from '../rpc/types.js'
3
+ import type { TransactionLifetime } from '../utils/getTransactionLifetime.js'
4
+ import { abortableSleep } from './abortableSleep.js'
5
+ import { createConfirmationDeadline } from './createConfirmationDeadline.js'
6
+ import { pollUntilDeadline } from './pollUntilDeadline.js'
7
+ import {
8
+ type ConfirmationOutcome,
9
+ isConfirmedCommitment,
10
+ type SignatureStatus,
11
+ } from './types.js'
12
+
13
+ const RESEND_INTERVAL_MS = 1000
14
+ /**
15
+ * How often this poller re-reads `getSignatureStatuses`. The default Solana
16
+ * RPCs tolerate 2.5 req/s of status reads; the Jito bundle poller runs slower
17
+ * because its endpoints do not (see `confirmBundle`).
18
+ */
19
+ export const SIGNATURE_POLL_INTERVAL_MS = 400
20
+
21
+ /** Confirms one transaction against one RPC. Holds no policy: the deadline
22
+ * decides when to stop, and the resend loop only observes an `AbortSignal`. */
23
+ export async function confirmSignature(options: {
24
+ rpc: SolanaRpcType
25
+ signal: AbortSignal
26
+ signature: Signature
27
+ lifetimes: TransactionLifetime[]
28
+ resend: (rpc: SolanaRpcType, signal: AbortSignal) => Promise<void>
29
+ /**
30
+ * Reports that this RPC accepted a send of the transaction. Must not throw -
31
+ * `sendAndConfirmTransaction` contains any throw from the integrator
32
+ * callback it wraps.
33
+ */
34
+ onBroadcast?: () => void
35
+ }): Promise<ConfirmationOutcome<SignatureStatus>> {
36
+ const { rpc, signal, signature, lifetimes, resend } = options
37
+ const deadline = createConfirmationDeadline({ lifetimes, rpc })
38
+
39
+ // Ends the resend loop when this branch finishes.
40
+ const branch = new AbortController()
41
+ const abortBranch = (): void => branch.abort()
42
+ signal.addEventListener('abort', abortBranch, { once: true })
43
+
44
+ let sendSucceeded = false
45
+
46
+ // Awaited so "did this RPC ever accept the transaction?" has a settled
47
+ // answer by the time polling ends, rather than one that depends on
48
+ // microtask ordering.
49
+ try {
50
+ await resend(rpc, signal)
51
+ sendSucceeded = true
52
+ // A send can fulfil after the abort; reporting a broadcast then would
53
+ // regress an action status the wait task already finalized.
54
+ // `sendSucceeded` still latches - the RPC did accept it.
55
+ if (!signal.aborted) {
56
+ options.onBroadcast?.()
57
+ }
58
+ } catch (_) {
59
+ // Continue with confirmation even if the initial send fails — another RPC
60
+ // may already have propagated the transaction.
61
+ }
62
+
63
+ const resending = (async () => {
64
+ while (!branch.signal.aborted) {
65
+ await abortableSleep(RESEND_INTERVAL_MS, branch.signal)
66
+ if (branch.signal.aborted) {
67
+ break
68
+ }
69
+ try {
70
+ await resend(rpc, branch.signal)
71
+ sendSucceeded = true
72
+ // Same late-fulfilment guard as the first send.
73
+ if (!branch.signal.aborted) {
74
+ options.onBroadcast?.()
75
+ }
76
+ } catch (_) {
77
+ // Resending is best-effort. A total failure is caught by the
78
+ // neverBroadcast check in the verdict.
79
+ }
80
+ }
81
+ })()
82
+ resending.catch(() => {})
83
+
84
+ const readStatus = async (): Promise<SignatureStatus | null> => {
85
+ const response = await rpc
86
+ .getSignatureStatuses([signature])
87
+ .send({ abortSignal: signal })
88
+ // A `{ value: null }` answer responded but said nothing - poll again
89
+ // rather than throw a `TypeError` into the read-failure budget.
90
+ const status = response?.value?.[0]
91
+ if (status && isConfirmedCommitment(status.confirmationStatus)) {
92
+ return status
93
+ }
94
+ return null
95
+ }
96
+
97
+ try {
98
+ return await pollUntilDeadline({
99
+ deadline,
100
+ signal,
101
+ pollIntervalMs: SIGNATURE_POLL_INTERVAL_MS,
102
+ probe: readStatus,
103
+ read: 'signature status read',
104
+ subject: 'transaction',
105
+ // Read at verdict time, not captured: the resend loop may succeed long
106
+ // after the awaited first send failed.
107
+ neverBroadcast: () => !sendSucceeded,
108
+ })
109
+ } finally {
110
+ branch.abort()
111
+ signal.removeEventListener('abort', abortBranch)
112
+ }
113
+ }
@@ -0,0 +1,174 @@
1
+ import type { Blockhash } from '@solana/kit'
2
+ import type { SolanaRpcType } from '../rpc/types.js'
3
+ import type { TransactionLifetime } from '../utils/getTransactionLifetime.js'
4
+
5
+ /** Give-up point for a branch's polling. Read between iterations only, so a
6
+ * hung RPC call needs `BRANCH_TIMEOUT_MS` to close the gap. */
7
+ export const CONFIRMATION_TIMEOUT_MS = 90_000
8
+ /** Head-room for the final probe after the deadline.
9
+ * `STATUS_RETRY_BACKOFF_CAP_MS` must stay below it. */
10
+ export const FINAL_PROBE_MARGIN_MS = 5_000
11
+ /** Hard bound on a branch, in-flight requests included. Above the ceiling so
12
+ * an abort cannot pre-empt the final probe. */
13
+ export const BRANCH_TIMEOUT_MS: number =
14
+ CONFIRMATION_TIMEOUT_MS + FINAL_PROBE_MARGIN_MS
15
+ /** How long a healthy-but-lagging node may need to catch up. A premise, not a
16
+ * knob: `isBlockhashValid` answers `false` for lag and for death alike, so no
17
+ * verdict may land inside this window. */
18
+ export const NODE_LAG_WINDOW_MS = 12_000
19
+ /** Gap between `isBlockhashValid` probes. Spacing them is what makes the
20
+ * consecutive-`false` rule meaningful: quantized to the 400 ms tick, probes
21
+ * land at 0.4/7.6/14.8 s, so no verdict lands inside `NODE_LAG_WINDOW_MS`. */
22
+ export const EXPIRY_PROBE_INTERVAL_MS = 7_000
23
+ /** Consecutive `false` results before a blockhash is believed dead. Derived so
24
+ * a change to either premise moves it automatically; `+ 2` keeps the
25
+ * inequality strict when the window divides exactly. */
26
+ export const EXPIRY_CONFIRMATIONS: number =
27
+ Math.floor(NODE_LAG_WINDOW_MS / EXPIRY_PROBE_INTERVAL_MS) + 2
28
+ /** Probe failures per blockhash before that blockhash stops being probed.
29
+ * Prober-only; the status pollers have `MAX_STATUS_READ_SILENCE_MS`. */
30
+ export const MAX_PROBE_ERRORS = 5
31
+
32
+ /** Structural, so one implementation serves both the Solana and Jito RPC. */
33
+ export type BlockhashProbeRpc = Pick<SolanaRpcType, 'isBlockhashValid'>
34
+
35
+ export interface ConfirmationDeadline {
36
+ /** Checked at the top of every poll iteration. */
37
+ reached(): boolean
38
+ /** Advances the policy; never throws. Probes at most once per
39
+ * `EXPIRY_PROBE_INTERVAL_MS`. */
40
+ tick(signal: AbortSignal): Promise<void>
41
+ }
42
+
43
+ /**
44
+ * Owns every "should I stop polling?" decision.
45
+ *
46
+ * Never reads `getBlockHeight`: at least one default LI.FI RPC answers it with
47
+ * the slot number, making any `lastValidBlockHeight` comparison false on its
48
+ * first evaluation.
49
+ */
50
+ export function createConfirmationDeadline(options: {
51
+ lifetimes: TransactionLifetime[]
52
+ rpc: BlockhashProbeRpc
53
+ now?: () => number
54
+ }): ConfirmationDeadline {
55
+ const { lifetimes, rpc } = options
56
+ const now = options.now ?? Date.now
57
+ const startedAt = now()
58
+
59
+ const blockhashLifetimes = lifetimes.filter(
60
+ (
61
+ lifetime
62
+ ): lifetime is Extract<TransactionLifetime, { kind: 'blockhash' }> =>
63
+ lifetime.kind === 'blockhash'
64
+ )
65
+ // A single non-blockhash lifetime disables the early exit for the whole set:
66
+ // we cannot know when such a transaction stops being landable.
67
+ const allProbeable =
68
+ lifetimes.length > 0 && blockhashLifetimes.length === lifetimes.length
69
+ const blockhashes: Blockhash[] = allProbeable
70
+ ? [...new Set(blockhashLifetimes.map((lifetime) => lifetime.blockhash))]
71
+ : []
72
+
73
+ // Keyed by blockhash: expiry is a property of a blockhash, not of the set.
74
+ const expiredStreaks = new Map<Blockhash, number>()
75
+ // Keyed for the same reason: a sibling's broken probe is not evidence about
76
+ // this blockhash, so it must not spend this blockhash's error budget.
77
+ const errorStreaks = new Map<Blockhash, number>()
78
+ // The blockhashes still worth asking about. One leaves this set after
79
+ // MAX_PROBE_ERRORS failures of its own; the others keep being probed.
80
+ const probeable = new Set<Blockhash>(blockhashes)
81
+ let lastProbeAt: number | undefined
82
+
83
+ /** Derived, not latched: a blockhash that reads valid again zeroes its
84
+ * streak and clears the verdict with it. */
85
+ const isExpired = (): boolean => {
86
+ for (const streak of expiredStreaks.values()) {
87
+ if (streak >= EXPIRY_CONFIRMATIONS) {
88
+ return true
89
+ }
90
+ }
91
+ return false
92
+ }
93
+
94
+ return {
95
+ reached(): boolean {
96
+ const elapsed = now() - startedAt
97
+ if (elapsed >= CONFIRMATION_TIMEOUT_MS) {
98
+ return true
99
+ }
100
+ return isExpired()
101
+ },
102
+ async tick(signal: AbortSignal): Promise<void> {
103
+ if (probeable.size === 0 || signal.aborted) {
104
+ return
105
+ }
106
+ // The cadence is wall-clock, not iteration count, and it uses the
107
+ // injected `now` so the policy stays testable without timers.
108
+ const probeAt = now()
109
+ if (
110
+ lastProbeAt !== undefined &&
111
+ probeAt - lastProbeAt < EXPIRY_PROBE_INTERVAL_MS
112
+ ) {
113
+ return
114
+ }
115
+ lastProbeAt = probeAt
116
+ // `allSettled`, not `all`: `all` rejects on the first failure and
117
+ // discards answers the other probes already produced. All state is keyed
118
+ // by blockhash, so one broken probe cannot disable the early exit for
119
+ // the rest.
120
+ const active = [...probeable]
121
+ const probes = await Promise.allSettled(
122
+ active.map(async (blockhash) => {
123
+ const result = await rpc
124
+ .isBlockhashValid(blockhash, { commitment: 'confirmed' })
125
+ .send({ abortSignal: signal })
126
+ return result.value
127
+ })
128
+ )
129
+
130
+ // A read that produced no usable answer says nothing about this
131
+ // blockhash: it must never spend the expiry streak, only the error
132
+ // budget. Shared by a rejected probe and by a fulfilled one whose
133
+ // response carried no boolean.
134
+ const recordFailedProbe = (blockhash: Blockhash): void => {
135
+ expiredStreaks.set(blockhash, 0)
136
+ const errors = (errorStreaks.get(blockhash) ?? 0) + 1
137
+ errorStreaks.set(blockhash, errors)
138
+ if (errors >= MAX_PROBE_ERRORS) {
139
+ // Degrade to ceiling-only for this blockhash.
140
+ probeable.delete(blockhash)
141
+ }
142
+ }
143
+
144
+ probes.forEach((probe, index) => {
145
+ const blockhash = active[index]
146
+
147
+ if (probe.status === 'rejected') {
148
+ recordFailedProbe(blockhash)
149
+ return
150
+ }
151
+
152
+ // `=== true` / `=== false`, never truthiness: a response carrying no
153
+ // `value` is not a `false`, and reading it as one is the only coercion
154
+ // here that can invent an expiry.
155
+ if (probe.value === true) {
156
+ errorStreaks.set(blockhash, 0)
157
+ expiredStreaks.set(blockhash, 0)
158
+ return
159
+ }
160
+
161
+ if (probe.value === false) {
162
+ errorStreaks.set(blockhash, 0)
163
+ expiredStreaks.set(
164
+ blockhash,
165
+ (expiredStreaks.get(blockhash) ?? 0) + 1
166
+ )
167
+ return
168
+ }
169
+
170
+ recordFailedProbe(blockhash)
171
+ })
172
+ },
173
+ }
174
+ }
@@ -0,0 +1,182 @@
1
+ import { abortableSleep } from './abortableSleep.js'
2
+ import type { ConfirmationDeadline } from './createConfirmationDeadline.js'
3
+ import type { ConfirmationOutcome } from './types.js'
4
+
5
+ /** Cadence of the detached deadline-advance loop. Independent of the
6
+ * status-poll interval, which each caller sets for its own rate limits. */
7
+ export const DEADLINE_TICK_INTERVAL_MS = 400
8
+ /** How long an endpoint may go without answering a status read before its
9
+ * branch gives up. Measured in wall-clock time, not in failures: a count is
10
+ * coupled to the backoff curve, and ten failures spanned only ~16.4 s, so a
11
+ * routine 20 s throttling window ended the branch 74 s inside the 90 s ceiling
12
+ * and reported an already-broadcast transaction as an outage. */
13
+ export const MAX_STATUS_READ_SILENCE_MS = 30_000
14
+ /** Ceiling on one backoff sleep. Squeezed between two bounds:
15
+ * - Above `BUNDLE_POLL_INTERVAL_MS`, the largest base interval any caller
16
+ * uses. At 2 s the two were equal, so `Math.max(pollIntervalMs, ...)` below
17
+ * returned the base interval for every failure count and the bundle path
18
+ * never backed off at all.
19
+ * - Far enough below `FINAL_PROBE_MARGIN_MS` to leave the final probe a
20
+ * usable window. A sleep straddling the ceiling delays that probe by up to
21
+ * the cap, so the window is the margin minus this value - 2 s here. `cap <
22
+ * margin` alone is not the constraint: 4 s satisfied it and left the probe
23
+ * 1 s, on the failing endpoints where the cap is reached and reads are
24
+ * slowest.
25
+ *
26
+ * The gap between the two bounds fits one doubling, so the bundle path's
27
+ * backoff is a single step rather than a curve. Widening it means raising
28
+ * `FINAL_PROBE_MARGIN_MS`, which lengthens the branch bound the SDK
29
+ * documents. */
30
+ export const STATUS_RETRY_BACKOFF_CAP_MS = 3_000
31
+
32
+ /**
33
+ * Polls one probe against one RPC until the deadline, and owns the verdict
34
+ * rules shared by the signature and bundle branches.
35
+ *
36
+ * `probe` resolves non-`null` for a confirmation, `null` for "answered, saw
37
+ * nothing", and rejects for a failed read. The deadline advances on a detached
38
+ * loop so a hung blockhash probe cannot stop status polling.
39
+ */
40
+ export async function pollUntilDeadline<T>(options: {
41
+ deadline: ConfirmationDeadline
42
+ signal: AbortSignal
43
+ /** Sleep between two status reads that answered. */
44
+ pollIntervalMs: number
45
+ /** One status read. `null` means it answered but saw no confirmation. */
46
+ probe: () => Promise<T | null>
47
+ /** Names the read in error messages, e.g. 'signature status read'. */
48
+ read: string
49
+ /** Names the thing being confirmed in error messages, e.g. 'transaction'. */
50
+ subject: string
51
+ /** `true` when this RPC never accepted the broadcast. Read at verdict time,
52
+ * and only when the observation did not complete. */
53
+ neverBroadcast?: () => boolean
54
+ /** Injectable clock, so the silence budget is testable without timers.
55
+ * Mirrors `createConfirmationDeadline`. */
56
+ now?: () => number
57
+ }): Promise<ConfirmationOutcome<T>> {
58
+ const { deadline, signal, pollIntervalMs, probe, read, subject } = options
59
+ const now = options.now ?? Date.now
60
+
61
+ let settled = false
62
+
63
+ // Advances the deadline independently of the status reads.
64
+ const advancing = (async () => {
65
+ while (!settled && !signal.aborted) {
66
+ await abortableSleep(DEADLINE_TICK_INTERVAL_MS, signal)
67
+ if (settled || signal.aborted) {
68
+ break
69
+ }
70
+ await deadline.tick(signal)
71
+ }
72
+ })()
73
+ advancing.catch(() => {})
74
+
75
+ try {
76
+ let failures = 0
77
+ // Did this RPC ever answer? A `null` read still answered. Separates
78
+ // "polled and saw nothing" from "never got a word out of this endpoint".
79
+ let probeSucceeded = false
80
+ // When a read last answered; the branch start until one does. A `null` read
81
+ // counts as an answer - the endpoint is alive and says nothing.
82
+ let lastAnswerAt = now()
83
+
84
+ // Records WHY the loop ended, because the two reasons earn different
85
+ // verdicts. Reaching the deadline is a complete observation; being aborted
86
+ // mid-read is not. The final probe below is a bonus on top of a complete
87
+ // observation, so losing it must not downgrade the verdict.
88
+ let deadlineReached = false
89
+ while (!signal.aborted) {
90
+ if (deadline.reached()) {
91
+ deadlineReached = true
92
+ break
93
+ }
94
+ try {
95
+ const value = await probe()
96
+ failures = 0
97
+ lastAnswerAt = now()
98
+ probeSucceeded = true
99
+ if (value !== null) {
100
+ return { kind: 'confirmed', value }
101
+ }
102
+ } catch (error) {
103
+ // `failures` still drives the backoff below; only the give-up rule is
104
+ // time-based.
105
+ failures += 1
106
+ if (now() - lastAnswerAt >= MAX_STATUS_READ_SILENCE_MS) {
107
+ throw error
108
+ }
109
+ }
110
+ // Exponential backoff, so a throttling burst meets a falling rate. The
111
+ // outer `max` stops the cap inverting it for a caller whose base
112
+ // interval already exceeds the cap.
113
+ const delay =
114
+ failures === 0
115
+ ? pollIntervalMs
116
+ : Math.max(
117
+ pollIntervalMs,
118
+ Math.min(
119
+ pollIntervalMs * 2 ** failures,
120
+ STATUS_RETRY_BACKOFF_CAP_MS
121
+ )
122
+ )
123
+ await abortableSleep(delay, signal)
124
+ }
125
+
126
+ // The status may have flipped between the last poll and the deadline
127
+ // being reached.
128
+ if (!signal.aborted) {
129
+ try {
130
+ const value = await probe()
131
+ probeSucceeded = true
132
+ if (value !== null) {
133
+ return { kind: 'confirmed', value }
134
+ }
135
+ } catch (_) {
136
+ // The loop already ran. One failed final probe is not evidence that
137
+ // this RPC is unusable.
138
+ }
139
+ }
140
+
141
+ // A completed observation outranks everything below: polled to its own
142
+ // deadline and saw nothing. It stays ahead of the send-failure signal on
143
+ // purpose - a throw here is bucketed as `rpc-unavailable` by `raceRpcs`,
144
+ // which would discard a real observation and misreport a genuinely expired
145
+ // transaction as an outage. The never-broadcast case is answered one level
146
+ // up, in the actions, which know whether ANY branch accepted the send.
147
+ //
148
+ // Keyed on `deadlineReached`, not on `!signal.aborted`: the final probe is
149
+ // a bonus on top of the observation, and the shared BRANCH_TIMEOUT_MS timer
150
+ // can abort that probe in every branch at once. Reading the abort here
151
+ // would discard every observation and report a fleet-wide expiry as an
152
+ // outage.
153
+ if (probeSucceeded && deadlineReached) {
154
+ return { kind: 'not-confirmed' }
155
+ }
156
+
157
+ if (options.neverBroadcast?.()) {
158
+ throw new Error(`Every ${subject} send to this RPC failed.`)
159
+ }
160
+
161
+ // Every read hung until the abort: an in-flight read never answers, so it
162
+ // never renews `lastAnswerAt` and never throws either - the abort arrives
163
+ // first. `not-confirmed` here would report a hung endpoint as an expiry.
164
+ if (!probeSucceeded) {
165
+ throw new Error(`No ${read} against this RPC ever completed.`)
166
+ }
167
+
168
+ // Exiting via `signal.aborted` means the final observation never
169
+ // happened — an in-flight read held the loop until the abort cut it off.
170
+ // An answer received early in the window must not stand in for one near
171
+ // the deadline: a branch that answered once and then went dark has no
172
+ // basis to call the subject of the read expired. (A branch aborted because another
173
+ // RPC already confirmed also throws here; `raceRpcs` drops a losing
174
+ // branch's error once its controller has aborted, so nothing is
175
+ // misreported.)
176
+ throw new Error(
177
+ `This RPC stopped answering before a final ${read} could run.`
178
+ )
179
+ } finally {
180
+ settled = true
181
+ }
182
+ }