@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.
Files changed (133) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/actions/lookupSignatureStatus.d.ts +66 -0
  4. package/dist/cjs/actions/lookupSignatureStatus.js +258 -0
  5. package/dist/cjs/actions/lookupSignatureStatus.js.map +1 -0
  6. package/dist/cjs/actions/sendAndConfirmTransaction.d.ts +7 -0
  7. package/dist/cjs/actions/sendAndConfirmTransaction.js +1 -0
  8. package/dist/cjs/actions/sendAndConfirmTransaction.js.map +1 -1
  9. package/dist/cjs/confirmation/confirmBundle.d.ts +1 -1
  10. package/dist/cjs/confirmation/confirmSignature.d.ts +1 -1
  11. package/dist/cjs/confirmation/createConfirmationDeadline.d.ts +6 -0
  12. package/dist/cjs/confirmation/createConfirmationDeadline.js +24 -8
  13. package/dist/cjs/confirmation/createConfirmationDeadline.js.map +1 -1
  14. package/dist/cjs/confirmation/pollUntilDeadline.js +9 -1
  15. package/dist/cjs/confirmation/pollUntilDeadline.js.map +1 -1
  16. package/dist/cjs/confirmation/raceRpcs.d.ts +8 -0
  17. package/dist/cjs/confirmation/raceRpcs.js +9 -1
  18. package/dist/cjs/confirmation/raceRpcs.js.map +1 -1
  19. package/dist/cjs/confirmation/types.d.ts +3 -0
  20. package/dist/cjs/confirmation/types.js.map +1 -1
  21. package/dist/cjs/core/SolanaStepExecutor.js +2 -4
  22. package/dist/cjs/core/SolanaStepExecutor.js.map +1 -1
  23. package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js +69 -33
  24. package/dist/cjs/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
  25. package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js +13 -5
  26. package/dist/cjs/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
  27. package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js +71 -38
  28. package/dist/cjs/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
  29. package/dist/cjs/core/tasks/SolanaWaitForTransactionTask.js +13 -1
  30. package/dist/cjs/core/tasks/SolanaWaitForTransactionTask.js.map +1 -1
  31. package/dist/cjs/core/tasks/confirmationError.d.ts +29 -0
  32. package/dist/cjs/core/tasks/confirmationError.js +26 -0
  33. package/dist/cjs/core/tasks/confirmationError.js.map +1 -0
  34. package/dist/cjs/core/tasks/resumeFromStore.d.ts +31 -0
  35. package/dist/cjs/core/tasks/resumeFromStore.js +81 -0
  36. package/dist/cjs/core/tasks/resumeFromStore.js.map +1 -0
  37. package/dist/cjs/core/tasks/transactionOutcome.d.ts +107 -0
  38. package/dist/cjs/core/tasks/transactionOutcome.js +158 -0
  39. package/dist/cjs/core/tasks/transactionOutcome.js.map +1 -0
  40. package/dist/cjs/types.d.ts +13 -2
  41. package/dist/cjs/types.js.map +1 -1
  42. package/dist/cjs/utils/storedTransactions.d.ts +36 -0
  43. package/dist/cjs/utils/storedTransactions.js +57 -0
  44. package/dist/cjs/utils/storedTransactions.js.map +1 -0
  45. package/dist/cjs/version.d.ts +1 -1
  46. package/dist/cjs/version.js +1 -1
  47. package/dist/cjs/version.js.map +1 -1
  48. package/dist/esm/actions/lookupSignatureStatus.d.ts +66 -0
  49. package/dist/esm/actions/lookupSignatureStatus.d.ts.map +1 -0
  50. package/dist/esm/actions/lookupSignatureStatus.js +252 -0
  51. package/dist/esm/actions/lookupSignatureStatus.js.map +1 -0
  52. package/dist/esm/actions/sendAndConfirmTransaction.d.ts +7 -0
  53. package/dist/esm/actions/sendAndConfirmTransaction.d.ts.map +1 -1
  54. package/dist/esm/actions/sendAndConfirmTransaction.js +1 -0
  55. package/dist/esm/actions/sendAndConfirmTransaction.js.map +1 -1
  56. package/dist/esm/confirmation/confirmBundle.d.ts +1 -1
  57. package/dist/esm/confirmation/confirmSignature.d.ts +1 -1
  58. package/dist/esm/confirmation/createConfirmationDeadline.d.ts +6 -0
  59. package/dist/esm/confirmation/createConfirmationDeadline.d.ts.map +1 -1
  60. package/dist/esm/confirmation/createConfirmationDeadline.js +24 -8
  61. package/dist/esm/confirmation/createConfirmationDeadline.js.map +1 -1
  62. package/dist/esm/confirmation/pollUntilDeadline.js +9 -1
  63. package/dist/esm/confirmation/pollUntilDeadline.js.map +1 -1
  64. package/dist/esm/confirmation/raceRpcs.d.ts +8 -0
  65. package/dist/esm/confirmation/raceRpcs.d.ts.map +1 -1
  66. package/dist/esm/confirmation/raceRpcs.js +9 -1
  67. package/dist/esm/confirmation/raceRpcs.js.map +1 -1
  68. package/dist/esm/confirmation/types.d.ts +3 -0
  69. package/dist/esm/confirmation/types.d.ts.map +1 -1
  70. package/dist/esm/confirmation/types.js.map +1 -1
  71. package/dist/esm/core/SolanaStepExecutor.d.ts.map +1 -1
  72. package/dist/esm/core/SolanaStepExecutor.js +3 -5
  73. package/dist/esm/core/SolanaStepExecutor.js.map +1 -1
  74. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.d.ts.map +1 -1
  75. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js +69 -33
  76. package/dist/esm/core/tasks/SolanaJitoWaitForTransactionTask.js.map +1 -1
  77. package/dist/esm/core/tasks/SolanaSignAndExecuteTask.d.ts.map +1 -1
  78. package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js +14 -6
  79. package/dist/esm/core/tasks/SolanaSignAndExecuteTask.js.map +1 -1
  80. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.d.ts.map +1 -1
  81. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js +71 -38
  82. package/dist/esm/core/tasks/SolanaStandardWaitForTransactionTask.js.map +1 -1
  83. package/dist/esm/core/tasks/SolanaWaitForTransactionTask.d.ts.map +1 -1
  84. package/dist/esm/core/tasks/SolanaWaitForTransactionTask.js +13 -1
  85. package/dist/esm/core/tasks/SolanaWaitForTransactionTask.js.map +1 -1
  86. package/dist/esm/core/tasks/confirmationError.d.ts +29 -0
  87. package/dist/esm/core/tasks/confirmationError.d.ts.map +1 -0
  88. package/dist/esm/core/tasks/confirmationError.js +25 -0
  89. package/dist/esm/core/tasks/confirmationError.js.map +1 -0
  90. package/dist/esm/core/tasks/resumeFromStore.d.ts +31 -0
  91. package/dist/esm/core/tasks/resumeFromStore.d.ts.map +1 -0
  92. package/dist/esm/core/tasks/resumeFromStore.js +80 -0
  93. package/dist/esm/core/tasks/resumeFromStore.js.map +1 -0
  94. package/dist/esm/core/tasks/transactionOutcome.d.ts +107 -0
  95. package/dist/esm/core/tasks/transactionOutcome.d.ts.map +1 -0
  96. package/dist/esm/core/tasks/transactionOutcome.js +150 -0
  97. package/dist/esm/core/tasks/transactionOutcome.js.map +1 -0
  98. package/dist/esm/types.d.ts +13 -2
  99. package/dist/esm/types.d.ts.map +1 -1
  100. package/dist/esm/types.js.map +1 -1
  101. package/dist/esm/utils/storedTransactions.d.ts +36 -0
  102. package/dist/esm/utils/storedTransactions.d.ts.map +1 -0
  103. package/dist/esm/utils/storedTransactions.js +54 -0
  104. package/dist/esm/utils/storedTransactions.js.map +1 -0
  105. package/dist/esm/version.d.ts +1 -1
  106. package/dist/esm/version.js +1 -1
  107. package/dist/esm/version.js.map +1 -1
  108. package/package.json +2 -2
  109. package/src/actions/lookupSignatureStatus.ts +444 -0
  110. package/src/actions/sendAndConfirmTransaction.ts +18 -0
  111. package/src/confirmation/createConfirmationDeadline.ts +43 -11
  112. package/src/confirmation/pollUntilDeadline.ts +14 -1
  113. package/src/confirmation/raceRpcs.ts +27 -1
  114. package/src/confirmation/types.ts +5 -0
  115. package/src/core/SolanaStepExecutor.ts +15 -8
  116. package/src/core/tasks/SolanaJitoWaitForTransactionTask.ts +133 -71
  117. package/src/core/tasks/SolanaSignAndExecuteTask.ts +50 -10
  118. package/src/core/tasks/SolanaStandardWaitForTransactionTask.ts +130 -76
  119. package/src/core/tasks/SolanaWaitForTransactionTask.ts +19 -1
  120. package/src/core/tasks/confirmationError.ts +60 -0
  121. package/src/core/tasks/resumeFromStore.ts +160 -0
  122. package/src/core/tasks/transactionOutcome.ts +273 -0
  123. package/src/types.ts +13 -1
  124. package/src/utils/storedTransactions.ts +88 -0
  125. package/src/version.ts +1 -1
  126. package/dist/cjs/core/tasks/unwrapConfirmation.d.ts +0 -24
  127. package/dist/cjs/core/tasks/unwrapConfirmation.js +0 -24
  128. package/dist/cjs/core/tasks/unwrapConfirmation.js.map +0 -1
  129. package/dist/esm/core/tasks/unwrapConfirmation.d.ts +0 -24
  130. package/dist/esm/core/tasks/unwrapConfirmation.d.ts.map +0 -1
  131. package/dist/esm/core/tasks/unwrapConfirmation.js +0 -23
  132. package/dist/esm/core/tasks/unwrapConfirmation.js.map +0 -1
  133. package/src/core/tasks/unwrapConfirmation.ts +0 -59
