@odatano/core 2.0.0-rc.4 → 2.0.0-rc.41

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 (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -18,6 +18,8 @@ class ConfirmationTracker {
18
18
  running = false;
19
19
  polling = false;
20
20
  lastKnownTipHeight = null;
21
+ /** Polling round counter; see TrackedJob.seenRound. */
22
+ round = 0;
21
23
  constructor(deps) {
22
24
  this.deps = deps;
23
25
  }
@@ -69,7 +71,7 @@ class ConfirmationTracker {
69
71
  }
70
72
  const txHashes = new Set(event.txHashes);
71
73
  const found = [...this.pending.values()].filter(j => j.foundHeight == null && txHashes.has(j.txHash));
72
- // Persist + depth-check detached: hook callers (the crawler) must not await us.
74
+ // Detached: hook callers (the crawler) must not await us.
73
75
  void (async () => {
74
76
  for (const job of found) {
75
77
  job.foundSlot = event.slot;
@@ -88,44 +90,48 @@ class ConfirmationTracker {
88
90
  async onReorg(event) {
89
91
  if (!this.running)
90
92
  return;
91
- // The pre-fork tip no longer exists — clamp (or drop) lastKnownTipHeight so
92
- // confirmations are never counted against it. Without this, a tx re-included
93
- // on the new chain would reach "depth" instantly via the stale tip height,
94
- // defeating the confirmation-depth guarantee exactly in the rollback case.
93
+ // Clamp (or drop) the stale pre-fork tip, otherwise a tx re-included on the new
94
+ // chain would reach depth instantly against it.
95
95
  if (event.forkHeight != null) {
96
96
  if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
97
97
  this.lastKnownTipHeight = event.forkHeight;
98
98
  }
99
99
  }
100
100
  else {
101
- this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
101
+ this.lastKnownTipHeight = null; // re-learn from the next block/poll
102
102
  }
103
103
  for (const job of this.pending.values()) {
104
104
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
105
105
  logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
106
- job.foundSlot = null;
107
- job.foundHeight = null;
108
- try {
109
- await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
110
- }
111
- catch (err) {
112
- logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
106
+ await this.forgetInclusion(job);
107
+ }
108
+ }
109
+ }
110
+ /**
111
+ * Inclusion rolled back: back to watching, optionally re-submitting the SAME signed CBOR
112
+ * (never a rebuild — the double-spend guard). "Already known" means the tx survived; success.
113
+ */
114
+ async forgetInclusion(job) {
115
+ job.foundSlot = null;
116
+ job.foundHeight = null;
117
+ job.seenRound = undefined;
118
+ try {
119
+ await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
120
+ }
121
+ catch (err) {
122
+ logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
123
+ }
124
+ if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
125
+ try {
126
+ await this.deps.client.submitTransaction(job.signedTxCbor);
127
+ logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
128
+ }
129
+ catch (err) {
130
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
131
+ logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
113
132
  }
114
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
115
- // SAME signed CBOR only — never a rebuild. "Already known" means the tx
116
- // survived into the new chain's mempool; that is success, not an error.
117
- try {
118
- await this.deps.client.submitTransaction(job.signedTxCbor);
119
- logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
120
- }
121
- catch (err) {
122
- if (err instanceof errors_1.TransactionAlreadySubmittedError) {
123
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
124
- }
125
- else {
126
- logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
127
- }
128
- }
133
+ else {
134
+ logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
129
135
  }
130
136
  }
131
137
  }
@@ -136,9 +142,9 @@ class ConfirmationTracker {
136
142
  if (!this.running || this.polling || this.pending.size === 0)
137
143
  return;
138
144
  this.polling = true;
145
+ this.round++;
139
146
  try {
140
- // Tip first — also serves the depth check for hook-found entries when the
141
- // crawler is off.
147
+ // Tip first — also the depth check for hook-found entries when the crawler is off.
142
148
  try {
143
149
  const tip = await this.deps.client.getLatestBlock();
144
150
  if (tip.height != null) {
@@ -156,13 +162,13 @@ class ConfirmationTracker {
156
162
  const tx = await this.deps.client.getTransaction(job.txHash);
157
163
  job.foundSlot = tx.slot ?? null;
158
164
  job.foundHeight = tx.blockHeight ?? null;
165
+ job.seenRound = this.round;
159
166
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
160
167
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
161
168
  }
162
169
  catch (err) {
163
- // The client's failover wraps per-backend 404s into AllBackendsFailedError,
164
- // so a plain `instanceof NotFoundError` check never fires — the helper also
165
- // accepts "every consulted backend said 404" as proof of absence.
170
+ // Failover wraps per-backend 404s into AllBackendsFailedError; the helper
171
+ // treats "every backend said 404" as proof of absence.
166
172
  if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
167
173
  // Not on-chain yet — check the mempool-TTL timeout.
168
174
  const age = Date.now() - Date.parse(job.submittedAt);
@@ -175,31 +181,66 @@ class ConfirmationTracker {
175
181
  }
176
182
  }
177
183
  }
178
- await this.confirmMature();
184
+ // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
185
+ await this.confirmMature(true);
179
186
  }
180
187
  finally {
181
188
  this.polling = false;
182
189
  }
183
190
  }
184
191
  // ---- Shared -----------------------------------------------------------------
185
- /** Confirm every found job whose depth requirement is met by the known tip. */
186
- async confirmMature() {
192
+ /**
193
+ * Confirm every found job whose depth is met by the known tip. With `revalidate`
194
+ * (polling path) an inclusion not seen in this round is looked up again first.
195
+ */
196
+ async confirmMature(revalidate = false) {
187
197
  const tip = this.lastKnownTipHeight;
188
198
  if (tip == null)
189
199
  return;
190
200
  for (const job of [...this.pending.values()]) {
191
201
  if (job.foundHeight == null)
192
202
  continue;
193
- const confirmations = tip - job.foundHeight + 1;
194
- if (confirmations >= this.deps.options.confirmationDepth) {
195
- await this.finalize(job, 'confirmed');
203
+ if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
204
+ continue;
205
+ if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
206
+ continue;
207
+ await this.finalize(job, 'confirmed');
208
+ }
209
+ }
210
+ /**
211
+ * Is the tx still on-chain and deep enough? A tx that moved blocks is re-anchored at its
212
+ * new height; one that is gone goes back to watching and the tip is re-learned next round.
213
+ */
214
+ async stillIncluded(job, tip) {
215
+ try {
216
+ const tx = await this.deps.client.getTransaction(job.txHash);
217
+ const height = tx.blockHeight ?? null;
218
+ job.seenRound = this.round;
219
+ if (height != null && height !== job.foundHeight) {
220
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
221
+ job.foundHeight = height;
222
+ job.foundSlot = tx.slot ?? null;
223
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
224
+ return tip - height + 1 >= this.deps.options.confirmationDepth;
225
+ }
226
+ return true;
227
+ }
228
+ catch (err) {
229
+ if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
230
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
231
+ this.lastKnownTipHeight = null;
232
+ await this.forgetInclusion(job);
233
+ return false;
196
234
  }
235
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
236
+ return false;
197
237
  }
198
238
  }
199
239
  async finalize(job, outcome, errorCode, err) {
240
+ let transitioned = false;
200
241
  try {
201
242
  await cds_1.default.tx(async (tx) => {
202
- const transitioned = outcome === 'confirmed'
243
+ transitioned = outcome === 'confirmed'
203
244
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
204
245
  : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
205
246
  if (transitioned) {
@@ -209,9 +250,14 @@ class ConfirmationTracker {
209
250
  }
210
251
  catch (persistErr) {
211
252
  logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
212
- return; // keep tracking — the next poll round retries the transition
253
+ return; // keep tracking — the next round retries
213
254
  }
214
255
  this.pending.delete(job.jobId);
256
+ if (!transitioned) {
257
+ // Another actor reached the terminal state first; stats bump and event belong to it.
258
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
259
+ return;
260
+ }
215
261
  logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
216
262
  this.deps.onFinal?.({
217
263
  jobId: job.jobId,
@@ -12,14 +12,8 @@ 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
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.
15
+ * Process-wide wallet-worker singleton, started from the `served` hook and controlled via the
16
+ * worker service. No standby: every instance may dispatch, the per-wallet DB leases decide who executes.
23
17
  */
24
18
  let active = null;
25
19
  let lifecycleQueue = Promise.resolve();
@@ -1,38 +1,20 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  /**
3
- * Wallet-worker job store (v2.0).
3
+ * Persistence for `CardanoWalletJobs` + `CardanoWorkerWallets`. `insertJob` runs on the caller's
4
+ * ambient tx (a detached insert would deadlock on the SQLite write lock); transition helpers run in
5
+ * short fresh txs so the pooled connection is never held across a job execution.
4
6
  *
5
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
6
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
7
- *
8
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
9
- * handler in its own root tx which may already hold the SQLite write lock; a
10
- * detached insert would deadlock against it. The row simply commits together
11
- * with the handler, and the worker's dispatch loop only sees it once visible.
12
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
13
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
14
- * never held across the seconds-to-minutes job execution.
15
- *
16
- * State machine (see WALLET_WORKER_DESIGN.md §5):
7
+ * State machine:
17
8
  * pending → building → submitting → submitted → confirmed
18
9
  * │ │ │ └────→ failed
19
10
  * │ │ └→ submitted (reconciled) | failed (proven absent)
20
11
  * │ └→ pending (transient retry) | failed
21
12
  * └→ cancelled
22
13
  *
23
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
24
- * fee are committed BEFORE the transaction can reach the network, so a process
25
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
26
- * against the chain (or re-submitted verbatim) instead of a `building` row that
27
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
28
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
29
- *
30
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
31
- * a read-back verification — the wallet lease already fences concurrent workers,
32
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
33
- * all reads coerce via `num()` so callers get clean numbers.
14
+ * `submitting` commits the signed CBOR, hash and fee BEFORE the network call and keeps the idempotency
15
+ * key held; transitions are conditional UPDATEs on the expected source status.
34
16
  */
35
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
17
+ /** Per-wallet DB lease TTL. */
36
18
  export declare const WORKER_LEASE_TTL_MS = 15000;
37
19
  export declare const JOB_ERROR_CODES: {
38
20
  readonly PROCESS_RESTART: "PROCESS_RESTART";
@@ -104,30 +86,21 @@ export interface InsertJobResult {
104
86
  deduplicated: boolean;
105
87
  }
106
88
  /**
107
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
108
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
109
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
110
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
111
- * intended work never reached the chain, so re-using the key must be able to
112
- * actually execute it (a cancelled job would otherwise burn its key forever).
113
- *
114
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
115
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
116
- * app instances, or two HANA sessions — can both read "no such job" before either
117
- * commits, and would both insert. The read is only a fast path; the constraint is
118
- * what makes it correct, and the loser of the race returns the winner's job.
119
- *
120
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
121
- * otherwise, so keyless jobs never collide and terminated jobs free their key
122
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
123
- * inside a unique index.
89
+ * Stored dedup claim for an idempotency key, scoped to the submitting principal: an owned key
90
+ * becomes `o:` + hash(owner, key) (fits String(100), never collides with a plain key); an
91
+ * owner-less key stays as-is. The `idempotencyKey` column keeps the raw key.
92
+ */
93
+ export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
94
+ /**
95
+ * Insert a job row on the caller's transaction; an active-or-confirmed row with the same
96
+ * (walletId, kind, dedupKey) is returned instead, `failed`/`cancelled` rows never block a retry.
97
+ * The UNIQUE constraint decides concurrent inserts (the loser returns the winner's job).
124
98
  */
125
99
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
126
100
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
127
101
  /**
128
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
129
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
130
- * avoids adapter-specific NULL/OR predicate quirks.
102
+ * Pending jobs ordered by (priority, createdAt). `notBefore` is filtered in JS to avoid
103
+ * adapter-specific NULL/OR predicate quirks.
131
104
  */
132
105
  export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
133
106
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
@@ -135,31 +108,20 @@ export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJob
135
108
  /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
136
109
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
137
110
  /**
138
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
139
- * executor — its submit outcome is unknown (crash, or a submit call that failed
140
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
141
- * wallet lease is still held are being worked on right now and are left alone.
111
+ * Oldest `submitting` row of a wallet whose lease is expired/unowned: its submit outcome is
112
+ * unknown and needs chain reconciliation. Rows under a held lease are being worked on.
142
113
  */
143
114
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
144
115
  /**
145
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
146
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
147
- * which is what lets a caller re-use the key for a fresh attempt while the row
148
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
149
- *
150
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
151
- * request resolves to it instead of paying again.
116
+ * Free a job's idempotency key by pointing `dedupKey` at its own ID; `idempotencyKey` stays for
117
+ * the audit trail. Not called for `confirmed`: a completed job keeps its key.
152
118
  */
153
119
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
154
120
  /** pending → building. Increments the attempt counter. Returns false when lost. */
155
121
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
156
122
  /**
157
- * building → submitting. Commits the signed transaction, its hash, the unsigned
158
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
159
- * state: whatever happens to the process during `submitTransaction`, the exact
160
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
161
- * key so a caller retry can never turn into a second, differently-built payment.
162
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
123
+ * building → submitting. Commits the signed tx, hash, unsigned CBOR and fee BEFORE the network
124
+ * call, so the exact bytes survive a crash. `submittedAt` is the attempt time, not proof of acceptance.
163
125
  */
164
126
  export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
165
127
  txHash: string;
@@ -167,19 +129,11 @@ export declare function markSubmitting(db: CapTransaction, jobId: string, artifa
167
129
  signedTxCbor: string;
168
130
  fee: string | number | null;
169
131
  }): Promise<boolean>;
170
- /**
171
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
172
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
173
- * is re-asserted, in case the backend canonicalized it.
174
- */
132
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
175
133
  export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
176
134
  /**
177
- * building → pending (transient failure, attempts left). Keeps the error visible
178
- * and defers the next attempt via `notBefore` (exponential backoff).
179
- *
180
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
181
- * mempool, and re-queueing it would rebuild a different transaction from the same
182
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
135
+ * building → pending (transient failure), deferring via `notBefore`. Guarded on `building` only:
136
+ * a `submitting` tx may be in a mempool and a rebuild would double-pay; those rows are reconciled.
183
137
  */
184
138
  export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
185
139
  /** Record where the submitted tx was seen on-chain (not yet at depth). */
@@ -192,9 +146,8 @@ export declare function clearConfirmationPoint(db: CapTransaction, jobId: string
192
146
  /** submitted → confirmed (depth reached). */
193
147
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
194
148
  /**
195
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
196
- * only safe once the chain has been consulted — a failed row releases the
197
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
149
+ * Any active state → failed. Releases the idempotency key, so a `submitting`/`submitted` row
150
+ * may only be failed once the chain has been consulted.
198
151
  */
199
152
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
200
153
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
@@ -208,33 +161,14 @@ export interface RecoveryResult {
208
161
  submittingToReconcile: WalletJobRow[];
209
162
  }
210
163
  /**
211
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
212
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
213
- * lease is held belong to a running executor (possibly on another instance) and
214
- * must not be touched.
215
- *
216
- * Safe by construction: a `building` row is pre-submit by definition — the worker
217
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
218
- * backend, so nothing that is still `building` has ever been sent. Rows that made
219
- * it past that point are `submitting` and are reconciled, never failed here.
164
+ * Fail a wallet's orphaned `building` rows, only when its lease is expired/unowned. A `building`
165
+ * row is pre-submit by definition (the signed CBOR is committed as `submitting` first), so nothing sent is failed.
220
166
  */
221
167
  export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
222
168
  /**
223
- * Boot-time recovery (design §8), by state:
224
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
225
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
226
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
227
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
228
- * chain and re-submits those exact bytes if needed.
229
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
230
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
231
- *
232
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
233
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
234
- * job right now (rolling deploy) — failing it here while its submit succeeds
235
- * would leave a failed row for an on-chain tx, and since failed rows don't block
236
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
237
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
169
+ * Boot-time recovery: `building` → failed PROCESS_RESTART (never sent; only when the wallet lease
170
+ * is expired/unowned, a held lease means another live instance owns it); `submitting` → returned
171
+ * for chain reconciliation, never rebuilt; `submitted` → handed to the confirmation tracker.
238
172
  */
239
173
  export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
240
174
  /** Idempotently register/refresh a configured wallet row (no key material). */
@@ -247,9 +181,8 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
247
181
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
248
182
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
249
183
  /**
250
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
251
- * read-back verification, same shape as the crawler lease). At most one worker
252
- * instance may execute jobs for a wallet at any time.
184
+ * Acquire an expired/unowned per-wallet lease (compare-and-swap + read-back verification).
185
+ * At most one worker instance may execute jobs for a wallet at any time.
253
186
  */
254
187
  export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
255
188
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
@@ -1,23 +1,7 @@
1
1
  /**
2
- * Keeps a per-wallet lease alive for as long as a job execution runs.
3
- *
4
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
5
- * multi-backend build plus an HSM round-trip); a single renewal before the build
6
- * is therefore not enough. Without a heartbeat the lease silently expires
7
- * mid-execution, another instance adopts the wallet, fails this executor's row as
8
- * orphaned and starts the next job — two executors on one wallet, which is exactly
9
- * what the per-wallet lease exists to prevent.
10
- *
11
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
12
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
13
- * wedged stops beating and correctly loses the wallet.
14
- *
15
- * Two failure semantics, on purpose:
16
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
17
- * only a definitive "not yours" marks the lease lost.
18
- * - `fence()` is strict: it is called right before an irreversible step, where
19
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
20
- * free (nothing has been sent yet); guessing wrong is a double spend.
2
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
3
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
4
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
21
5
  */
22
6
  export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
23
7
  export declare class LeaseHeartbeat {
@@ -33,7 +17,7 @@ export declare class LeaseHeartbeat {
33
17
  constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
34
18
  start(): void;
35
19
  stop(): void;
36
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
20
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
37
21
  isLost(): boolean;
38
22
  /** Renew now; false means "do not touch this wallet any further". */
39
23
  fence(): Promise<boolean>;
@@ -8,25 +8,9 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const job_store_1 = require("./job-store");
9
9
  const logger = cds_1.default.log('CardanoWalletWorker');
10
10
  /**
11
- * Keeps a per-wallet lease alive for as long as a job execution runs.
12
- *
13
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
14
- * multi-backend build plus an HSM round-trip); a single renewal before the build
15
- * is therefore not enough. Without a heartbeat the lease silently expires
16
- * mid-execution, another instance adopts the wallet, fails this executor's row as
17
- * orphaned and starts the next job — two executors on one wallet, which is exactly
18
- * what the per-wallet lease exists to prevent.
19
- *
20
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
21
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
22
- * wedged stops beating and correctly loses the wallet.
23
- *
24
- * Two failure semantics, on purpose:
25
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
26
- * only a definitive "not yours" marks the lease lost.
27
- * - `fence()` is strict: it is called right before an irreversible step, where
28
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
29
- * free (nothing has been sent yet); guessing wrong is a double spend.
11
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
12
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
13
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
30
14
  */
31
15
  exports.LEASE_HEARTBEAT_INTERVAL_MS = Math.floor(job_store_1.WORKER_LEASE_TTL_MS / 3);
32
16
  class LeaseHeartbeat {
@@ -56,7 +40,7 @@ class LeaseHeartbeat {
56
40
  this.timer = null;
57
41
  }
58
42
  }
59
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
43
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
60
44
  isLost() {
61
45
  return this.lost;
62
46
  }
@@ -1,16 +1,8 @@
1
1
  import type { WorkerSignerTypeValue } from './job-store';
2
2
  /**
3
- * Wallet-worker signers (v2.0).
4
- *
5
- * `WorkerSigner` is the signer-agnostic surface the worker engine executes against:
6
- * - `hsm` (production): thin wrapper around the already-initialized `HsmSigner`
7
- * (PKCS#11 — keys never leave the module).
8
- * - `software` (dev/test): operator-configured Ed25519 key from an environment
9
- * variable, either plain 64-char hex or AES-256-GCM encrypted
10
- * (`iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY — see srv/utils/crypto.ts).
11
- *
12
- * Keys are NEVER accepted through the OData surface and never persisted; the
13
- * software key lives only in this process's memory.
3
+ * Wallet-worker signers: `hsm` wraps the process-wide HsmSigner (PKCS#11), `software` holds an
4
+ * Ed25519 key from an env var (plain hex or AES-256-GCM `iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY).
5
+ * Keys are never accepted via OData and never persisted.
14
6
  */
15
7
  export interface WorkerSigner {
16
8
  readonly type: WorkerSignerTypeValue;
@@ -25,17 +17,12 @@ export interface WorkerSigner {
25
17
  export interface WorkerWalletConfig {
26
18
  walletId: string;
27
19
  signerType: WorkerSignerTypeValue;
28
- /**
29
- * software only: name of the environment variable holding the Ed25519 signing
30
- * key — plain 64-char hex, or AES-256-GCM `iv:authTag:ciphertext` (base64 parts).
31
- */
20
+ /** software only: env var holding the Ed25519 key — 64-char hex or AES-256-GCM `iv:authTag:ciphertext` (base64). */
32
21
  keyEnv?: string;
33
22
  }
34
23
  /**
35
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
36
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
37
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
38
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
24
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
25
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
39
26
  */
40
27
  export declare function mergeVkeyWitness(unsignedTxCbor: string, publicKeyHex: string, signatureHex: string): string;
41
28
  /** Derive the bech32 enterprise key-hash address for a 28-byte key hash. */
@@ -17,10 +17,8 @@ const errors_1 = require("../../utils/errors");
17
17
  const crypto_2 = require("../../utils/crypto");
18
18
  const logger = cds_1.default.log('CardanoWalletWorker');
19
19
  /**
20
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
21
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
22
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
23
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
20
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
21
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
24
22
  */
25
23
  function mergeVkeyWitness(unsignedTxCbor, publicKeyHex, signatureHex) {
26
24
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
@@ -99,10 +97,7 @@ class SoftwareWorkerSigner {
99
97
  }
100
98
  }
101
99
  exports.SoftwareWorkerSigner = SoftwareWorkerSigner;
102
- /**
103
- * Resolve the software key material for a wallet: plain hex passes through,
104
- * the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY.
105
- */
100
+ /** Plain hex passes through; the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY. */
106
101
  function resolveSoftwareKey(wallet) {
107
102
  if (!wallet.keyEnv) {
108
103
  throw new errors_1.ConfigError(`Wallet worker: wallet "${wallet.walletId}" is signerType=software but has no keyEnv configured`);