@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -1,22 +1,5 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
- /**
3
- * Confirmation tracker (v2.0, design §7).
4
- *
5
- * Watches `submitted` jobs until their tx sits at depth ≥ `confirmationDepth`:
6
- * - Crawler hook (preferred, zero extra load): `blockIndexed` events match
7
- * submitted tx hashes and carry the advancing tip; `reorg` events invalidate
8
- * confirmation points behind the fork and optionally re-submit the SAME
9
- * signed CBOR (never a rebuild — the double-spend guard).
10
- * - Polling fallback (always on, hook path just accelerates): every
11
- * `pollIntervalMs` unfound txs are looked up via `client.getTransaction`
12
- * and the tip via `client.getLatestBlock`.
13
- *
14
- * A tx that stays unseen past `confirmationTimeoutMs` fails as TX_DROPPED —
15
- * safe to retry from the caller, because the guard is the on-chain lookup itself.
16
- *
17
- * Confirmations are counted as `tipHeight - foundHeight + 1`, so depth 1 means
18
- * "confirmed as soon as included in a block".
19
- */
2
+ import { type LandingIndexer } from '../signing/landing-proof';
20
3
  export interface TrackedJob {
21
4
  jobId: string;
22
5
  walletId: string;
@@ -28,13 +11,13 @@ export interface TrackedJob {
28
11
  submittedAt: string;
29
12
  foundSlot: number | null;
30
13
  foundHeight: number | null;
31
- /**
32
- * Polling round in which the tx was last SEEN on-chain (found or
33
- * re-validated). A job found in the current round needs no second lookup
34
- * before it is confirmed; one found in an earlier round is re-checked, so a
35
- * rollback the crawler did not report (crawler off) cannot slip through.
36
- */
14
+ /** Polling round that last saw the tx. Older inclusions are re-checked to catch unreported rollbacks. */
37
15
  seenRound?: number;
16
+ /** Epoch ms before which an overdue job has no chain read. */
17
+ nextLandingCheckAt?: number;
18
+ /** Epoch ms before which an overdue job is not sent again, and how often it was. */
19
+ nextResendAt?: number;
20
+ resends?: number;
38
21
  }
39
22
  export interface ConfirmationTrackerOptions {
40
23
  confirmationDepth: number;
@@ -44,18 +27,28 @@ export interface ConfirmationTrackerOptions {
44
27
  }
45
28
  export interface ConfirmationTrackerDeps {
46
29
  client: CardanoClient;
30
+ /** The local index, read before any backend. */
31
+ indexer: LandingIndexer;
47
32
  options: ConfirmationTrackerOptions;
48
33
  /** Called exactly once per job when it reaches a terminal state. */
49
34
  onFinal?: (job: {
50
35
  jobId: string;
51
36
  walletId: string;
52
- outcome: 'confirmed' | 'failed';
37
+ outcome: 'confirmed' | 'failed' | 'unresolved';
53
38
  kind: string | null;
54
- /** The tracked transaction — present even on failure (it was submitted). */
39
+ /** Set even on failure, since the tx was submitted. */
55
40
  txHash: string;
56
41
  errorCode?: string;
57
42
  errorMessage?: string;
58
43
  }) => void;
44
+ /** Called when a job's transaction has no expiry, has not landed and still can through these inputs. */
45
+ onStale?: (job: {
46
+ jobId: string;
47
+ walletId: string;
48
+ }, unspentInputs: Array<{
49
+ txHash: string;
50
+ outputIndex: number;
51
+ }>) => void;
59
52
  }
60
53
  export declare class ConfirmationTracker {
61
54
  private readonly deps;
@@ -73,6 +66,8 @@ export declare class ConfirmationTracker {
73
66
  stop(): void;
74
67
  /** Number of jobs currently awaiting confirmation. */
75
68
  size(): number;
69
+ /** Stops watching a job another path finalized. */
70
+ untrack(jobId: string): void;
76
71
  /** Register a submitted job for confirmation watching. Idempotent per jobId. */
77
72
  track(job: {
78
73
  jobId: string;
@@ -86,31 +81,16 @@ export declare class ConfirmationTracker {
86
81
  }): void;
87
82
  private onBlockIndexed;
88
83
  private onReorg;
89
- /**
90
- * The recorded inclusion is gone (a reorg the crawler reported, or a polling
91
- * re-check that no longer finds the tx): back to watching, and optionally
92
- * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
93
- * guard. "Already known" means the tx survived into the new chain's mempool;
94
- * that is success, not an error.
95
- */
84
+ /** Back to watching. After a rollback it re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
96
85
  private forgetInclusion;
97
86
  /** One polling round. Public for tests; guarded against overlapping rounds. */
98
87
  pollOnce(): Promise<void>;
99
- /**
100
- * Confirm every found job whose depth requirement is met by the known tip.
101
- * `revalidate` (polling path): an inclusion not seen in THIS round is looked
102
- * up again first — the crawler's reorg events are the only rollback signal,
103
- * and with the crawler off there is none, so a tx that was found at height N
104
- * and then rolled back would otherwise be confirmed on the tip alone.
105
- */
88
+ private settleOverdue;
89
+ private locate;
90
+ private stillOnLedger;
91
+ /** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
106
92
  private confirmMature;
107
- /**
108
- * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
109
- * moved to another block (re-included after a rollback) gets its new point
110
- * and is judged at the new height; one that is gone is forgotten (back to
111
- * watching, optional same-CBOR re-submit) and the tip is re-learned next
112
- * round, because the pre-rollback tip may overstate the depth.
113
- */
93
+ /** True if the tx is still on-chain and deep enough. A moved tx takes its new height, a vanished one is watched again. */
114
94
  private stillIncluded;
115
95
  private finalize;
116
96
  }
@@ -5,10 +5,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ConfirmationTracker = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
+ const cardano_1 = require("#cds-models/odatano/cardano");
8
9
  const errors_1 = require("../../utils/errors");
10
+ const tx_utils_1 = require("../../utils/tx-utils");
11
+ const landing_proof_1 = require("../signing/landing-proof");
12
+ const transaction_presence_1 = require("../transaction-presence");
9
13
  const hooks_1 = require("../crawler/hooks");
10
14
  const job_store_1 = require("./job-store");
15
+ const { UPDATE } = cds_1.default.ql;
11
16
  const logger = cds_1.default.log('CardanoWalletWorker');
17
+ /** A job overdue for confirmation has the chain read for it at most this often. */
18
+ const LANDING_CHECK_INTERVAL_MS = 60_000;
19
+ /** First and longest wait before the stored bytes of an overdue job are sent again. */
20
+ const RESEND_BACKOFF_MIN_MS = 60_000;
21
+ const RESEND_BACKOFF_MAX_MS = 30 * 60_000;
12
22
  class ConfirmationTracker {
13
23
  deps;
14
24
  pending = new Map();
@@ -46,6 +56,10 @@ class ConfirmationTracker {
46
56
  size() {
47
57
  return this.pending.size;
48
58
  }
59
+ /** Stops watching a job another path finalized. */
60
+ untrack(jobId) {
61
+ this.pending.delete(jobId);
62
+ }
49
63
  /** Register a submitted job for confirmation watching. Idempotent per jobId. */
50
64
  track(job) {
51
65
  if (this.pending.has(job.jobId))
@@ -71,7 +85,7 @@ class ConfirmationTracker {
71
85
  }
72
86
  const txHashes = new Set(event.txHashes);
73
87
  const found = [...this.pending.values()].filter(j => j.foundHeight == null && txHashes.has(j.txHash));
74
- // Persist + depth-check detached: hook callers (the crawler) must not await us.
88
+ // Detached: hook callers (the crawler) must not await us.
75
89
  void (async () => {
76
90
  for (const job of found) {
77
91
  job.foundSlot = event.slot;
@@ -90,33 +104,25 @@ class ConfirmationTracker {
90
104
  async onReorg(event) {
91
105
  if (!this.running)
92
106
  return;
93
- // The pre-fork tip no longer exists — clamp (or drop) lastKnownTipHeight so
94
- // confirmations are never counted against it. Without this, a tx re-included
95
- // on the new chain would reach "depth" instantly via the stale tip height,
96
- // defeating the confirmation-depth guarantee exactly in the rollback case.
107
+ // Clamp (or drop) the stale pre-fork tip, otherwise a tx re-included on the new
108
+ // chain would reach depth instantly against it.
97
109
  if (event.forkHeight != null) {
98
110
  if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
99
111
  this.lastKnownTipHeight = event.forkHeight;
100
112
  }
101
113
  }
102
114
  else {
103
- this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
115
+ this.lastKnownTipHeight = null; // re-learn from the next block/poll
104
116
  }
105
117
  for (const job of this.pending.values()) {
106
118
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
107
- logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
119
+ logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot}, re-watching`);
108
120
  await this.forgetInclusion(job);
109
121
  }
110
122
  }
111
123
  }
112
- /**
113
- * The recorded inclusion is gone (a reorg the crawler reported, or a polling
114
- * re-check that no longer finds the tx): back to watching, and optionally
115
- * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
116
- * guard. "Already known" means the tx survived into the new chain's mempool;
117
- * that is success, not an error.
118
- */
119
- async forgetInclusion(job) {
124
+ /** Back to watching. After a rollback it re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
125
+ async forgetInclusion(job, resubmit = true) {
120
126
  job.foundSlot = null;
121
127
  job.foundHeight = null;
122
128
  job.seenRound = undefined;
@@ -126,14 +132,14 @@ class ConfirmationTracker {
126
132
  catch (err) {
127
133
  logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
128
134
  }
129
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
135
+ if (resubmit && this.deps.options.resubmitOnRollback && job.signedTxCbor && !(0, landing_proof_1.isExpired)(job.signedTxCbor, this.deps.client.network)) {
130
136
  try {
131
137
  await this.deps.client.submitTransaction(job.signedTxCbor);
132
138
  logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
133
139
  }
134
140
  catch (err) {
135
141
  if (err instanceof errors_1.TransactionAlreadySubmittedError) {
136
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
142
+ logger.debug(`Job ${job.jobId}: tx already known after rollback, nothing to do`);
137
143
  }
138
144
  else {
139
145
  logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
@@ -149,8 +155,7 @@ class ConfirmationTracker {
149
155
  this.polling = true;
150
156
  this.round++;
151
157
  try {
152
- // Tip first — also serves the depth check for hook-found entries when the
153
- // crawler is off.
158
+ // Tip first. It is also the depth check for hook-found entries when the crawler is off.
154
159
  try {
155
160
  const tip = await this.deps.client.getLatestBlock();
156
161
  if (tip.height != null) {
@@ -164,46 +169,106 @@ class ConfirmationTracker {
164
169
  for (const job of [...this.pending.values()]) {
165
170
  if (job.foundHeight != null)
166
171
  continue;
172
+ let found;
167
173
  try {
168
- const tx = await this.deps.client.getTransaction(job.txHash);
169
- job.foundSlot = tx.slot ?? null;
170
- job.foundHeight = tx.blockHeight ?? null;
174
+ found = await this.locate(job);
175
+ }
176
+ catch (err) {
177
+ logger.debug(`Job ${job.jobId}: confirmation lookup failed (transient, next round retries):`, err);
178
+ continue;
179
+ }
180
+ if (found?.scriptFailed) {
181
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(`Transaction ${job.txHash} is on chain with failing scripts: only its collateral was spent`));
182
+ continue;
183
+ }
184
+ if (found && found.height != null) {
185
+ job.foundSlot = found.slot;
186
+ job.foundHeight = found.height;
171
187
  job.seenRound = this.round;
172
188
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
173
189
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
190
+ continue;
174
191
  }
175
- catch (err) {
176
- // The client's failover wraps per-backend 404s into AllBackendsFailedError,
177
- // so a plain `instanceof NotFoundError` check never fires — the helper also
178
- // accepts "every consulted backend said 404" as proof of absence.
179
- if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
180
- // Not on-chain yet — check the mempool-TTL timeout.
181
- const age = Date.now() - Date.parse(job.submittedAt);
182
- if (age > this.deps.options.confirmationTimeoutMs) {
183
- await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(`Transaction ${job.txHash} not seen on-chain within ${this.deps.options.confirmationTimeoutMs}ms of submission`));
184
- }
185
- }
186
- else {
187
- logger.debug(`Job ${job.jobId}: confirmation lookup failed (transient, next round retries):`, err);
188
- }
192
+ if (Date.now() - Date.parse(job.submittedAt) > this.deps.options.confirmationTimeoutMs && job.signedTxCbor) {
193
+ await this.settleOverdue(job, job.signedTxCbor);
189
194
  }
190
195
  }
191
- // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
- // round is re-checked before it counts (see stillIncluded).
196
+ // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
193
197
  await this.confirmMature(true);
194
198
  }
195
199
  finally {
196
200
  this.polling = false;
197
201
  }
198
202
  }
203
+ // Unseen past the timeout: proof that it can never land fails the job, time alone proves nothing.
204
+ // While it stays open the same bytes go out again: a node may have dropped them from its mempool.
205
+ async settleOverdue(job, signedTxCbor) {
206
+ const now = Date.now();
207
+ if (now < (job.nextLandingCheckAt ?? 0))
208
+ return;
209
+ job.nextLandingCheckAt = now + LANDING_CHECK_INTERVAL_MS;
210
+ const sentAtMs = Date.parse(job.submittedAt);
211
+ const landing = await (0, tx_utils_1.runWithoutAmbientTx)(() => (0, landing_proof_1.judgeLanding)(signedTxCbor, job.txHash, this.deps, Number.isFinite(sentAtMs) ? sentAtMs : null));
212
+ if (landing.verdict === 'neverLands') {
213
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(landing.reason));
214
+ return;
215
+ }
216
+ if (landing.verdict === 'scriptFailed') {
217
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(landing.reason));
218
+ return;
219
+ }
220
+ if (landing.verdict === 'unresolved') {
221
+ await this.finalize(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, new Error(landing.reason));
222
+ return;
223
+ }
224
+ // no expiry and still able to land: the worker spends one of its inputs, no resend
225
+ if (landing.verdict === 'stale') {
226
+ this.deps.onStale?.({ jobId: job.jobId, walletId: job.walletId }, landing.unspentInputs);
227
+ return;
228
+ }
229
+ // expired bytes are refused by every node, sending them again only costs requests
230
+ if (landing.verdict !== 'open' || now < (job.nextResendAt ?? 0) || (0, landing_proof_1.isExpired)(signedTxCbor, this.deps.client.network))
231
+ return;
232
+ job.resends = (job.resends ?? 0) + 1;
233
+ job.nextResendAt = now + Math.min(RESEND_BACKOFF_MIN_MS * 2 ** (job.resends - 1), RESEND_BACKOFF_MAX_MS);
234
+ try {
235
+ await this.deps.client.submitTransaction(signedTxCbor);
236
+ logger.info(`Job ${job.jobId}: tx ${job.txHash} still unseen, sent its signed bytes again`);
237
+ }
238
+ catch (err) {
239
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError)) {
240
+ logger.debug(`Job ${job.jobId}: resend of tx ${job.txHash} was refused (the chain still decides):`, err);
241
+ }
242
+ }
243
+ }
199
244
  // ---- Shared -----------------------------------------------------------------
200
- /**
201
- * Confirm every found job whose depth requirement is met by the known tip.
202
- * `revalidate` (polling path): an inclusion not seen in THIS round is looked
203
- * up again first — the crawler's reorg events are the only rollback signal,
204
- * and with the crawler off there is none, so a tx that was found at height N
205
- * and then rolled back would otherwise be confirmed on the tip alone.
206
- */
245
+ // Where the transaction is: the crawled chain first, then a backend lookup. Without a transaction
246
+ // lookup an unspent output shows it on chain; its height is then taken as the tip, never deeper.
247
+ // Null when it is not on chain. Throws when a lookup gives no answer.
248
+ async locate(job) {
249
+ const presence = await (0, transaction_presence_1.findOnChain)(this.deps.indexer, this.deps.client, job.txHash);
250
+ if (presence)
251
+ return presence;
252
+ if (presence === null)
253
+ return null;
254
+ // only an own output seen unspent shows it on chain; spent inputs prove nothing about who spent them
255
+ if (job.signedTxCbor && this.lastKnownTipHeight != null && await (0, landing_proof_1.hasUnspentOutput)(job.signedTxCbor, job.txHash, this.deps.client)) {
256
+ return { slot: null, height: this.lastKnownTipHeight, scriptFailed: false };
257
+ }
258
+ return null;
259
+ }
260
+ // Without a transaction lookup, after an own output was seen. included: an own output is unspent.
261
+ // rolledBack: an input is unspent again. unknown: everything is spent, by whom shows nowhere.
262
+ async stillOnLedger(signedTxCbor, txHash) {
263
+ if (await (0, landing_proof_1.hasUnspentOutput)(signedTxCbor, txHash, this.deps.client))
264
+ return 'included';
265
+ for (const input of (0, landing_proof_1.landingFacts)(signedTxCbor).inputs) {
266
+ if (await this.deps.client.isUtxoUnspent(input.txHash, input.outputIndex))
267
+ return 'rolledBack';
268
+ }
269
+ return 'unknown';
270
+ }
271
+ /** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
207
272
  async confirmMature(revalidate = false) {
208
273
  const tip = this.lastKnownTipHeight;
209
274
  if (tip == null)
@@ -218,20 +283,43 @@ class ConfirmationTracker {
218
283
  await this.finalize(job, 'confirmed');
219
284
  }
220
285
  }
221
- /**
222
- * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
223
- * moved to another block (re-included after a rollback) gets its new point
224
- * and is judged at the new height; one that is gone is forgotten (back to
225
- * watching, optional same-CBOR re-submit) and the tip is re-learned next
226
- * round, because the pre-rollback tip may overstate the depth.
227
- */
286
+ /** True if the tx is still on-chain and deep enough. A moved tx takes its new height, a vanished one is watched again. */
228
287
  async stillIncluded(job, tip) {
288
+ if (!this.deps.client.supports('getTransaction')) {
289
+ if (!job.signedTxCbor)
290
+ return true;
291
+ let state;
292
+ try {
293
+ state = await this.stillOnLedger(job.signedTxCbor, job.txHash);
294
+ }
295
+ catch (err) {
296
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
297
+ return false;
298
+ }
299
+ job.seenRound = this.round;
300
+ if (state === 'included')
301
+ return true;
302
+ if (state === 'rolledBack') {
303
+ logger.warn(`Job ${job.jobId}: an input of tx ${job.txHash} is unspent again (was at height ${job.foundHeight}). Rollback without a crawler signal, re-watching`);
304
+ this.lastKnownTipHeight = null;
305
+ await this.forgetInclusion(job);
306
+ return false;
307
+ }
308
+ // its outputs and inputs are all spent: no evidence left that this transaction spent them
309
+ logger.warn(`Job ${job.jobId}: every output and input of tx ${job.txHash} is spent before the confirmation depth; nothing shows it is still included, waiting for the chain to decide`);
310
+ await this.forgetInclusion(job, false);
311
+ return false;
312
+ }
229
313
  try {
230
314
  const tx = await this.deps.client.getTransaction(job.txHash);
231
315
  const height = tx.blockHeight ?? null;
232
316
  job.seenRound = this.round;
317
+ if (tx.spendsCollaterals === true) {
318
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(`Transaction ${job.txHash} is on chain with failing scripts: only its collateral was spent`));
319
+ return false;
320
+ }
233
321
  if (height != null && height !== job.foundHeight) {
234
- logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
322
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height}, re-anchoring`);
235
323
  job.foundHeight = height;
236
324
  job.foundSlot = tx.slot ?? null;
237
325
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
@@ -241,7 +329,7 @@ class ConfirmationTracker {
241
329
  }
242
330
  catch (err) {
243
331
  if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
244
- logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
332
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}). Rollback without a crawler signal, re-watching`);
245
333
  this.lastKnownTipHeight = null;
246
334
  await this.forgetInclusion(job);
247
335
  return false;
@@ -254,27 +342,36 @@ class ConfirmationTracker {
254
342
  let transitioned = false;
255
343
  try {
256
344
  await cds_1.default.tx(async (tx) => {
345
+ if (outcome === 'unresolved') {
346
+ transitioned = await (0, job_store_1.markUnresolved)(tx, job.jobId, err ?? new Error('unresolved'));
347
+ if (transitioned)
348
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'unresolved' }).where({ txHash: job.txHash, status: 'submitted' }));
349
+ return;
350
+ }
257
351
  transitioned = outcome === 'confirmed'
258
352
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
259
- : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
353
+ : await (0, job_store_1.markFailedAfterSend)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
260
354
  if (transitioned) {
261
355
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
356
+ // the job's submission record follows its outcome
357
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: outcome }).where({ txHash: job.txHash, status: 'submitted' }));
262
358
  }
263
359
  });
264
360
  }
265
361
  catch (persistErr) {
266
362
  logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
267
- return; // keep tracking — the next poll round retries the transition
363
+ return; // keep tracking, the next round retries
268
364
  }
269
365
  this.pending.delete(job.jobId);
270
366
  if (!transitioned) {
271
- // Somebody else (another tracker instance, a reconciliation pass, a
272
- // cancel) reached the terminal state first. The job is done either way,
273
- // but the stats bump and the terminal event belong to the winner only.
274
- logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
367
+ // Another actor reached the terminal state first; stats bump and event belong to it.
368
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere, no event from this tracker`);
275
369
  return;
276
370
  }
277
- logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
371
+ if (outcome === 'unresolved')
372
+ logger.error(`Job ${job.jobId}: unresolved, an operator resolves it (${err instanceof Error ? err.message : String(err)})`);
373
+ else
374
+ logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
278
375
  this.deps.onFinal?.({
279
376
  jobId: job.jobId,
280
377
  walletId: job.walletId,
@@ -3,7 +3,7 @@ export type StartWalletWorkerDeps = Omit<WalletWorkerDeps, 'instanceId'> & {
3
3
  instanceId?: string;
4
4
  };
5
5
  export type { WalletWorkerConfig };
6
- /** Start the worker (idempotent — a no-op when one is already running). */
6
+ /** Starts the worker. A no-op when one is already running. */
7
7
  export declare function startWalletWorker(deps: StartWalletWorkerDeps): Promise<void>;
8
8
  /** Stop the local worker (in-flight execution steps are awaited). */
9
9
  export declare function stopWalletWorker(): Promise<void>;
@@ -11,19 +11,11 @@ const cds_1 = __importDefault(require("@sap/cds"));
11
11
  const node_crypto_1 = require("node:crypto");
12
12
  const wallet_worker_1 = require("./wallet-worker");
13
13
  const logger = cds_1.default.log('CardanoWalletWorker');
14
- /**
15
- * Module-level singleton lifecycle for the wallet worker. Mirrors the crawler's
16
- * srv/blockchain/crawler/index.ts: one active worker per process, started
17
- * fire-and-forget from the server's `served` hook and controlled (pause/resume/
18
- * status) via the worker control service.
19
- *
20
- * Unlike the crawler there is no standby machinery: every instance may run a
21
- * dispatch loop — the per-WALLET DB leases decide which instance executes a
22
- * given wallet's jobs, so failover is inherent.
23
- */
14
+ // Process-wide wallet-worker singleton, started from the served hook.
15
+ // Every instance may dispatch. Per-wallet DB leases decide who executes.
24
16
  let active = null;
25
17
  let lifecycleQueue = Promise.resolve();
26
- /** Start the worker (idempotent — a no-op when one is already running). */
18
+ /** Starts the worker. A no-op when one is already running. */
27
19
  async function startWalletWorker(deps) {
28
20
  return serializeLifecycle(async () => {
29
21
  if (active?.isRunning()) {
@@ -0,0 +1,35 @@
1
+ import type { CardanoClient, Network } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ import { type WalletJobRow } from './job-store';
4
+ import type { WorkerSigner } from './signers';
5
+ /** Sends stored self-transfer bytes again; a refusal proves nothing, the next check reads the chain. */
6
+ export declare function resendInvalidation(deps: InvalidationDeps, job: WalletJobRow): Promise<void>;
7
+ export type OutputRef = {
8
+ txHash: string;
9
+ outputIndex: number;
10
+ };
11
+ /** confirmed: deep enough, the job's transaction can never land. included: on chain, not deep enough yet.
12
+ * retry: it can no longer land itself. unknown: its inputs are spent and nothing shows by whom.
13
+ * waiting: not seen yet and it may still land, so its bytes are sent again. */
14
+ export type InvalidationState = 'confirmed' | 'included' | 'retry' | 'unknown' | 'waiting';
15
+ export interface InvalidationDeps {
16
+ client: CardanoClient;
17
+ indexer: CardanoIndexer;
18
+ network: Network;
19
+ }
20
+ /** Blocks the self-transfer must be deep before it counts: the depth no rollback reaches. */
21
+ export declare function invalidationDepth(network: Network): number;
22
+ /** An unspent input of the job's transaction that the wallet holds, or null, and the UTxOs the wallet holds. */
23
+ export declare function pickInvalidationInput(deps: InvalidationDeps, address: string, unspentInputs: OutputRef[]): Promise<{
24
+ input: OutputRef | null;
25
+ held: OutputRef[];
26
+ }>;
27
+ /** The self-transfer cannot be funded: the wallet has too little besides inputs it must not spend. */
28
+ export declare class InvalidationUnfundedError extends Error {
29
+ }
30
+ export declare function sendInvalidation(deps: InvalidationDeps, job: WalletJobRow, signer: WorkerSigner, input: OutputRef, around?: {
31
+ held?: OutputRef[];
32
+ keep?: OutputRef[];
33
+ }): Promise<string | null>;
34
+ export declare function checkInvalidation(deps: InvalidationDeps, job: WalletJobRow, seen: Map<string, number>): Promise<InvalidationState>;
35
+ //# sourceMappingURL=invalidation.d.ts.map