@@ -0,0 +1,252 @@
1
+ import { getSolanaRpcs } from "../rpc/registry.js";
2
+ import { isConfirmedCommitment } from "../confirmation/types.js";
3
+ import { isSignature } from "@solana/kit";
4
+ //#region src/actions/lookupSignatureStatus.ts
5
+ /** Budget of each `getSignatureStatuses` call, the status request. A hung
6
+ * endpoint would otherwise hold the `allSettled` below - and the wait task
7
+ * with it - open for good. */
8
+ const SIGNATURE_LOOKUP_TIMEOUT_MS = 15e3;
9
+ /** Budget of each `getSlot` and `getBlock` call of the proof search. An RPC
10
+ * that has not answered by then counts as silent, as a rejection does, and
11
+ * is left out of the rest of the search: a single hung RPC must not block a
12
+ * verdict when other RPCs answer. */
13
+ const CANARY_CALL_TIMEOUT_MS = 3e3;
14
+ /** Budget of the whole proof search. Past it the lookup asks for the target
15
+ * alone: it can still find the transaction, but it cannot prove absence. */
16
+ const COVERAGE_PROOF_TIMEOUT_MS = 1e4;
17
+ /** Target slot time. Real slots are rarely faster, so `ceil(age / 400)`
18
+ * slots back reach at or before the anchor; the anchor's clock-skew margin
19
+ * absorbs the rest. */
20
+ const SLOT_DURATION_MS = 400;
21
+ /** How far each canary search steps over skipped or empty slots. */
22
+ const CANARY_SLOT_STEPS = 32;
23
+ /** The history canary block. Old enough to be finalized everywhere. */
24
+ const HISTORY_BLOCK_CONFIG = {
25
+ transactionDetails: "signatures",
26
+ rewards: false,
27
+ maxSupportedTransactionVersion: 0
28
+ };
29
+ /** The head canary block: only a block the majority confirmed. */
30
+ const HEAD_BLOCK_CONFIG = {
31
+ commitment: "confirmed",
32
+ ...HISTORY_BLOCK_CONFIG
33
+ };
34
+ /** Never throws: `String()` throws on an object without a prototype, and a
35
+ * proxy can throw on `instanceof`. */
36
+ const toError = (reason) => {
37
+ try {
38
+ return reason instanceof Error ? reason : new Error(String(reason));
39
+ } catch {
40
+ return /* @__PURE__ */ new Error("An RPC call failed with a reason that cannot be read.");
41
+ }
42
+ };
43
+ /** Only an object is a status. Unvalidated wire data, so `true` or a
44
+ * string is no answer. */
45
+ const isStatus = (entry) => typeof entry === "object" && entry !== null;
46
+ /** A canary status counts only with the slot of the block that supplied the
47
+ * canary. A node on a minority fork can hold the head canary transaction if
48
+ * the same transaction also landed on its fork; its status then has another
49
+ * slot. This also rejects `{}`, arrays and a status without a bigint slot. */
50
+ const isCanaryStatus = (entry, canary) => isStatus(entry) && typeof entry.slot === "bigint" && entry.slot === canary.slot;
51
+ /** `isSignature` throws on a 64-88 character string that is not base58.
52
+ * Here a throw means "not a signature". */
53
+ const isSignatureEntry = (entry) => {
54
+ if (typeof entry !== "string") return false;
55
+ try {
56
+ return isSignature(entry);
57
+ } catch {
58
+ return false;
59
+ }
60
+ };
61
+ var CallTimeoutError = class extends Error {};
62
+ /**
63
+ * Runs `call` with its own abort signal and a budget of `timeoutMs`. Past
64
+ * the budget it rejects with a `CallTimeoutError` and aborts the call. The
65
+ * race does not rely on the transport to honour the abort. A synchronous
66
+ * throw of `call` becomes a rejection too.
67
+ */
68
+ function callWithin(call, timeoutMs) {
69
+ const controller = new AbortController();
70
+ let timer;
71
+ const timeout = new Promise((_resolve, reject) => {
72
+ timer = setTimeout(() => {
73
+ const error = new CallTimeoutError(`This RPC did not answer within ${timeoutMs}ms.`);
74
+ controller.abort(error);
75
+ reject(error);
76
+ }, timeoutMs);
77
+ });
78
+ const answer = new Promise((resolve) => resolve(call(controller.signal)));
79
+ return Promise.race([answer, timeout]).finally(() => clearTimeout(timer));
80
+ }
81
+ /**
82
+ * Looks a signature up on every Solana RPC, the transaction history
83
+ * included.
84
+ *
85
+ * Not `raceRpcs`: a race returns the first answer, and one pruned or lagging
86
+ * node answering `null` would then read as "the transaction does not exist".
87
+ * A node's `null` proves nothing on its own either: a default RPC forgets
88
+ * signatures after about two days, a node on a minority fork has not seen
89
+ * the majority's blocks, and a pool may route each request to another
90
+ * backend. So with `bounds` the same request also asks for two canaries:
91
+ * one that landed before the transaction could, and one from a confirmed
92
+ * block at or after the expiry. The `null` counts only when that response
93
+ * knows both canaries and its head is at or past the last slot the
94
+ * transaction could land in.
95
+ *
96
+ * Takes at most `COVERAGE_PROOF_TIMEOUT_MS + CANARY_CALL_TIMEOUT_MS` for
97
+ * the proof search and `SIGNATURE_LOOKUP_TIMEOUT_MS` for the status
98
+ * request. Never throws.
99
+ */
100
+ async function lookupSignatureStatus(client, signature, bounds) {
101
+ try {
102
+ const rpcs = await getSolanaRpcs(client);
103
+ const proof = bounds ? await findCoverageProof(rpcs, bounds) : void 0;
104
+ const signatures = proof ? [
105
+ signature,
106
+ proof.historyCanary.signature,
107
+ proof.headCanary.signature
108
+ ] : [signature];
109
+ return classifyReads(await Promise.allSettled(rpcs.map((rpc) => callWithin((abortSignal) => rpc.getSignatureStatuses(signatures, { searchTransactionHistory: true }).send({ abortSignal }), SIGNATURE_LOOKUP_TIMEOUT_MS))), proof);
110
+ } catch (error) {
111
+ return {
112
+ kind: "unknown",
113
+ answered: false,
114
+ errors: [toError(error)]
115
+ };
116
+ }
117
+ }
118
+ function classifyReads(reads, proof) {
119
+ let found;
120
+ let provenAbsent = false;
121
+ let answered = false;
122
+ const errors = [];
123
+ for (const read of reads) {
124
+ if (read.status === "rejected") {
125
+ errors.push(toError(read.reason));
126
+ continue;
127
+ }
128
+ const statuses = read.value?.value;
129
+ if (!Array.isArray(statuses) || statuses.length === 0) {
130
+ errors.push(/* @__PURE__ */ new Error("The signature status response carried no statuses."));
131
+ continue;
132
+ }
133
+ const [target, historyCanary, headCanary] = statuses;
134
+ if (isStatus(target)) {
135
+ answered = true;
136
+ if (!found || !isConfirmedCommitment(found.confirmationStatus) && isConfirmedCommitment(target.confirmationStatus)) found = target;
137
+ continue;
138
+ }
139
+ if (target !== null) {
140
+ errors.push(/* @__PURE__ */ new Error("The signature status response was unusable."));
141
+ continue;
142
+ }
143
+ answered = true;
144
+ const headSlot = read.value?.context?.slot;
145
+ if (!proof) errors.push(/* @__PURE__ */ new Error("This null carries no coverage proof: no canary was asked for."));
146
+ else if (!isCanaryStatus(historyCanary, proof.historyCanary)) errors.push(/* @__PURE__ */ new Error("This RPC does not cover the signing time: it has no status for the history canary at the slot of its block."));
147
+ else if (!isCanaryStatus(headCanary, proof.headCanary)) errors.push(/* @__PURE__ */ new Error("This RPC does not know the confirmed block at the head: it has no status for the head canary at the slot of its block."));
148
+ else if (typeof headSlot !== "bigint" || headSlot < proof.headSlot) errors.push(/* @__PURE__ */ new Error("This RPC has not reached the last slot the transaction could land in."));
149
+ else provenAbsent = true;
150
+ }
151
+ if (found) return {
152
+ kind: "found",
153
+ status: found
154
+ };
155
+ if (provenAbsent) return { kind: "not-found" };
156
+ return {
157
+ kind: "unknown",
158
+ answered,
159
+ errors
160
+ };
161
+ }
162
+ /** Up to `CANARY_SLOT_STEPS` slots from `from` in `direction`, within
163
+ * `[0, last]`. */
164
+ function slotsFrom(from, direction, last = from) {
165
+ const slots = [];
166
+ for (let step = 0n; step < BigInt(32); step += 1n) {
167
+ const slot = from + direction * step;
168
+ if (slot < 0n || direction === 1n && slot > last) break;
169
+ slots.push(slot);
170
+ }
171
+ return slots;
172
+ }
173
+ /**
174
+ * The canaries and the head a `null` has to meet. `undefined` when no RPC
175
+ * reports its current slot, no RPC supplies a canary block, the age is not
176
+ * positive, or the search runs out of time - then no answer can prove
177
+ * absence.
178
+ *
179
+ * - History canary: a block at or before
180
+ * `lowest current slot - ceil(age / SLOT_DURATION_MS)`, stepping down.
181
+ * The lowest slot places it: one RPC ahead of the others - or wrong - must
182
+ * not move it after the anchor.
183
+ * - Head canary: a `confirmed` block at or after `expiredAtSlot`, stepping
184
+ * up toward the current slot. Without a verdict, the freshest confirmed
185
+ * block, stepping down from the highest current slot, which is then also
186
+ * the head.
187
+ */
188
+ async function findCoverageProof(rpcs, bounds) {
189
+ const age = (bounds.now ?? Date.now()) - bounds.anchor;
190
+ if (!Number.isFinite(age) || age <= 0) return;
191
+ let outOfTime = false;
192
+ const deadline = setTimeout(() => {
193
+ outOfTime = true;
194
+ }, COVERAGE_PROOF_TIMEOUT_MS);
195
+ const silent = /* @__PURE__ */ new Set();
196
+ /** The answers of the RPCs that are not silent, each within its budget. */
197
+ const ask = async (call) => {
198
+ const asked = rpcs.filter((rpc) => !silent.has(rpc));
199
+ const results = await Promise.allSettled(asked.map((rpc) => callWithin((abortSignal) => call(rpc, abortSignal), CANARY_CALL_TIMEOUT_MS)));
200
+ const answers = [];
201
+ results.forEach((result, index) => {
202
+ if (result.status === "fulfilled") answers.push(result.value);
203
+ else if (result.reason instanceof CallTimeoutError) silent.add(asked[index]);
204
+ });
205
+ return answers;
206
+ };
207
+ /** A signature from the first of `slots` whose block any RPC supplies,
208
+ * with the slot of that block. */
209
+ const canaryFrom = async (slots, config) => {
210
+ for (const slot of slots) {
211
+ if (outOfTime) return;
212
+ const signature = firstSignatureOf(await ask((rpc, abortSignal) => rpc.getBlock(slot, config).send({ abortSignal })));
213
+ if (signature) return {
214
+ signature,
215
+ slot
216
+ };
217
+ }
218
+ };
219
+ try {
220
+ const slots = (await ask((rpc, abortSignal) => rpc.getSlot({ commitment: "confirmed" }).send({ abortSignal }))).filter((slot) => typeof slot === "bigint");
221
+ if (slots.length === 0) return;
222
+ const lowestSlot = slots.reduce((low, slot) => slot < low ? slot : low);
223
+ const highestSlot = slots.reduce((high, slot) => slot > high ? slot : high);
224
+ const historyCanary = await canaryFrom(slotsFrom(lowestSlot - BigInt(Math.ceil(age / 400)), -1n), HISTORY_BLOCK_CONFIG);
225
+ if (!historyCanary) return;
226
+ const { expiredAtSlot } = bounds;
227
+ const headCanary = await canaryFrom(expiredAtSlot === void 0 ? slotsFrom(highestSlot, -1n) : slotsFrom(expiredAtSlot, 1n, highestSlot > expiredAtSlot ? highestSlot : expiredAtSlot), HEAD_BLOCK_CONFIG);
228
+ if (!headCanary) return;
229
+ return {
230
+ historyCanary,
231
+ headCanary,
232
+ headSlot: expiredAtSlot ?? highestSlot
233
+ };
234
+ } finally {
235
+ clearTimeout(deadline);
236
+ }
237
+ }
238
+ /** A signature from the first block that has one. `undefined` for skipped
239
+ * or empty slots, pruned history or an outage. */
240
+ function firstSignatureOf(blocks) {
241
+ for (const block of blocks) {
242
+ if (typeof block !== "object" || block === null) continue;
243
+ const { signatures } = block;
244
+ if (!Array.isArray(signatures)) continue;
245
+ const canary = signatures.find(isSignatureEntry);
246
+ if (canary) return canary;
247
+ }
248
+ }
249
+ //#endregion
250
+ export { CANARY_CALL_TIMEOUT_MS, CANARY_SLOT_STEPS, COVERAGE_PROOF_TIMEOUT_MS, SIGNATURE_LOOKUP_TIMEOUT_MS, SLOT_DURATION_MS, lookupSignatureStatus };
251
+
252
+ //# sourceMappingURL=lookupSignatureStatus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lookupSignatureStatus.js","names":[],"sources":["../../../src/actions/lookupSignatureStatus.ts"],"sourcesContent":["import type { SDKClient } from '@lifi/sdk'\nimport { isSignature, type Signature } from '@solana/kit'\nimport {\n isConfirmedCommitment,\n type SignatureStatus,\n} from '../confirmation/types.js'\nimport { getSolanaRpcs } from '../rpc/registry.js'\nimport type { SolanaRpcType } from '../rpc/types.js'\n\n/** Budget of each `getSignatureStatuses` call, the status request. A hung\n * endpoint would otherwise hold the `allSettled` below - and the wait task\n * with it - open for good. */\nexport const SIGNATURE_LOOKUP_TIMEOUT_MS = 15_000\n/** Budget of each `getSlot` and `getBlock` call of the proof search. An RPC\n * that has not answered by then counts as silent, as a rejection does, and\n * is left out of the rest of the search: a single hung RPC must not block a\n * verdict when other RPCs answer. */\nexport const CANARY_CALL_TIMEOUT_MS = 3_000\n/** Budget of the whole proof search. Past it the lookup asks for the target\n * alone: it can still find the transaction, but it cannot prove absence. */\nexport const COVERAGE_PROOF_TIMEOUT_MS = 10_000\n/** Target slot time. Real slots are rarely faster, so `ceil(age / 400)`\n * slots back reach at or before the anchor; the anchor's clock-skew margin\n * absorbs the rest. */\nexport const SLOT_DURATION_MS = 400\n/** How far each canary search steps over skipped or empty slots. */\nexport const CANARY_SLOT_STEPS = 32\n\nexport type LookupBounds = {\n /** The earliest time the transaction can have landed, in ms since the\n * epoch: `execution.signedAt - CLOCK_SKEW_MARGIN_MS`. */\n anchor: number\n /** The slot of the expiry verdict (the `expired` result): the highest\n * slot of the expiry streak. A node's head at or past it (`>=`) has seen\n * every slot the transaction could land in. Without a verdict the freshest\n * current slot of the RPCs is the head. */\n expiredAtSlot?: bigint\n /** Injectable clock for the canary bound. */\n now?: number\n}\n\nexport type SignatureLookup =\n /** An RPC returned a status, of any commitment: the caller decides what\n * counts as landed. */\n | { kind: 'found'; status: SignatureStatus }\n /** An RPC answered `null` in a response that also proves it covers the\n * signing time and has seen every slot the transaction could land in, and\n * no RPC returned a status. */\n | { kind: 'not-found' }\n /** Nothing proves either way. `answered` separates silent RPCs - an\n * outage - from RPCs that gave a usable answer without proof. */\n | { kind: 'unknown'; answered: boolean; errors: Error[] }\n\n/** What makes one RPC's `null` count as absence. */\ntype CoverageProof = {\n /** A landed signature from before the anchor: the node's history reaches\n * back to the signing time. */\n historyCanary: Canary\n /** A signature from a confirmed block at or after the expiry slot (or,\n * without a verdict, a recent one): the node is on the majority fork. */\n headCanary: Canary\n /** The slot the answering node's head has to reach. */\n headSlot: bigint\n}\n\n/** A canary signature and the slot of the block that supplied it. */\ntype Canary = { signature: Signature; slot: bigint }\n\n/** The history canary block. Old enough to be finalized everywhere. */\nconst HISTORY_BLOCK_CONFIG = {\n transactionDetails: 'signatures',\n rewards: false,\n maxSupportedTransactionVersion: 0,\n} as const\n/** The head canary block: only a block the majority confirmed. */\nconst HEAD_BLOCK_CONFIG = {\n commitment: 'confirmed',\n ...HISTORY_BLOCK_CONFIG,\n} as const\n\n/** Never throws: `String()` throws on an object without a prototype, and a\n * proxy can throw on `instanceof`. */\nconst toError = (reason: unknown): Error => {\n try {\n return reason instanceof Error ? reason : new Error(String(reason))\n } catch {\n return new Error('An RPC call failed with a reason that cannot be read.')\n }\n}\n\n/** Only an object is a status. Unvalidated wire data, so `true` or a\n * string is no answer. */\nconst isStatus = (entry: unknown): entry is SignatureStatus =>\n typeof entry === 'object' && entry !== null\n\n/** A canary status counts only with the slot of the block that supplied the\n * canary. A node on a minority fork can hold the head canary transaction if\n * the same transaction also landed on its fork; its status then has another\n * slot. This also rejects `{}`, arrays and a status without a bigint slot. */\nconst isCanaryStatus = (entry: unknown, canary: Canary): boolean =>\n isStatus(entry) &&\n typeof entry.slot === 'bigint' &&\n entry.slot === canary.slot\n\n/** `isSignature` throws on a 64-88 character string that is not base58.\n * Here a throw means \"not a signature\". */\nconst isSignatureEntry = (entry: unknown): entry is Signature => {\n if (typeof entry !== 'string') {\n return false\n }\n try {\n return isSignature(entry)\n } catch {\n return false\n }\n}\n\nclass CallTimeoutError extends Error {}\n\n/**\n * Runs `call` with its own abort signal and a budget of `timeoutMs`. Past\n * the budget it rejects with a `CallTimeoutError` and aborts the call. The\n * race does not rely on the transport to honour the abort. A synchronous\n * throw of `call` becomes a rejection too.\n */\nfunction callWithin<T>(\n call: (abortSignal: AbortSignal) => Promise<T>,\n timeoutMs: number\n): Promise<T> {\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const error = new CallTimeoutError(\n `This RPC did not answer within ${timeoutMs}ms.`\n )\n controller.abort(error)\n reject(error)\n }, timeoutMs)\n })\n const answer = new Promise<T>((resolve) => resolve(call(controller.signal)))\n return Promise.race([answer, timeout]).finally(() => clearTimeout(timer))\n}\n\n/**\n * Looks a signature up on every Solana RPC, the transaction history\n * included.\n *\n * Not `raceRpcs`: a race returns the first answer, and one pruned or lagging\n * node answering `null` would then read as \"the transaction does not exist\".\n * A node's `null` proves nothing on its own either: a default RPC forgets\n * signatures after about two days, a node on a minority fork has not seen\n * the majority's blocks, and a pool may route each request to another\n * backend. So with `bounds` the same request also asks for two canaries:\n * one that landed before the transaction could, and one from a confirmed\n * block at or after the expiry. The `null` counts only when that response\n * knows both canaries and its head is at or past the last slot the\n * transaction could land in.\n *\n * Takes at most `COVERAGE_PROOF_TIMEOUT_MS + CANARY_CALL_TIMEOUT_MS` for\n * the proof search and `SIGNATURE_LOOKUP_TIMEOUT_MS` for the status\n * request. Never throws.\n */\nexport async function lookupSignatureStatus(\n client: SDKClient,\n signature: Signature,\n bounds?: LookupBounds\n): Promise<SignatureLookup> {\n try {\n const rpcs = await getSolanaRpcs(client)\n const proof = bounds ? await findCoverageProof(rpcs, bounds) : undefined\n const signatures = proof\n ? [signature, proof.historyCanary.signature, proof.headCanary.signature]\n : [signature]\n // Every RPC, also one that timed out in the proof search: it may still\n // return the target.\n const reads = await Promise.allSettled(\n rpcs.map((rpc) =>\n callWithin(\n (abortSignal) =>\n rpc\n .getSignatureStatuses(signatures, {\n searchTransactionHistory: true,\n })\n .send({ abortSignal }),\n SIGNATURE_LOOKUP_TIMEOUT_MS\n )\n )\n )\n return classifyReads(reads, proof)\n } catch (error) {\n // An unexpected fault proves nothing either way.\n return { kind: 'unknown', answered: false, errors: [toError(error)] }\n }\n}\n\nfunction classifyReads(\n reads: PromiseSettledResult<{\n context?: { slot?: unknown }\n value?: unknown\n }>[],\n proof: CoverageProof | undefined\n): SignatureLookup {\n let found: SignatureStatus | undefined\n let provenAbsent = false\n let answered = false\n const errors: Error[] = []\n\n for (const read of reads) {\n if (read.status === 'rejected') {\n errors.push(toError(read.reason))\n continue\n }\n // Unvalidated wire data: only entries of a `value` array are answers.\n // `{ value: null }` responded but said nothing about the signature.\n const statuses = read.value?.value\n if (!Array.isArray(statuses) || statuses.length === 0) {\n errors.push(\n new Error('The signature status response carried no statuses.')\n )\n continue\n }\n const [target, historyCanary, headCanary]: unknown[] = statuses\n\n if (isStatus(target)) {\n answered = true\n // A lagging RPC may still report `processed` for a confirmed one.\n if (\n !found ||\n (!isConfirmedCommitment(found.confirmationStatus) &&\n isConfirmedCommitment(target.confirmationStatus))\n ) {\n found = target\n }\n continue\n }\n if (target !== null) {\n errors.push(new Error('The signature status response was unusable.'))\n continue\n }\n answered = true\n\n // A `null` for the target. It proves absence only together with the\n // coverage and head proof from this very response.\n const headSlot = read.value?.context?.slot\n if (!proof) {\n errors.push(\n new Error(\n 'This null carries no coverage proof: no canary was asked for.'\n )\n )\n } else if (!isCanaryStatus(historyCanary, proof.historyCanary)) {\n errors.push(\n new Error(\n 'This RPC does not cover the signing time: it has no status for the history canary at the slot of its block.'\n )\n )\n } else if (!isCanaryStatus(headCanary, proof.headCanary)) {\n errors.push(\n new Error(\n 'This RPC does not know the confirmed block at the head: it has no status for the head canary at the slot of its block.'\n )\n )\n } else if (typeof headSlot !== 'bigint' || headSlot < proof.headSlot) {\n errors.push(\n new Error(\n 'This RPC has not reached the last slot the transaction could land in.'\n )\n )\n } else {\n provenAbsent = true\n }\n }\n\n if (found) {\n return { kind: 'found', status: found }\n }\n if (provenAbsent) {\n return { kind: 'not-found' }\n }\n return { kind: 'unknown', answered, errors }\n}\n\n/** Up to `CANARY_SLOT_STEPS` slots from `from` in `direction`, within\n * `[0, last]`. */\nfunction slotsFrom(\n from: bigint,\n direction: 1n | -1n,\n last: bigint = from\n): bigint[] {\n const slots: bigint[] = []\n for (let step = 0n; step < BigInt(CANARY_SLOT_STEPS); step += 1n) {\n const slot = from + direction * step\n if (slot < 0n || (direction === 1n && slot > last)) {\n break\n }\n slots.push(slot)\n }\n return slots\n}\n\n/**\n * The canaries and the head a `null` has to meet. `undefined` when no RPC\n * reports its current slot, no RPC supplies a canary block, the age is not\n * positive, or the search runs out of time - then no answer can prove\n * absence.\n *\n * - History canary: a block at or before\n * `lowest current slot - ceil(age / SLOT_DURATION_MS)`, stepping down.\n * The lowest slot places it: one RPC ahead of the others - or wrong - must\n * not move it after the anchor.\n * - Head canary: a `confirmed` block at or after `expiredAtSlot`, stepping\n * up toward the current slot. Without a verdict, the freshest confirmed\n * block, stepping down from the highest current slot, which is then also\n * the head.\n */\nasync function findCoverageProof(\n rpcs: SolanaRpcType[],\n bounds: LookupBounds\n): Promise<CoverageProof | undefined> {\n const age = (bounds.now ?? Date.now()) - bounds.anchor\n // A clock before the anchor cannot place the history canary: an age of 0\n // would put it at the current slot, the weakest canary there is.\n if (!Number.isFinite(age) || age <= 0) {\n return undefined\n }\n\n let outOfTime = false\n const deadline = setTimeout(() => {\n outOfTime = true\n }, COVERAGE_PROOF_TIMEOUT_MS)\n // RPCs that let a call run out of its budget. A rejection does not count:\n // a pruned node rejects an old block but can still supply the head canary.\n const silent = new Set<SolanaRpcType>()\n\n /** The answers of the RPCs that are not silent, each within its budget. */\n const ask = async <T>(\n call: (rpc: SolanaRpcType, abortSignal: AbortSignal) => Promise<T>\n ): Promise<T[]> => {\n const asked = rpcs.filter((rpc) => !silent.has(rpc))\n const results = await Promise.allSettled(\n asked.map((rpc) =>\n callWithin(\n (abortSignal) => call(rpc, abortSignal),\n CANARY_CALL_TIMEOUT_MS\n )\n )\n )\n const answers: T[] = []\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n answers.push(result.value)\n } else if (result.reason instanceof CallTimeoutError) {\n silent.add(asked[index])\n }\n })\n return answers\n }\n\n /** A signature from the first of `slots` whose block any RPC supplies,\n * with the slot of that block. */\n const canaryFrom = async (\n slots: bigint[],\n config: typeof HISTORY_BLOCK_CONFIG | typeof HEAD_BLOCK_CONFIG\n ): Promise<Canary | undefined> => {\n for (const slot of slots) {\n if (outOfTime) {\n return undefined\n }\n const blocks = await ask<unknown>((rpc, abortSignal) =>\n rpc.getBlock(slot, config).send({ abortSignal })\n )\n const signature = firstSignatureOf(blocks)\n if (signature) {\n return { signature, slot }\n }\n }\n return undefined\n }\n\n try {\n const slots = (\n await ask<unknown>((rpc, abortSignal) =>\n rpc.getSlot({ commitment: 'confirmed' }).send({ abortSignal })\n )\n ).filter((slot): slot is bigint => typeof slot === 'bigint')\n if (slots.length === 0) {\n return undefined\n }\n const lowestSlot = slots.reduce((low, slot) => (slot < low ? slot : low))\n const highestSlot = slots.reduce((high, slot) =>\n slot > high ? slot : high\n )\n\n const historyCanary = await canaryFrom(\n slotsFrom(lowestSlot - BigInt(Math.ceil(age / SLOT_DURATION_MS)), -1n),\n HISTORY_BLOCK_CONFIG\n )\n if (!historyCanary) {\n return undefined\n }\n\n const { expiredAtSlot } = bounds\n const headCanary = await canaryFrom(\n expiredAtSlot === undefined\n ? slotsFrom(highestSlot, -1n)\n : slotsFrom(\n expiredAtSlot,\n 1n,\n highestSlot > expiredAtSlot ? highestSlot : expiredAtSlot\n ),\n HEAD_BLOCK_CONFIG\n )\n if (!headCanary) {\n return undefined\n }\n return {\n historyCanary,\n headCanary,\n headSlot: expiredAtSlot ?? highestSlot,\n }\n } finally {\n clearTimeout(deadline)\n }\n}\n\n/** A signature from the first block that has one. `undefined` for skipped\n * or empty slots, pruned history or an outage. */\nfunction firstSignatureOf(blocks: unknown[]): Signature | undefined {\n for (const block of blocks) {\n if (typeof block !== 'object' || block === null) {\n continue\n }\n const { signatures } = block as { signatures?: unknown }\n if (!Array.isArray(signatures)) {\n continue\n }\n const canary = signatures.find(isSignatureEntry)\n if (canary) {\n return canary\n }\n }\n return undefined\n}\n"],"mappings":";;;;;;;AAYA,MAAa,8BAA8B;;;;;AAK3C,MAAa,yBAAyB;;;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AC3B;EAEF,MAAM,SAAS,WAAW,KAAK,gBAAgB;EAC/C,IAAI,QACF,OAAO;CAEX;AAEF"}
@@ -18,6 +18,13 @@ import { Transaction } from "@solana/kit";
18
18
  export declare function sendAndConfirmTransaction(client: SDKClient, signedTransaction: Transaction, options?: {
19
19
  /** Runs once, when the first RPC accepts a send. */
20
20
  onBroadcast?: () => void;
21
+ /**
22
+ * Asked before every send, the resends included. `false` refuses the
23
+ * send as a failed one, and polling goes on. The wait tasks close it at
24
+ * the resend age cap, so stored bytes without their own expiry are never
25
+ * sent past it.
26
+ */
27
+ mayResend?: () => boolean;
21
28
  }): Promise<RaceResult<SignatureStatus>>;
