@lifi/sdk-provider-solana 4.3.3 → 4.3.4

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 +8 -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 +51 -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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @lifi/sdk-provider-solana
2
2
 
3
+ ## 4.3.4
4
+
5
+ ### Patch Changes
6
+
7
+ - [#507](https://github.com/lifinance/sdk/pull/507) [`14f4ecc`](https://github.com/lifinance/sdk/commit/14f4ecc2714799449d57b61ff06b040df505184e) Thanks [@chybisov](https://github.com/chybisov)! - Resume a signed or broadcast transaction instead of signing again. The signed transaction is stored in `txHex` and resent after a reload until it confirms or its blockhash expires (a durable-nonce transaction only within two minutes of signing); a transaction is declared dropped only when it can no longer land, an RPC whose history covers the signing time does not find it, and the LI.FI status API does not know it. It can no longer land when its blockhash expired or, without a blockhash verdict (an RPC without `isBlockhashValid`, a probe error, no RPC answering, a route stored without `txHex`, or a durable-nonce transaction past its two-minute resend window), about 5 minutes after signing (`isOldEnoughToDrop`). The sign task checks the action again after the wallet returns: if a stopped run's transaction merged into it while the prompt was open, the step fails with `TransactionConflict` and the new signature is neither stored nor sent. The wallet account is resolved only when signing. An expired blockhash after the SDK stopped waiting now reports `TransactionExpired` instead of `RpcUnavailable` when an RPC answered.
8
+ - Updated dependencies [[`bb964c0`](https://github.com/lifinance/sdk/commit/bb964c03d8ea1770303ab1bba803373a80e6388f), [`48af3ae`](https://github.com/lifinance/sdk/commit/48af3aeb250299ef9d2ff9eb79a38a6b8f52d409), [`14f4ecc`](https://github.com/lifinance/sdk/commit/14f4ecc2714799449d57b61ff06b040df505184e)]:
9
+ - @lifi/sdk@4.11.0
10
+
3
11
  ## 4.3.3
4
12
 
5
13
  ### Patch Changes
package/README.md CHANGED
@@ -83,6 +83,13 @@ needs no ecosystem library. To discover and connect browser wallets such as Frei
83
83
  xBull, or Lobstr, we recommend
84
84
  [Stellar Wallets Kit](https://github.com/Creit-Tech/Stellar-Wallets-Kit).
85
85
 
86
+ **Zcash**
87
+ ```bash
88
+ pnpm add @lifi/sdk-provider-zcash
89
+ ```
90
+
91
+ ZEC is a destination-only chain: `ZcashProvider` validates transparent `t1` and `t3` receivers, and unified `u1` receivers that carry an Orchard receiver, and needs no wallet. Register it after `BitcoinProvider`; it serves ZEC only.
92
+
86
93
  ## Architecture
87
94
 
88
95
  The LI.FI SDK uses a modular provider architecture:
@@ -134,6 +141,7 @@ import { BitcoinProvider } from '@lifi/sdk-provider-bitcoin'
134
141
  import { SuiProvider } from '@lifi/sdk-provider-sui'
135
142
  import { TronProvider } from '@lifi/sdk-provider-tron'
136
143
  import { StellarProvider } from '@lifi/sdk-provider-stellar'
144
+ import { ZcashProvider } from '@lifi/sdk-provider-zcash'
137
145
 
138
146
  const client = createClient({
139
147
  integrator: 'Your dApp/company name',
@@ -144,6 +152,7 @@ const client = createClient({
144
152
  SuiProvider({ /* options */ }),
145
153
  TronProvider({ /* options */ }),
146
154
  StellarProvider({ /* options */ }),
155
+ ZcashProvider(),
147
156
  ],
148
157
  })
149
158
  ```
@@ -0,0 +1,66 @@
1
+ import { SignatureStatus } from "../confirmation/types.js";
2
+ import { SDKClient } from "@lifi/sdk";
3
+ import { Signature } from "@solana/kit";
4
+ //#region src/actions/lookupSignatureStatus.d.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
+ export declare 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
+ export declare 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
+ export declare 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
+ export declare const SLOT_DURATION_MS = 400;
21
+ /** How far each canary search steps over skipped or empty slots. */
22
+ export declare const CANARY_SLOT_STEPS = 32;
23
+ export type LookupBounds = {
24
+ /** The earliest time the transaction can have landed, in ms since the
25
+ * epoch: `execution.signedAt - CLOCK_SKEW_MARGIN_MS`. */
26
+ anchor: number;
27
+ /** The slot of the expiry verdict (the `expired` result): the highest
28
+ * slot of the expiry streak. A node's head at or past it (`>=`) has seen
29
+ * every slot the transaction could land in. Without a verdict the freshest
30
+ * current slot of the RPCs is the head. */
31
+ expiredAtSlot?: bigint;
32
+ /** Injectable clock for the canary bound. */
33
+ now?: number;
34
+ };
35
+ export type SignatureLookup = {
36
+ kind: "found";
37
+ status: SignatureStatus;
38
+ } | {
39
+ kind: "not-found";
40
+ } | {
41
+ kind: "unknown";
42
+ answered: boolean;
43
+ errors: Error[];
44
+ };
45
+ /**
46
+ * Looks a signature up on every Solana RPC, the transaction history
47
+ * included.
48
+ *
49
+ * Not `raceRpcs`: a race returns the first answer, and one pruned or lagging
50
+ * node answering `null` would then read as "the transaction does not exist".
51
+ * A node's `null` proves nothing on its own either: a default RPC forgets
52
+ * signatures after about two days, a node on a minority fork has not seen
53
+ * the majority's blocks, and a pool may route each request to another
54
+ * backend. So with `bounds` the same request also asks for two canaries:
55
+ * one that landed before the transaction could, and one from a confirmed
56
+ * block at or after the expiry. The `null` counts only when that response
57
+ * knows both canaries and its head is at or past the last slot the
58
+ * transaction could land in.
59
+ *
60
+ * Takes at most `COVERAGE_PROOF_TIMEOUT_MS + CANARY_CALL_TIMEOUT_MS` for
61
+ * the proof search and `SIGNATURE_LOOKUP_TIMEOUT_MS` for the status
62
+ * request. Never throws.
63
+ */
64
+ export declare function lookupSignatureStatus(client: SDKClient, signature: Signature, bounds?: LookupBounds): Promise<SignatureLookup>;
65
+ //#endregion
66
+ //# sourceMappingURL=lookupSignatureStatus.d.ts.map
@@ -0,0 +1,258 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_rpc_registry = require("../rpc/registry.js");
3
+ const require_confirmation_types = require("../confirmation/types.js");
4
+ let _solana_kit = require("@solana/kit");
5
+ //#region src/actions/lookupSignatureStatus.ts
6
+ /** Budget of each `getSignatureStatuses` call, the status request. A hung
7
+ * endpoint would otherwise hold the `allSettled` below - and the wait task
8
+ * with it - open for good. */
9
+ const SIGNATURE_LOOKUP_TIMEOUT_MS = 15e3;
10
+ /** Budget of each `getSlot` and `getBlock` call of the proof search. An RPC
11
+ * that has not answered by then counts as silent, as a rejection does, and
12
+ * is left out of the rest of the search: a single hung RPC must not block a
13
+ * verdict when other RPCs answer. */
14
+ const CANARY_CALL_TIMEOUT_MS = 3e3;
15
+ /** Budget of the whole proof search. Past it the lookup asks for the target
16
+ * alone: it can still find the transaction, but it cannot prove absence. */
17
+ const COVERAGE_PROOF_TIMEOUT_MS = 1e4;
18
+ /** Target slot time. Real slots are rarely faster, so `ceil(age / 400)`
19
+ * slots back reach at or before the anchor; the anchor's clock-skew margin
20
+ * absorbs the rest. */
21
+ const SLOT_DURATION_MS = 400;
22
+ /** How far each canary search steps over skipped or empty slots. */
23
+ const CANARY_SLOT_STEPS = 32;
24
+ /** The history canary block. Old enough to be finalized everywhere. */
25
+ const HISTORY_BLOCK_CONFIG = {
26
+ transactionDetails: "signatures",
27
+ rewards: false,
28
+ maxSupportedTransactionVersion: 0
29
+ };
30
+ /** The head canary block: only a block the majority confirmed. */
31
+ const HEAD_BLOCK_CONFIG = {
32
+ commitment: "confirmed",
33
+ ...HISTORY_BLOCK_CONFIG
34
+ };
35
+ /** Never throws: `String()` throws on an object without a prototype, and a
36
+ * proxy can throw on `instanceof`. */
37
+ const toError = (reason) => {
38
+ try {
39
+ return reason instanceof Error ? reason : new Error(String(reason));
40
+ } catch {
41
+ return /* @__PURE__ */ new Error("An RPC call failed with a reason that cannot be read.");
42
+ }
43
+ };
44
+ /** Only an object is a status. Unvalidated wire data, so `true` or a
45
+ * string is no answer. */
46
+ const isStatus = (entry) => typeof entry === "object" && entry !== null;
47
+ /** A canary status counts only with the slot of the block that supplied the
48
+ * canary. A node on a minority fork can hold the head canary transaction if
49
+ * the same transaction also landed on its fork; its status then has another
50
+ * slot. This also rejects `{}`, arrays and a status without a bigint slot. */
51
+ const isCanaryStatus = (entry, canary) => isStatus(entry) && typeof entry.slot === "bigint" && entry.slot === canary.slot;
52
+ /** `isSignature` throws on a 64-88 character string that is not base58.
53
+ * Here a throw means "not a signature". */
54
+ const isSignatureEntry = (entry) => {
55
+ if (typeof entry !== "string") return false;
56
+ try {
57
+ return (0, _solana_kit.isSignature)(entry);
58
+ } catch {
59
+ return false;
60
+ }
61
+ };
62
+ var CallTimeoutError = class extends Error {};
63
+ /**
64
+ * Runs `call` with its own abort signal and a budget of `timeoutMs`. Past
65
+ * the budget it rejects with a `CallTimeoutError` and aborts the call. The
66
+ * race does not rely on the transport to honour the abort. A synchronous
67
+ * throw of `call` becomes a rejection too.
68
+ */
69
+ function callWithin(call, timeoutMs) {
70
+ const controller = new AbortController();
71
+ let timer;
72
+ const timeout = new Promise((_resolve, reject) => {
73
+ timer = setTimeout(() => {
74
+ const error = new CallTimeoutError(`This RPC did not answer within ${timeoutMs}ms.`);
75
+ controller.abort(error);
76
+ reject(error);
77
+ }, timeoutMs);
78
+ });
79
+ const answer = new Promise((resolve) => resolve(call(controller.signal)));
80
+ return Promise.race([answer, timeout]).finally(() => clearTimeout(timer));
81
+ }
82
+ /**
83
+ * Looks a signature up on every Solana RPC, the transaction history
84
+ * included.
85
+ *
86
+ * Not `raceRpcs`: a race returns the first answer, and one pruned or lagging
87
+ * node answering `null` would then read as "the transaction does not exist".
88
+ * A node's `null` proves nothing on its own either: a default RPC forgets
89
+ * signatures after about two days, a node on a minority fork has not seen
90
+ * the majority's blocks, and a pool may route each request to another
91
+ * backend. So with `bounds` the same request also asks for two canaries:
92
+ * one that landed before the transaction could, and one from a confirmed
93
+ * block at or after the expiry. The `null` counts only when that response
94
+ * knows both canaries and its head is at or past the last slot the
95
+ * transaction could land in.
96
+ *
97
+ * Takes at most `COVERAGE_PROOF_TIMEOUT_MS + CANARY_CALL_TIMEOUT_MS` for
98
+ * the proof search and `SIGNATURE_LOOKUP_TIMEOUT_MS` for the status
99
+ * request. Never throws.
100
+ */
101
+ async function lookupSignatureStatus(client, signature, bounds) {
102
+ try {
103
+ const rpcs = await require_rpc_registry.getSolanaRpcs(client);
104
+ const proof = bounds ? await findCoverageProof(rpcs, bounds) : void 0;
105
+ const signatures = proof ? [
106
+ signature,
107
+ proof.historyCanary.signature,
108
+ proof.headCanary.signature
109
+ ] : [signature];
110
+ return classifyReads(await Promise.allSettled(rpcs.map((rpc) => callWithin((abortSignal) => rpc.getSignatureStatuses(signatures, { searchTransactionHistory: true }).send({ abortSignal }), SIGNATURE_LOOKUP_TIMEOUT_MS))), proof);
111
+ } catch (error) {
112
+ return {
113
+ kind: "unknown",
114
+ answered: false,
115
+ errors: [toError(error)]
116
+ };
117
+ }
118
+ }
119
+ function classifyReads(reads, proof) {
120
+ let found;
121
+ let provenAbsent = false;
122
+ let answered = false;
123
+ const errors = [];
124
+ for (const read of reads) {
125
+ if (read.status === "rejected") {
126
+ errors.push(toError(read.reason));
127
+ continue;
128
+ }
129
+ const statuses = read.value?.value;
130
+ if (!Array.isArray(statuses) || statuses.length === 0) {
131
+ errors.push(/* @__PURE__ */ new Error("The signature status response carried no statuses."));
132
+ continue;
133
+ }
134
+ const [target, historyCanary, headCanary] = statuses;
135
+ if (isStatus(target)) {
136
+ answered = true;
137
+ if (!found || !require_confirmation_types.isConfirmedCommitment(found.confirmationStatus) && require_confirmation_types.isConfirmedCommitment(target.confirmationStatus)) found = target;
138
+ continue;
139
+ }
140
+ if (target !== null) {
141
+ errors.push(/* @__PURE__ */ new Error("The signature status response was unusable."));
142
+ continue;
143
+ }
144
+ answered = true;
145
+ const headSlot = read.value?.context?.slot;
146
+ if (!proof) errors.push(/* @__PURE__ */ new Error("This null carries no coverage proof: no canary was asked for."));
147
+ 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."));
148
+ 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."));
149
+ 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."));
150
+ else provenAbsent = true;
151
+ }
152
+ if (found) return {
153
+ kind: "found",
154
+ status: found
155
+ };
156
+ if (provenAbsent) return { kind: "not-found" };
157
+ return {
158
+ kind: "unknown",
159
+ answered,
160
+ errors
161
+ };
162
+ }
163
+ /** Up to `CANARY_SLOT_STEPS` slots from `from` in `direction`, within
164
+ * `[0, last]`. */
165
+ function slotsFrom(from, direction, last = from) {
166
+ const slots = [];
167
+ for (let step = 0n; step < BigInt(32); step += 1n) {
168
+ const slot = from + direction * step;
169
+ if (slot < 0n || direction === 1n && slot > last) break;
170
+ slots.push(slot);
171
+ }
172
+ return slots;
173
+ }
174
+ /**
175
+ * The canaries and the head a `null` has to meet. `undefined` when no RPC
176
+ * reports its current slot, no RPC supplies a canary block, the age is not
177
+ * positive, or the search runs out of time - then no answer can prove
178
+ * absence.
179
+ *
180
+ * - History canary: a block at or before
181
+ * `lowest current slot - ceil(age / SLOT_DURATION_MS)`, stepping down.
182
+ * The lowest slot places it: one RPC ahead of the others - or wrong - must
183
+ * not move it after the anchor.
184
+ * - Head canary: a `confirmed` block at or after `expiredAtSlot`, stepping
185
+ * up toward the current slot. Without a verdict, the freshest confirmed
186
+ * block, stepping down from the highest current slot, which is then also
187
+ * the head.
188
+ */
189
+ async function findCoverageProof(rpcs, bounds) {
190
+ const age = (bounds.now ?? Date.now()) - bounds.anchor;
191
+ if (!Number.isFinite(age) || age <= 0) return;
192
+ let outOfTime = false;
193
+ const deadline = setTimeout(() => {
194
+ outOfTime = true;
195
+ }, COVERAGE_PROOF_TIMEOUT_MS);
196
+ const silent = /* @__PURE__ */ new Set();
197
+ /** The answers of the RPCs that are not silent, each within its budget. */
198
+ const ask = async (call) => {
199
+ const asked = rpcs.filter((rpc) => !silent.has(rpc));
200
+ const results = await Promise.allSettled(asked.map((rpc) => callWithin((abortSignal) => call(rpc, abortSignal), CANARY_CALL_TIMEOUT_MS)));
201
+ const answers = [];
202
+ results.forEach((result, index) => {
203
+ if (result.status === "fulfilled") answers.push(result.value);
204
+ else if (result.reason instanceof CallTimeoutError) silent.add(asked[index]);
205
+ });
206
+ return answers;
207
+ };
208
+ /** A signature from the first of `slots` whose block any RPC supplies,
209
+ * with the slot of that block. */
210
+ const canaryFrom = async (slots, config) => {
211
+ for (const slot of slots) {
212
+ if (outOfTime) return;
213
+ const signature = firstSignatureOf(await ask((rpc, abortSignal) => rpc.getBlock(slot, config).send({ abortSignal })));
214
+ if (signature) return {
215
+ signature,
216
+ slot
217
+ };
218
+ }
219
+ };
220
+ try {
221
+ const slots = (await ask((rpc, abortSignal) => rpc.getSlot({ commitment: "confirmed" }).send({ abortSignal }))).filter((slot) => typeof slot === "bigint");
222
+ if (slots.length === 0) return;
223
+ const lowestSlot = slots.reduce((low, slot) => slot < low ? slot : low);
224
+ const highestSlot = slots.reduce((high, slot) => slot > high ? slot : high);
225
+ const historyCanary = await canaryFrom(slotsFrom(lowestSlot - BigInt(Math.ceil(age / 400)), -1n), HISTORY_BLOCK_CONFIG);
226
+ if (!historyCanary) return;
227
+ const { expiredAtSlot } = bounds;
228
+ const headCanary = await canaryFrom(expiredAtSlot === void 0 ? slotsFrom(highestSlot, -1n) : slotsFrom(expiredAtSlot, 1n, highestSlot > expiredAtSlot ? highestSlot : expiredAtSlot), HEAD_BLOCK_CONFIG);
229
+ if (!headCanary) return;
230
+ return {
231
+ historyCanary,
232
+ headCanary,
233
+ headSlot: expiredAtSlot ?? highestSlot
234
+ };
235
+ } finally {
236
+ clearTimeout(deadline);
237
+ }
238
+ }
239
+ /** A signature from the first block that has one. `undefined` for skipped
240
+ * or empty slots, pruned history or an outage. */
241
+ function firstSignatureOf(blocks) {
242
+ for (const block of blocks) {
243
+ if (typeof block !== "object" || block === null) continue;
244
+ const { signatures } = block;
245
+ if (!Array.isArray(signatures)) continue;
246
+ const canary = signatures.find(isSignatureEntry);
247
+ if (canary) return canary;
248
+ }
249
+ }
250
+ //#endregion
251
+ exports.CANARY_CALL_TIMEOUT_MS = CANARY_CALL_TIMEOUT_MS;
252
+ exports.CANARY_SLOT_STEPS = CANARY_SLOT_STEPS;
253
+ exports.COVERAGE_PROOF_TIMEOUT_MS = COVERAGE_PROOF_TIMEOUT_MS;
254
+ exports.SIGNATURE_LOOKUP_TIMEOUT_MS = SIGNATURE_LOOKUP_TIMEOUT_MS;
255
+ exports.SLOT_DURATION_MS = SLOT_DURATION_MS;
256
+ exports.lookupSignatureStatus = lookupSignatureStatus;
257
+
258
+ //# sourceMappingURL=lookupSignatureStatus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lookupSignatureStatus.js","names":["isSignature","getSolanaRpcs","isConfirmedCommitment"],"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;;;AAGtC,MAAa,4BAA4B;;;;AAIzC,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;;AA2CjC,MAAM,uBAAuB;CAC3B,oBAAoB;CACpB,SAAS;CACT,gCAAgC;AAClC;;AAEA,MAAM,oBAAoB;CACxB,YAAY;CACZ,GAAG;AACL;;;AAIA,MAAM,WAAW,WAA2B;CAC1C,IAAI;EACF,OAAO,kBAAkB,QAAQ,SAAS,IAAI,MAAM,OAAO,MAAM,CAAC;CACpE,QAAQ;EACN,uBAAO,IAAI,MAAM,uDAAuD;CAC1E;AACF;;;AAIA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU;;;;;AAMzC,MAAM,kBAAkB,OAAgB,WACtC,SAAS,KAAK,KACd,OAAO,MAAM,SAAS,YACtB,MAAM,SAAS,OAAO;;;AAIxB,MAAM,oBAAoB,UAAuC;CAC/D,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,IAAI;EACF,QAAA,GAAOA,YAAAA,YAAAA,CAAY,KAAK;CAC1B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,IAAM,mBAAN,cAA+B,MAAM,CAAC;;;;;;;AAQtC,SAAS,WACP,MACA,WACY;CACZ,MAAM,aAAa,IAAI,gBAAgB;CACvC,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,UAAU,WAAW;EACvD,QAAQ,iBAAiB;GACvB,MAAM,QAAQ,IAAI,iBAChB,kCAAkC,UAAU,IAC9C;GACA,WAAW,MAAM,KAAK;GACtB,OAAO,KAAK;EACd,GAAG,SAAS;CACd,CAAC;CACD,MAAM,SAAS,IAAI,SAAY,YAAY,QAAQ,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,IAAI,CAAC,YACH;EAEF,OAAO;GACL;GACA;GACA,UAAU,iBAAiB;EAC7B;CACF,UAAU;EACR,aAAa,QAAQ;CACvB;AACF;;;AAIA,SAAS,iBAAiB,QAA0C;CAClE,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC;EAEF,MAAM,EAAE,eAAe;EACvB,IAAI,CAAC,MAAM,QAAQ,UAAU,GAC3B;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
@@ -41,6 +41,7 @@ async function sendAndConfirmTransaction(client, signedTransaction, options) {
41
41
  encoding: "base64"
42
42
  };
43
43
  const send = async (rpc, signal) => {
44
+ if (options?.mayResend && !options.mayResend()) throw new Error("The resend age cap has passed; the stored transaction is not sent again.");
44
45
  await rpc.sendTransaction(signedTxSerialized, rawTransactionOptions).send({ abortSignal: signal });
45
46
  };
46
47
  const writeRpcs = writeRpcUrls.length ? require_rpc_registry.getSolanaWriteRpcs(writeRpcUrls) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"sendAndConfirmTransaction.js","names":["getSolanaRpcs","ChainId","getBase64EncodedWireTransaction","getSignatureFromTransaction","getTransactionLifetime","getSolanaWriteRpcs","RESEND_INTERVAL_MS","raceRpcs","confirmSignature","BRANCH_TIMEOUT_MS"],"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' && !sendAcc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EAGnB,MAAM,QAAQ,KAAK,QAAQ,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC;EAEtD,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,GACpEC,sCAAAA,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,MAAMC,8BAAAA,SACb,aACC,KAAK,WACJC,sCAAAA,iBAAiB;GACf;GACA;GACA,WAAW;GACX,WAAW,CAAC,QAAQ;GACpB;GACA,aAAa;EACf,CAAC,GACH,EAAE,WAAWC,gDAAAA,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":["getSolanaRpcs","ChainId","getBase64EncodedWireTransaction","getSignatureFromTransaction","getTransactionLifetime","getSolanaWriteRpcs","RESEND_INTERVAL_MS","raceRpcs","confirmSignature","BRANCH_TIMEOUT_MS"],"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":";;;;;;;;;;;;;;;;;;;;;AA8BA,eAAsB,0BACpB,QACA,mBACA,SAWsC;CACtC,MAAM,CAAC,YAAY,eAAe,CAAC,KAAK,MAAM,QAAQ,IAAI,CACxDA,qBAAAA,cAAc,MAAM,GACpB,OAAO,2BAA2BC,UAAAA,QAAQ,GAAG,CAC/C,CAAC;CAED,IAAI,oBAAoB;CAMxB,IAAI,eAAe;CACnB,MAAM,wBAA8B;EAClC,eAAe;EACf,IAAI,mBACF;EAEF,IAAI;GACF,SAAS,cAAc;GAIvB,oBAAoB;EACtB,SAAS,GAAG,CAOZ;CACF;CAEA,MAAM,sBAAA,GAAqBC,YAAAA,gCAAAA,CAAgC,iBAAiB;CAC5E,MAAM,eAAA,GAAcC,YAAAA,4BAAAA,CAA4B,iBAAiB;CAEjE,MAAM,WAAW,MAAMC,qCAAAA,uBAAuB,iBAAiB;CAE/D,MAAM,wBAAwB;EAG5B,eAAe;EAEf,YAAY,OAAO,CAAC;EAEpB,qBAAqB;EACrB,UAAU;CACZ;CAEA,MAAM,OAAO,OACX,KACA,WACkB;EAGlB,IAAI,SAAS,aAAa,CAAC,QAAQ,UAAU,GAC3C,MAAM,IAAI,MACR,0EACF;EAEF,MAAM,IACH,gBAAgB,oBAAoB,qBAAqB,CAAC,CAC1D,KAAK,EAAE,aAAa,OAAO,CAAC;CACjC;CAEA,MAAM,YAAY,aAAa,SAC3BC,qBAAAA,mBAAmB,YAAY,IAC/B,KAAA;CAKJ,MAAM,SAAS,IAAI,gBAAgB;CAKnC,IAAI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AG1D,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>;
@@ -38,20 +38,27 @@ function createConfirmationDeadline(options) {
38
38
  const blockhashLifetimes = lifetimes.filter((lifetime) => lifetime.kind === "blockhash");
39
39
  const blockhashes = lifetimes.length > 0 && blockhashLifetimes.length === lifetimes.length ? [...new Set(blockhashLifetimes.map((lifetime) => lifetime.blockhash))] : [];
40
40
  const expiredStreaks = /* @__PURE__ */ new Map();
41
+ const expiredSlots = /* @__PURE__ */ new Map();
41
42
  const errorStreaks = /* @__PURE__ */ new Map();
42
43
  const probeable = new Set(blockhashes);
43
44
  let lastProbeAt;
44
45
  /** Derived, not latched: a blockhash that reads valid again zeroes its
45
- * streak and clears the verdict with it. */
46
- const isExpired = () => {
47
- for (const streak of expiredStreaks.values()) if (streak >= EXPIRY_CONFIRMATIONS) return true;
48
- return false;
46
+ * streak and clears the verdict with it. The highest slot among the expired
47
+ * blockhashes is the strictest head bound. */
48
+ const expiredAt = () => {
49
+ let slot;
50
+ for (const [blockhash, streak] of expiredStreaks) {
51
+ const observedAt = expiredSlots.get(blockhash);
52
+ if (streak >= EXPIRY_CONFIRMATIONS && observedAt !== void 0 && (slot === void 0 || observedAt > slot)) slot = observedAt;
53
+ }
54
+ return slot;
49
55
  };
50
56
  return {
51
57
  reached() {
52
58
  if (now() - startedAt >= 9e4) return true;
53
- return isExpired();
59
+ return expiredAt() !== void 0;
54
60
  },
61
+ expiredAt,
55
62
  async tick(signal) {
56
63
  if (probeable.size === 0 || signal.aborted) return;
57
64
  const probeAt = now();
@@ -59,10 +66,15 @@ function createConfirmationDeadline(options) {
59
66
  lastProbeAt = probeAt;
60
67
  const active = [...probeable];
61
68
  const probes = await Promise.allSettled(active.map(async (blockhash) => {
62
- return (await rpc.isBlockhashValid(blockhash, { commitment: "confirmed" }).send({ abortSignal: signal })).value;
69
+ const result = await rpc.isBlockhashValid(blockhash, { commitment: "confirmed" }).send({ abortSignal: signal });
70
+ return {
71
+ value: result?.value,
72
+ slot: result?.context?.slot
73
+ };
63
74
  }));
64
75
  const recordFailedProbe = (blockhash) => {
65
76
  expiredStreaks.set(blockhash, 0);
77
+ expiredSlots.delete(blockhash);
66
78
  const errors = (errorStreaks.get(blockhash) ?? 0) + 1;
67
79
  errorStreaks.set(blockhash, errors);
68
80
  if (errors >= 5) probeable.delete(blockhash);
@@ -73,14 +85,18 @@ function createConfirmationDeadline(options) {
73
85
  recordFailedProbe(blockhash);
74
86
  return;
75
87
  }
76
- if (probe.value === true) {
88
+ const { value, slot } = probe.value;
89
+ if (value === true) {
77
90
  errorStreaks.set(blockhash, 0);
78
91
  expiredStreaks.set(blockhash, 0);
92
+ expiredSlots.delete(blockhash);
79
93
  return;
80
94
  }
81
- if (probe.value === false) {
95
+ if (value === false && typeof slot === "bigint") {
82
96
  errorStreaks.set(blockhash, 0);
83
97
  expiredStreaks.set(blockhash, (expiredStreaks.get(blockhash) ?? 0) + 1);
98
+ const previous = expiredSlots.get(blockhash);
99
+ expiredSlots.set(blockhash, previous === void 0 || slot > previous ? slot : previous);
84
100
  return;
85
101
  }
86
102
  recordFailedProbe(blockhash);