22
29
  //#endregion
23
30
  //# sourceMappingURL=sendAndConfirmTransaction.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sendAndConfirmTransaction.d.ts","names":[],"sources":["../../../src/actions/sendAndConfirmTransaction.ts"],"mappings":";;;;;;;;;;;;;;;;;wBA8BsB,0BACpB,QAAQ,WACR,mBAAmB,aACnB;;EAEE;IAED,QAAQ,WAAW"}
1
+ {"version":3,"file":"sendAndConfirmTransaction.d.ts","names":[],"sources":["../../../src/actions/sendAndConfirmTransaction.ts"],"mappings":";;;;;;;;;;;;;;;;;wBA8BsB,0BACpB,QAAQ,WACR,mBAAmB,aACnB;;EAEE;;;;;;;EAOA;IAED,QAAQ,WAAW"}
@@ -40,6 +40,7 @@ async function sendAndConfirmTransaction(client, signedTransaction, options) {
40
40
  encoding: "base64"
41
41
  };
42
42
  const send = async (rpc, signal) => {
43
+ if (options?.mayResend && !options.mayResend()) throw new Error("The resend age cap has passed; the stored transaction is not sent again.");
43
44
  await rpc.sendTransaction(signedTxSerialized, rawTransactionOptions).send({ abortSignal: signal });
44
45
  };
45
46
  const writeRpcs = writeRpcUrls.length ? getSolanaWriteRpcs(writeRpcUrls) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"sendAndConfirmTransaction.js","names":[],"sources":["../../../src/actions/sendAndConfirmTransaction.ts"],"sourcesContent":["import { ChainId, type SDKClient } from '@lifi/sdk'\nimport {\n type Commitment,\n getBase64EncodedWireTransaction,\n getSignatureFromTransaction,\n type Transaction,\n} from '@solana/kit'\nimport {\n confirmSignature,\n RESEND_INTERVAL_MS,\n} from '../confirmation/confirmSignature.js'\nimport { BRANCH_TIMEOUT_MS } from '../confirmation/createConfirmationDeadline.js'\nimport { type RaceResult, raceRpcs } from '../confirmation/raceRpcs.js'\nimport type { SignatureStatus } from '../confirmation/types.js'\nimport { getSolanaRpcs, getSolanaWriteRpcs } from '../rpc/registry.js'\nimport type { SolanaRpcType } from '../rpc/types.js'\nimport { getTransactionLifetime } from '../utils/getTransactionLifetime.js'\n\n/**\n * Sends a Solana transaction to every configured RPC and returns as soon as\n * one of them confirms it.\n *\n * When the client has Solana write RPCs (`rpcUrls[ChainId.SOL].write`), the\n * transaction is sent only through those, and the read RPCs only confirm it.\n *\n * The polling horizon comes from the signed transaction's own blockhash and a\n * wall-clock ceiling. It deliberately never comes from `getBlockHeight`: at\n * least one endpoint in the default LI.FI set answers that call with the slot\n * number.\n */\nexport async function sendAndConfirmTransaction(\n client: SDKClient,\n signedTransaction: Transaction,\n options?: {\n /** Runs once, when the first RPC accepts a send. */\n onBroadcast?: () => void\n }\n): Promise<RaceResult<SignatureStatus>> {\n const [solanaRpcs, writeRpcUrls = []] = await Promise.all([\n getSolanaRpcs(client),\n client.getWriteRpcUrlsByChainId?.(ChainId.SOL),\n ])\n\n let broadcastReported = false\n // Distinct from `broadcastReported`, which records whether the integrator\n // callback has *succeeded*. This one answers \"did any RPC accept the send?\",\n // and only that question may steer the verdict below. Set before the callback\n // runs, so a hook that throws on every resend cannot make a real expiry look\n // like an outage.\n let sendAccepted = false\n const reportBroadcast = (): void => {\n sendAccepted = true\n if (broadcastReported) {\n return\n }\n try {\n options?.onBroadcast?.()\n // Latched only after the callback returned. A callback that threw wrote\n // nothing, so the next successful send must be allowed to try again -\n // latching first made one failed `txLink` write permanent.\n broadcastReported = true\n } catch (_) {\n // This runs integrator code: the callback reaches `updateRouteHook` via\n // `StatusManager.updateAction`. Its failure must never reject the branch\n // that called it - the send has already been accepted by the network at\n // this point, so a throw here would report a landed transaction as an\n // RPC outage. Swallowed rather than surfaced because there is no verdict\n // it could honestly change.\n }\n }\n\n const signedTxSerialized = getBase64EncodedWireTransaction(signedTransaction)\n const txSignature = getSignatureFromTransaction(signedTransaction)\n\n const lifetime = await getTransactionLifetime(signedTransaction)\n\n const rawTransactionOptions = {\n // We can skip preflight check after the first transaction has been sent\n // https://solana.com/docs/advanced/retry#the-cost-of-skipping-preflight\n skipPreflight: true,\n // Setting max retries to 0 as we are handling retries manually\n maxRetries: BigInt(0),\n // https://solana.com/docs/advanced/confirmation#use-an-appropriate-preflight-commitment-level\n preflightCommitment: 'confirmed' as Commitment,\n encoding: 'base64' as const,\n }\n\n const send = async (\n rpc: SolanaRpcType,\n signal: AbortSignal\n ): Promise<void> => {\n await rpc\n .sendTransaction(signedTxSerialized, rawTransactionOptions)\n .send({ abortSignal: signal })\n }\n\n const writeRpcs = writeRpcUrls.length\n ? getSolanaWriteRpcs(writeRpcUrls)\n : undefined\n\n // Sends to the write RPCs belong to the whole call, not to one branch:\n // other branches wait on the same send, so the branch that started it must\n // not cancel it by ending. They end when the race does.\n const writes = new AbortController()\n\n // Every confirmation branch resends about once a second. Branches share one\n // send to the write RPCs per interval, so each write RPC sees the same rate\n // it would as a configured RPC, however many configured RPCs are polling.\n let lastWrite: { at: number; sent: Promise<void> } | undefined\n // A write RPC that has not answered its last send gets no new one, so a\n // hung endpoint holds one open request, not one per interval.\n const openSends = new Set<SolanaRpcType>()\n const sendToWriteRpc = async (rpc: SolanaRpcType): Promise<void> => {\n openSends.add(rpc)\n try {\n await send(rpc, writes.signal)\n } finally {\n openSends.delete(rpc)\n }\n }\n const sendToWriteRpcs = (rpcs: SolanaRpcType[]): Promise<void> => {\n const now = Date.now()\n if (lastWrite && now - lastWrite.at < RESEND_INTERVAL_MS) {\n return lastWrite.sent\n }\n // With every write RPC busy this rejects at once, and the branch polls.\n const ready = rpcs.filter((rpc) => !openSends.has(rpc))\n // Accepted as soon as one write RPC accepts it.\n const sent = Promise.any(ready.map(sendToWriteRpc)).then(() => undefined)\n // Recorded here, not only by the branches: a branch stops waiting after\n // one interval (below), and an acceptance after that must still count.\n // Skipped once the race is over, so a late acceptance cannot regress an\n // action status the wait task already finalized.\n sent.then(\n () => {\n if (!writes.signal.aborted) {\n reportBroadcast()\n }\n },\n () => {}\n )\n lastWrite = { at: now, sent }\n return sent\n }\n\n // `confirmSignature` awaits its first send before it starts polling. Every\n // branch waits on the same shared send, so a write RPC that hangs would hold\n // up polling on all of them - even for a transaction that already landed.\n // A branch waits at most one resend interval, then polls either way.\n const waitForWrite = (sent: Promise<void>): Promise<void> =>\n new Promise((resolve, reject) => {\n const timer = setTimeout(\n () =>\n reject(new Error('No write RPC accepted the transaction in time.')),\n RESEND_INTERVAL_MS\n )\n sent.then(\n () => {\n clearTimeout(timer)\n resolve()\n },\n (error: unknown) => {\n clearTimeout(timer)\n reject(error)\n }\n )\n })\n\n const resend = writeRpcs\n ? (): Promise<void> => waitForWrite(sendToWriteRpcs(writeRpcs))\n : send\n\n let result: RaceResult<SignatureStatus>\n try {\n result = await raceRpcs(\n solanaRpcs,\n (rpc, signal) =>\n confirmSignature({\n rpc,\n signal,\n signature: txSignature,\n lifetimes: [lifetime],\n resend,\n onBroadcast: reportBroadcast,\n }),\n { timeoutMs: BRANCH_TIMEOUT_MS }\n )\n } finally {\n writes.abort()\n }\n\n // Only this scope knows whether ANY branch accepted the send. A branch that\n // polls to its deadline reports `not-confirmed` regardless - correct per\n // branch, but across the whole race it would claim a transaction expired\n // when nothing ever submitted it. That is an outage, not an expiry.\n //\n // Reads `sendAccepted`, never `broadcastReported`: the latter is false\n // whenever the integrator's callback threw, which says nothing about whether\n // the network took the transaction.\n if (result.kind === 'not-confirmed' && !sendAccepted) {\n return { kind: 'rpc-unavailable', errors: result.errors }\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c,CAAC,CAAC,CAAC,WAAW,KAAA,CAAS;EAKxE,KAAK,WACG;GACJ,IAAI,CAAC,OAAO,OAAO,SACjB,gBAAgB;EAEpB,SACM,CAAC,CACT;EACA,YAAY;GAAE,IAAI;GAAK;EAAK;EAC5B,OAAO;CACT;CAMA,MAAM,gBAAgB,SACpB,IAAI,SAAS,SAAS,WAAW;EAC/B,MAAM,QAAQ,iBAEV,uBAAO,IAAI,MAAM,gDAAgD,CAAC,GACpE,kBACF;EACA,KAAK,WACG;GACJ,aAAa,KAAK;GAClB,QAAQ;EACV,IACC,UAAmB;GAClB,aAAa,KAAK;GAClB,OAAO,KAAK;EACd,CACF;CACF,CAAC;CAEH,MAAM,SAAS,kBACU,aAAa,gBAAgB,SAAS,CAAC,IAC5D;CAEJ,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,SACb,aACC,KAAK,WACJ,iBAAiB;GACf;GACA;GACA,WAAW;GACX,WAAW,CAAC,QAAQ;GACpB;GACA,aAAa;EACf,CAAC,GACH,EAAE,WAAW,kBAAkB,CACjC;CACF,UAAU;EACR,OAAO,MAAM;CACf;CAUA,IAAI,OAAO,SAAS,mBAAmB,CAAC,cACtC,OAAO;EAAE,MAAM;EAAmB,QAAQ,OAAO;CAAO;CAG1D,OAAO;AACT"}
1
+ {"version":3,"file":"sendAndConfirmTransaction.js","names":[],"sources":["../../../src/actions/sendAndConfirmTransaction.ts"],"sourcesContent":["import { ChainId, type SDKClient } from '@lifi/sdk'\nimport {\n type Commitment,\n getBase64EncodedWireTransaction,\n getSignatureFromTransaction,\n type Transaction,\n} from '@solana/kit'\nimport {\n confirmSignature,\n RESEND_INTERVAL_MS,\n} from '../confirmation/confirmSignature.js'\nimport { BRANCH_TIMEOUT_MS } from '../confirmation/createConfirmationDeadline.js'\nimport { type RaceResult, raceRpcs } from '../confirmation/raceRpcs.js'\nimport type { SignatureStatus } from '../confirmation/types.js'\nimport { getSolanaRpcs, getSolanaWriteRpcs } from '../rpc/registry.js'\nimport type { SolanaRpcType } from '../rpc/types.js'\nimport { getTransactionLifetime } from '../utils/getTransactionLifetime.js'\n\n/**\n * Sends a Solana transaction to every configured RPC and returns as soon as\n * one of them confirms it.\n *\n * When the client has Solana write RPCs (`rpcUrls[ChainId.SOL].write`), the\n * transaction is sent only through those, and the read RPCs only confirm it.\n *\n * The polling horizon comes from the signed transaction's own blockhash and a\n * wall-clock ceiling. It deliberately never comes from `getBlockHeight`: at\n * least one endpoint in the default LI.FI set answers that call with the slot\n * number.\n */\nexport async function sendAndConfirmTransaction(\n client: SDKClient,\n signedTransaction: Transaction,\n options?: {\n /** Runs once, when the first RPC accepts a send. */\n onBroadcast?: () => void\n /**\n * Asked before every send, the resends included. `false` refuses the\n * send as a failed one, and polling goes on. The wait tasks close it at\n * the resend age cap, so stored bytes without their own expiry are never\n * sent past it.\n */\n mayResend?: () => boolean\n }\n): Promise<RaceResult<SignatureStatus>> {\n const [solanaRpcs, writeRpcUrls = []] = await Promise.all([\n getSolanaRpcs(client),\n client.getWriteRpcUrlsByChainId?.(ChainId.SOL),\n ])\n\n let broadcastReported = false\n // Distinct from `broadcastReported`, which records whether the integrator\n // callback has *succeeded*. This one answers \"did any RPC accept the send?\",\n // and only that question may steer the verdict below. Set before the callback\n // runs, so a hook that throws on every resend cannot make a real expiry look\n // like an outage.\n let sendAccepted = false\n const reportBroadcast = (): void => {\n sendAccepted = true\n if (broadcastReported) {\n return\n }\n try {\n options?.onBroadcast?.()\n // Latched only after the callback returned. A callback that threw wrote\n // nothing, so the next successful send must be allowed to try again -\n // latching first made one failed `txLink` write permanent.\n broadcastReported = true\n } catch (_) {\n // This runs integrator code: the callback reaches `updateRouteHook` via\n // `StatusManager.updateAction`. Its failure must never reject the branch\n // that called it - the send has already been accepted by the network at\n // this point, so a throw here would report a landed transaction as an\n // RPC outage. Swallowed rather than surfaced because there is no verdict\n // it could honestly change.\n }\n }\n\n const signedTxSerialized = getBase64EncodedWireTransaction(signedTransaction)\n const txSignature = getSignatureFromTransaction(signedTransaction)\n\n const lifetime = await getTransactionLifetime(signedTransaction)\n\n const rawTransactionOptions = {\n // We can skip preflight check after the first transaction has been sent\n // https://solana.com/docs/advanced/retry#the-cost-of-skipping-preflight\n skipPreflight: true,\n // Setting max retries to 0 as we are handling retries manually\n maxRetries: BigInt(0),\n // https://solana.com/docs/advanced/confirmation#use-an-appropriate-preflight-commitment-level\n preflightCommitment: 'confirmed' as Commitment,\n encoding: 'base64' as const,\n }\n\n const send = async (\n rpc: SolanaRpcType,\n signal: AbortSignal\n ): Promise<void> => {\n // Refused as a failed send, so the branch keeps polling: the bytes may\n // already be on their way from an earlier send.\n if (options?.mayResend && !options.mayResend()) {\n throw new Error(\n 'The resend age cap has passed; the stored transaction is not sent again.'\n )\n }\n await rpc\n .sendTransaction(signedTxSerialized, rawTransactionOptions)\n .send({ abortSignal: signal })\n }\n\n const writeRpcs = writeRpcUrls.length\n ? getSolanaWriteRpcs(writeRpcUrls)\n : undefined\n\n // Sends to the write RPCs belong to the whole call, not to one branch:\n // other branches wait on the same send, so the branch that started it must\n // not cancel it by ending. They end when the race does.\n const writes = new AbortController()\n\n // Every confirmation branch resends about once a second. Branches share one\n // send to the write RPCs per interval, so each write RPC sees the same rate\n // it would as a configured RPC, however many configured RPCs are polling.\n let lastWrite: { at: number; sent: Promise<void> } | undefined\n // A write RPC that has not answered its last send gets no new one, so a\n // hung endpoint holds one open request, not one per interval.\n const openSends = new Set<SolanaRpcType>()\n const sendToWriteRpc = async (rpc: SolanaRpcType): Promise<void> => {\n openSends.add(rpc)\n try {\n await send(rpc, writes.signal)\n } finally {\n openSends.delete(rpc)\n }\n }\n const sendToWriteRpcs = (rpcs: SolanaRpcType[]): Promise<void> => {\n const now = Date.now()\n if (lastWrite && now - lastWrite.at < RESEND_INTERVAL_MS) {\n return lastWrite.sent\n }\n // With every write RPC busy this rejects at once, and the branch polls.\n const ready = rpcs.filter((rpc) => !openSends.has(rpc))\n // Accepted as soon as one write RPC accepts it.\n const sent = Promise.any(ready.map(sendToWriteRpc)).then(() => undefined)\n // Recorded here, not only by the branches: a branch stops waiting after\n // one interval (below), and an acceptance after that must still count.\n // Skipped once the race is over, so a late acceptance cannot regress an\n // action status the wait task already finalized.\n sent.then(\n () => {\n if (!writes.signal.aborted) {\n reportBroadcast()\n }\n },\n () => {}\n )\n lastWrite = { at: now, sent }\n return sent\n }\n\n // `confirmSignature` awaits its first send before it starts polling. Every\n // branch waits on the same shared send, so a write RPC that hangs would hold\n // up polling on all of them - even for a transaction that already landed.\n // A branch waits at most one resend interval, then polls either way.\n const waitForWrite = (sent: Promise<void>): Promise<void> =>\n new Promise((resolve, reject) => {\n const timer = setTimeout(\n () =>\n reject(new Error('No write RPC accepted the transaction in time.')),\n RESEND_INTERVAL_MS\n )\n sent.then(\n () => {\n clearTimeout(timer)\n resolve()\n },\n (error: unknown) => {\n clearTimeout(timer)\n reject(error)\n }\n )\n })\n\n const resend = writeRpcs\n ? (): Promise<void> => waitForWrite(sendToWriteRpcs(writeRpcs))\n : send\n\n let result: RaceResult<SignatureStatus>\n try {\n result = await raceRpcs(\n solanaRpcs,\n (rpc, signal) =>\n confirmSignature({\n rpc,\n signal,\n signature: txSignature,\n lifetimes: [lifetime],\n resend,\n onBroadcast: reportBroadcast,\n }),\n { timeoutMs: BRANCH_TIMEOUT_MS }\n )\n } finally {\n writes.abort()\n }\n\n // Only this scope knows whether ANY branch accepted the send. A branch that\n // polls to its deadline reports `not-confirmed` regardless - correct per\n // branch, but across the whole race it would claim a transaction expired\n // when nothing ever submitted it. That is an outage, not an expiry.\n //\n // Reads `sendAccepted`, never `broadcastReported`: the latter is false\n // whenever the integrator's callback threw, which says nothing about whether\n // the network took the transaction.\n //\n // `expired` is left alone: once the blockhash is dead every send may be\n // rejected, so \"nothing was accepted\" is expected there. Rewriting it would\n // block the dropped verdict for good.\n if (result.kind === 'not-confirmed' && !sendAccepted) {\n return { kind: 'rpc-unavailable', errors: result.errors }\n }\n\n return result\n}\n"],"mappings":";;;;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EtD,MAAM,OAAO,QAAQ,IAAI,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,WAAW,KAAA,CAAS;EAKxE,KAAK,WACG;GACJ,IAAI,CAAC,OAAO,OAAO,SACjB,gBAAgB;EAEpB,SACM,CAAC,CACT;EACA,YAAY;GAAE,IAAI;GAAK;EAAK;EAC5B,OAAO;CACT;CAMA,MAAM,gBAAgB,SACpB,IAAI,SAAS,SAAS,WAAW;EAC/B,MAAM,QAAQ,iBAEV,uBAAO,IAAI,MAAM,gDAAgD,CAAC,GACpE,kBACF;EACA,KAAK,WACG;GACJ,aAAa,KAAK;GAClB,QAAQ;EACV,IACC,UAAmB;GAClB,aAAa,KAAK;GAClB,OAAO,KAAK;EACd,CACF;CACF,CAAC;CAEH,MAAM,SAAS,kBACU,aAAa,gBAAgB,SAAS,CAAC,IAC5D;CAEJ,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,SACb,aACC,KAAK,WACJ,iBAAiB;GACf;GACA;GACA,WAAW;GACX,WAAW,CAAC,QAAQ;GACpB;GACA,aAAa;EACf,CAAC,GACH,EAAE,WAAW,kBAAkB,CACjC;CACF,UAAU;EACR,OAAO,MAAM;CACf;CAcA,IAAI,OAAO,SAAS,mBAAmB,CAAC,cACtC,OAAO;EAAE,MAAM;EAAmB,QAAQ,OAAO;CAAO;CAG1D,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
  import { JitoRpcType } from "../rpc/types.js";
2
- import { TransactionLifetime } from "../utils/getTransactionLifetime.js";
3
2
  import { ConfirmationOutcome, SignatureStatus } from "./types.js";
3
+ import { TransactionLifetime } from "../utils/getTransactionLifetime.js";
4
4
  import { Signature } from "@solana/kit";
5
5
  //#region src/confirmation/confirmBundle.d.ts
6
6
  /** Slower than the signature poller's 400 ms: Jito documents 1 req/s per IP
@@ -1,6 +1,6 @@
1
1
  import { SolanaRpcType } from "../rpc/types.js";
2
- import { TransactionLifetime } from "../utils/getTransactionLifetime.js";
3
2
  import { ConfirmationOutcome, SignatureStatus } from "./types.js";
3
+ import { TransactionLifetime } from "../utils/getTransactionLifetime.js";
4
4
  import { Signature } from "@solana/kit";
5
5
  //#region src/confirmation/confirmSignature.d.ts
6
6
  /** How often each confirmation branch resends the transaction. */
@@ -30,6 +30,12 @@ export type BlockhashProbeRpc = Pick<SolanaRpcType, "isBlockhashValid">;
30
30
  export interface ConfirmationDeadline {
31
31
  /** Checked at the top of every poll iteration. */
32
32
  reached(): boolean;
33
+ /** The slot at which the blockhash probe confirmed expiry - the highest
34
+ * `context.slot` of the `false` answers in the streak - or `undefined`
35
+ * without a verdict. Tells the two reasons `reached()` fires apart: a dead
36
+ * blockhash may later count as "dropped", the wall-clock ceiling never
37
+ * does. */
38
+ expiredAt(): bigint | undefined;
33
39
  /** Advances the policy; never throws. Probes at most once per
34
40
  * `EXPIRY_PROBE_INTERVAL_MS`. */
35
41
  tick(signal: AbortSignal): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"createConfirmationDeadline.d.ts","names":[],"sources":["../../../src/confirmation/createConfirmationDeadline.ts"],"mappings":";;;;;qBAMa;;;qBAGA;;;qBAGA;;;;qBAKA;;;;qBAIA;;;;qBAIA;;;qBAIA;;YAGD,oBAAoB,KAAK;iBAEpB;;EAEf;;;EAGA,KAAK,QAAQ,cAAc;;;;;;;;;wBAUb,2BAA2B;EACzC,WAAW;EACX,KAAK;EACL;IACE"}
1
+ {"version":3,"file":"createConfirmationDeadline.d.ts","names":[],"sources":["../../../src/confirmation/createConfirmationDeadline.ts"],"mappings":";;;;;qBAMa;;;qBAGA;;;qBAGA;;;;qBAKA;;;;qBAIA;;;;qBAIA;;;qBAIA;;YAGD,oBAAoB,KAAK;iBAEpB;;EAEf;;;;;;EAMA;;;EAGA,KAAK,QAAQ,cAAc;;;;;;;;;wBAUb,2BAA2B;EACzC,WAAW;EACX,KAAK;EACL;IACE"}
@@ -37,20 +37,27 @@ function createConfirmationDeadline(options) {
37
37
  const blockhashLifetimes = lifetimes.filter((lifetime) => lifetime.kind === "blockhash");
38
38
  const blockhashes = lifetimes.length > 0 && blockhashLifetimes.length === lifetimes.length ? [...new Set(blockhashLifetimes.map((lifetime) => lifetime.blockhash))] : [];
39
39
  const expiredStreaks = /* @__PURE__ */ new Map();
40
+ const expiredSlots = /* @__PURE__ */ new Map();
40
41
  const errorStreaks = /* @__PURE__ */ new Map();
41
42
  const probeable = new Set(blockhashes);
42
43
  let lastProbeAt;
43
44
  /** Derived, not latched: a blockhash that reads valid again zeroes its
44
- * streak and clears the verdict with it. */
45
- const isExpired = () => {
46
- for (const streak of expiredStreaks.values()) if (streak >= EXPIRY_CONFIRMATIONS) return true;
47
- return false;
45
+ * streak and clears the verdict with it. The highest slot among the expired
46
+ * blockhashes is the strictest head bound. */
47
+ const expiredAt = () => {
48
+ let slot;
49
+ for (const [blockhash, streak] of expiredStreaks) {
50
+ const observedAt = expiredSlots.get(blockhash);
51
+ if (streak >= EXPIRY_CONFIRMATIONS && observedAt !== void 0 && (slot === void 0 || observedAt > slot)) slot = observedAt;
52
+ }
53
+ return slot;
48
54
  };
49
55
  return {
50
56
  reached() {
51
57
  if (now() - startedAt >= 9e4) return true;
52
- return isExpired();
58
+ return expiredAt() !== void 0;
53
59
  },
60
+ expiredAt,
54
61
  async tick(signal) {
55
62
  if (probeable.size === 0 || signal.aborted) return;
56
63
  const probeAt = now();
@@ -58,10 +65,15 @@ function createConfirmationDeadline(options) {
58
65
  lastProbeAt = probeAt;
59
66
  const active = [...probeable];
60
67
  const probes = await Promise.allSettled(active.map(async (blockhash) => {
61
- return (await rpc.isBlockhashValid(blockhash, { commitment: "confirmed" }).send({ abortSignal: signal })).value;
68
+ const result = await rpc.isBlockhashValid(blockhash, { commitment: "confirmed" }).send({ abortSignal: signal });
69
+ return {
70
+ value: result?.value,
71
+ slot: result?.context?.slot
72
+ };
62
73
  }));
63
74
  const recordFailedProbe = (blockhash) => {
64
75
  expiredStreaks.set(blockhash, 0);
76
+ expiredSlots.delete(blockhash);
65
77
  const errors = (errorStreaks.get(blockhash) ?? 0) + 1;
66
78
  errorStreaks.set(blockhash, errors);
67
79
  if (errors >= 5) probeable.delete(blockhash);
@@ -72,14 +84,18 @@ function createConfirmationDeadline(options) {
72
84
  recordFailedProbe(blockhash);
73
85
  return;
74
86
  }
75
- if (probe.value === true) {
87
+ const { value, slot } = probe.value;
88
+ if (value === true) {
76
89
  errorStreaks.set(blockhash, 0);
77
90
  expiredStreaks.set(blockhash, 0);
91
+ expiredSlots.delete(blockhash);
78
92
  return;
79
93
  }
80
- if (probe.value === false) {
94
+ if (value === false && typeof slot === "bigint") {
81
95
  errorStreaks.set(blockhash, 0);
82
96
  expiredStreaks.set(blockhash, (expiredStreaks.get(blockhash) ?? 0) + 1);
97
+ const previous = expiredSlots.get(blockhash);
98
+ expiredSlots.set(blockhash, previous === void 0 || slot > previous ? slot : previous);
83
99
  return;
84
100
  }
85
101
  recordFailedProbe(blockhash);
@@ -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) ?? 0) + 1\n )\n return\n }\n\n recordFailedProbe(blockhash)\n })\n },\n }\n}\n"],"mappings":";;;AAMA,MAAa,0BAA0B;;;AAGvC,MAAa,wBAAwB;;;AAGrC,MAAa,oBACX;;;;AAIF,MAAa,qBAAqB;;;;AAIlC,MAAa,2BAA2B;;;;AAIxC,MAAa,uBACX,KAAK,MAAM,qBAAqB,wBAAwB,IAAI;;;AAG9D,MAAa,mBAAmB;;;;;;;;AAoBhC,SAAgB,2BAA2B,SAIlB;CACvB,MAAM,EAAE,WAAW,QAAQ;CAC3B,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,YAAY,IAAI;CAEtB,MAAM,qBAAqB,UAAU,QAEjC,aAEA,SAAS,SAAS,WACtB;CAKA,MAAM,cADJ,UAAU,SAAS,KAAK,mBAAmB,WAAW,UAAU,SAE9D,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,IACrE,CAAC;CAGL,MAAM,iCAAiB,IAAI,IAAuB;CAGlD,MAAM,+BAAe,IAAI,IAAuB;CAGhD,MAAM,YAAY,IAAI,IAAe,WAAW;CAChD,IAAI;;;CAIJ,MAAM,kBAA2B;EAC/B,KAAK,MAAM,UAAU,eAAe,OAAO,GACzC,IAAI,UAAU,sBACZ,OAAO;EAGX,OAAO;CACT;CAEA,OAAO;EACL,UAAmB;GAEjB,IADgB,IAAI,IAAI,aAAA,KAEtB,OAAO;GAET,OAAO,UAAU;EACnB;EACA,MAAM,KAAK,QAAoC;GAC7C,IAAI,UAAU,SAAS,KAAK,OAAO,SACjC;GAIF,MAAM,UAAU,IAAI;GACpB,IACE,gBAAgB,KAAA,KAChB,UAAU,cAAA,KAEV;GAEF,cAAc;GAKd,MAAM,SAAS,CAAC,GAAG,SAAS;GAC5B,MAAM,SAAS,MAAM,QAAQ,WAC3B,OAAO,IAAI,OAAO,cAAc;IAI9B,QAAO,MAHc,IAClB,iBAAiB,WAAW,EAAE,YAAY,YAAY,CAAC,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":";;;AAMA,MAAa,0BAA0B;;;AAGvC,MAAa,wBAAwB;;;AAGrC,MAAa,oBACX;;;;AAIF,MAAa,qBAAqB;;;;AAIlC,MAAa,2BAA2B;;;;AAIxC,MAAa,uBACX,KAAK,MAAM,qBAAqB,wBAAwB,IAAI;;;AAG9D,MAAa,mBAAmB;;;;;;;;AA0BhC,SAAgB,2BAA2B,SAIlB;CACvB,MAAM,EAAE,WAAW,QAAQ;CAC3B,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,YAAY,IAAI;CAEtB,MAAM,qBAAqB,UAAU,QAEjC,aAEA,SAAS,SAAS,WACtB;CAKA,MAAM,cADJ,UAAU,SAAS,KAAK,mBAAmB,WAAW,UAAU,SAE9D,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,IACrE,CAAC;CAGL,MAAM,iCAAiB,IAAI,IAAuB;CAIlD,MAAM,+BAAe,IAAI,IAAuB;CAGhD,MAAM,+BAAe,IAAI,IAAuB;CAGhD,MAAM,YAAY,IAAI,IAAe,WAAW;CAChD,IAAI;;;;CAKJ,MAAM,kBAAsC;EAC1C,IAAI;EACJ,KAAK,MAAM,CAAC,WAAW,WAAW,gBAAgB;GAChD,MAAM,aAAa,aAAa,IAAI,SAAS;GAC7C,IACE,UAAU,wBACV,eAAe,KAAA,MACd,SAAS,KAAA,KAAa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,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"}
@@ -50,9 +50,11 @@ async function pollUntilDeadline(options) {
50
50
  let probeSucceeded = false;
51
51
  let lastAnswerAt = now();
52
52
  let deadlineReached = false;
53
+ let expiredAtDeadline;
53
54
  while (!signal.aborted) {
54
55
  if (deadline.reached()) {
55
56
  deadlineReached = true;
57
+ expiredAtDeadline = deadline.expiredAt();
56
58
  break;
57
59
  }
58
60
  try {
@@ -79,7 +81,13 @@ async function pollUntilDeadline(options) {
79
81
  value
80
82
  };
81
83
  } catch (_) {}
82
- if (probeSucceeded && deadlineReached) return { kind: "not-confirmed" };
84
+ if (probeSucceeded && deadlineReached) {
85
+ const expiredAt = expiredAtDeadline === void 0 ? void 0 : deadline.expiredAt();
86
+ return expiredAt === void 0 ? { kind: "not-confirmed" } : {
87
+ kind: "expired",
88
+ slot: expiredAt
89
+ };
90
+ }
83
91
  if (options.neverBroadcast?.()) throw new Error(`Every ${subject} send to this RPC failed.`);
84
92
  if (!probeSucceeded) throw new Error(`No ${read} against this RPC ever completed.`);
85
93
  throw new Error(`This RPC stopped answering before a final ${read} could run.`);
@@ -1 +1 @@
1
- {"version":3,"file":"pollUntilDeadline.js","names":[],"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,MAAM,eAAA,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,MAAM,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":[],"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;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