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

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 (208) 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 +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -5,9 +5,11 @@ 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");
9
10
  const hooks_1 = require("../crawler/hooks");
10
11
  const job_store_1 = require("./job-store");
12
+ const { UPDATE } = cds_1.default.ql;
11
13
  const logger = cds_1.default.log('CardanoWalletWorker');
12
14
  class ConfirmationTracker {
13
15
  deps;
@@ -71,7 +73,7 @@ class ConfirmationTracker {
71
73
  }
72
74
  const txHashes = new Set(event.txHashes);
73
75
  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.
76
+ // Detached: hook callers (the crawler) must not await us.
75
77
  void (async () => {
76
78
  for (const job of found) {
77
79
  job.foundSlot = event.slot;
@@ -90,32 +92,24 @@ class ConfirmationTracker {
90
92
  async onReorg(event) {
91
93
  if (!this.running)
92
94
  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.
95
+ // Clamp (or drop) the stale pre-fork tip, otherwise a tx re-included on the new
96
+ // chain would reach depth instantly against it.
97
97
  if (event.forkHeight != null) {
98
98
  if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
99
99
  this.lastKnownTipHeight = event.forkHeight;
100
100
  }
101
101
  }
102
102
  else {
103
- this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
103
+ this.lastKnownTipHeight = null; // re-learn from the next block/poll
104
104
  }
105
105
  for (const job of this.pending.values()) {
106
106
  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`);
107
+ logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot}, re-watching`);
108
108
  await this.forgetInclusion(job);
109
109
  }
110
110
  }
111
111
  }
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
- */
112
+ /** Back to watching after a rollback. Re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
119
113
  async forgetInclusion(job) {
120
114
  job.foundSlot = null;
121
115
  job.foundHeight = null;
@@ -133,7 +127,7 @@ class ConfirmationTracker {
133
127
  }
134
128
  catch (err) {
135
129
  if (err instanceof errors_1.TransactionAlreadySubmittedError) {
136
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
130
+ logger.debug(`Job ${job.jobId}: tx already known after rollback, nothing to do`);
137
131
  }
138
132
  else {
139
133
  logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
@@ -149,8 +143,7 @@ class ConfirmationTracker {
149
143
  this.polling = true;
150
144
  this.round++;
151
145
  try {
152
- // Tip first — also serves the depth check for hook-found entries when the
153
- // crawler is off.
146
+ // Tip first. It is also the depth check for hook-found entries when the crawler is off.
154
147
  try {
155
148
  const tip = await this.deps.client.getLatestBlock();
156
149
  if (tip.height != null) {
@@ -173,11 +166,10 @@ class ConfirmationTracker {
173
166
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
174
167
  }
175
168
  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.
169
+ // Failover wraps per-backend 404s into AllBackendsFailedError; the helper
170
+ // treats "every backend said 404" as proof of absence.
179
171
  if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
180
- // Not on-chain yet — check the mempool-TTL timeout.
172
+ // Not on-chain yet. Check the submission timeout.
181
173
  const age = Date.now() - Date.parse(job.submittedAt);
182
174
  if (age > this.deps.options.confirmationTimeoutMs) {
183
175
  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`));
@@ -188,8 +180,7 @@ class ConfirmationTracker {
188
180
  }
189
181
  }
190
182
  }
191
- // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
- // round is re-checked before it counts (see stillIncluded).
183
+ // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
193
184
  await this.confirmMature(true);
194
185
  }
195
186
  finally {
@@ -197,13 +188,7 @@ class ConfirmationTracker {
197
188
  }
198
189
  }
199
190
  // ---- 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
- */
191
+ /** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
207
192
  async confirmMature(revalidate = false) {
208
193
  const tip = this.lastKnownTipHeight;
209
194
  if (tip == null)
@@ -218,20 +203,14 @@ class ConfirmationTracker {
218
203
  await this.finalize(job, 'confirmed');
219
204
  }
220
205
  }
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
- */
206
+ /** 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
207
  async stillIncluded(job, tip) {
229
208
  try {
230
209
  const tx = await this.deps.client.getTransaction(job.txHash);
231
210
  const height = tx.blockHeight ?? null;
232
211
  job.seenRound = this.round;
233
212
  if (height != null && height !== job.foundHeight) {
234
- logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
213
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height}, re-anchoring`);
235
214
  job.foundHeight = height;
236
215
  job.foundSlot = tx.slot ?? null;
237
216
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
@@ -241,7 +220,7 @@ class ConfirmationTracker {
241
220
  }
242
221
  catch (err) {
243
222
  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`);
223
+ 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
224
  this.lastKnownTipHeight = null;
246
225
  await this.forgetInclusion(job);
247
226
  return false;
@@ -256,22 +235,23 @@ class ConfirmationTracker {
256
235
  await cds_1.default.tx(async (tx) => {
257
236
  transitioned = outcome === 'confirmed'
258
237
  ? 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'));
238
+ : await (0, job_store_1.markFailedAfterSend)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
260
239
  if (transitioned) {
261
240
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
241
+ if (outcome === 'confirmed') {
242
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'confirmed' }).where({ txHash: job.txHash, status: 'submitted' }));
243
+ }
262
244
  }
263
245
  });
264
246
  }
265
247
  catch (persistErr) {
266
248
  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
249
+ return; // keep tracking, the next round retries
268
250
  }
269
251
  this.pending.delete(job.jobId);
270
252
  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`);
253
+ // Another actor reached the terminal state first; stats bump and event belong to it.
254
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere, no event from this tracker`);
275
255
  return;
276
256
  }
277
257
  logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
@@ -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()) {
@@ -1,38 +1,5 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
- /**
3
- * Wallet-worker job store (v2.0).
4
- *
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):
17
- * pending → building → submitting → submitted → confirmed
18
- * │ │ │ └────→ failed
19
- * │ │ └→ submitted (reconciled) | failed (proven absent)
20
- * │ └→ pending (transient retry) | failed
21
- * └→ cancelled
22
- *
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.
34
- */
35
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
2
+ /** Per-wallet DB lease TTL. */
36
3
  export declare const WORKER_LEASE_TTL_MS = 15000;
37
4
  export declare const JOB_ERROR_CODES: {
38
5
  readonly PROCESS_RESTART: "PROCESS_RESTART";
@@ -43,7 +10,7 @@ export declare const JOB_ERROR_CODES: {
43
10
  readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
44
11
  };
45
12
  export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
46
- export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'submitSigned';
13
+ export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'payout' | 'submitSigned';
47
14
  export type WorkerSignerTypeValue = 'hsm' | 'software';
48
15
  export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
49
16
  /** Normalized, number-typed view of a job row. */
@@ -78,6 +45,7 @@ export interface WorkerWalletRow {
78
45
  signerType: WorkerSignerTypeValue;
79
46
  address: string | null;
80
47
  publicKeyHash: string | null;
48
+ requiresRole: string | null;
81
49
  enabled: boolean;
82
50
  leaseOwner: string | null;
83
51
  leaseUntil: string | null;
@@ -100,153 +68,70 @@ export interface InsertJobArgs {
100
68
  export interface InsertJobResult {
101
69
  jobId: string;
102
70
  status: WalletJobStatusValue;
103
- /** True when an idempotent retry matched an existing non-failed job. */
71
+ /** True when an idempotent retry matched the job that holds the key. */
104
72
  deduplicated: boolean;
105
73
  }
106
- /** The job that currently owns an idempotency key, or null when it is free. */
107
- /**
108
- * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
109
- * submits. Two agents (two grants, two users) may both use `order-1` on the
110
- * same wallet: each must get its own job, never a "deduplicated" answer that
111
- * hands one the other's job id. A key from an owner-less caller (privileged
112
- * test context) stays as-is; an owned key becomes a hash of owner + key, which
113
- * fits the String(100) column whatever the owner id's length and never collides
114
- * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
115
- */
74
+ /** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
116
75
  export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
117
- /**
118
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
119
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
120
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
121
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
122
- * intended work never reached the chain, so re-using the key must be able to
123
- * actually execute it (a cancelled job would otherwise burn its key forever).
124
- *
125
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
126
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
127
- * app instances, or two HANA sessions — can both read "no such job" before either
128
- * commits, and would both insert. The read is only a fast path; the constraint is
129
- * what makes it correct, and the loser of the race returns the winner's job.
130
- *
131
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
132
- * otherwise, so keyless jobs never collide and terminated jobs free their key
133
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
134
- * inside a unique index.
135
- */
76
+ /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
136
77
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
137
78
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
138
- /**
139
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
140
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
141
- * avoids adapter-specific NULL/OR predicate quirks.
142
- */
143
- export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
79
+ /** A due job's place in the dispatch order, without its payload. */
80
+ export interface DueJobRef {
81
+ ID: string;
82
+ walletId: string;
83
+ priority: number;
84
+ createdAt: string | null;
85
+ }
86
+ /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
87
+ export declare function findNextDueJob(db: CapTransaction, walletId: string, now?: Date): Promise<DueJobRef | null>;
88
+ /** Number of pending jobs, due or not. */
89
+ export declare function countPendingJobs(db: CapTransaction): Promise<number>;
144
90
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
145
91
  export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
146
92
  /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
147
93
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
148
- /**
149
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
150
- * executor — its submit outcome is unknown (crash, or a submit call that failed
151
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
152
- * wallet lease is still held are being worked on right now and are left alone.
153
- */
94
+ /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
154
95
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
155
- /**
156
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
157
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
158
- * which is what lets a caller re-use the key for a fresh attempt while the row
159
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
160
- *
161
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
162
- * request resolves to it instead of paying again.
163
- */
96
+ /** Frees the idempotency key by pointing dedupKey at the job ID. */
164
97
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
165
98
  /** pending → building. Increments the attempt counter. Returns false when lost. */
166
99
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
167
- /**
168
- * building → submitting. Commits the signed transaction, its hash, the unsigned
169
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
170
- * state: whatever happens to the process during `submitTransaction`, the exact
171
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
172
- * key so a caller retry can never turn into a second, differently-built payment.
173
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
174
- */
100
+ /** Stores the signed tx before the network call, so the exact bytes survive a crash. submittedAt is the attempt time. */
175
101
  export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
176
102
  txHash: string;
177
103
  unsignedTxCbor: string | null;
178
104
  signedTxCbor: string;
179
105
  fee: string | number | null;
180
106
  }): Promise<boolean>;
181
- /**
182
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
183
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
184
- * is re-asserted, in case the backend canonicalized it.
185
- */
107
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
186
108
  export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
187
- /**
188
- * building → pending (transient failure, attempts left). Keeps the error visible
189
- * and defers the next attempt via `notBefore` (exponential backoff).
190
- *
191
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
192
- * mempool, and re-queueing it would rebuild a different transaction from the same
193
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
194
- */
109
+ /** Requeues a building job after a transient error. Never a submitting job, since a rebuild could pay twice. */
195
110
  export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
196
111
  /** Record where the submitted tx was seen on-chain (not yet at depth). */
197
112
  export declare function recordConfirmationPoint(db: CapTransaction, jobId: string, point: {
198
113
  slot: number | null;
199
114
  height: number | null;
200
115
  }): Promise<void>;
201
- /** A rollback invalidated the recorded confirmation point — back to watching. */
116
+ /** A rollback invalidated the recorded confirmation point. */
202
117
  export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
203
118
  /** submitted → confirmed (depth reached). */
204
119
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
205
- /**
206
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
207
- * only safe once the chain has been consulted — a failed row releases the
208
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
209
- */
120
+ /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
210
121
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
122
+ export declare function markFailedAfterSend(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
211
123
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
212
124
  export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
213
125
  export interface RecoveryResult {
214
126
  /** `building` rows flipped to failed (never signed+stored, so never submitted). */
215
127
  failedBuilding: number;
216
- /** `submitted` rows to re-enqueue into the confirmation tracker — the chain decides. */
128
+ /** `submitted` rows for the confirmation tracker. The chain decides. */
217
129
  submittedToReconcile: WalletJobRow[];
218
- /** `submitting` rows with an unknown submit outcome — reconciled by the dispatch loop. */
130
+ /** `submitting` rows with an unknown outcome. The dispatch loop reconciles them. */
219
131
  submittingToReconcile: WalletJobRow[];
220
132
  }
221
- /**
222
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
223
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
224
- * lease is held belong to a running executor (possibly on another instance) and
225
- * must not be touched.
226
- *
227
- * Safe by construction: a `building` row is pre-submit by definition — the worker
228
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
229
- * backend, so nothing that is still `building` has ever been sent. Rows that made
230
- * it past that point are `submitting` and are reconciled, never failed here.
231
- */
133
+ /** Fails orphaned building rows of a wallet without a live lease. Such rows were never sent. */
232
134
  export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
233
- /**
234
- * Boot-time recovery (design §8), by state:
235
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
236
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
237
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
238
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
239
- * chain and re-submits those exact bytes if needed.
240
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
241
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
242
- *
243
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
244
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
245
- * job right now (rolling deploy) — failing it here while its submit succeeds
246
- * would leave a failed row for an on-chain tx, and since failed rows don't block
247
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
248
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
249
- */
250
135
  export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
251
136
  /** Idempotently register/refresh a configured wallet row (no key material). */
252
137
  export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
@@ -254,14 +139,11 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
254
139
  signerType: WorkerSignerTypeValue;
255
140
  address: string;
256
141
  publicKeyHash: string;
142
+ requiresRole?: string | null;
257
143
  }): Promise<void>;
258
144
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
259
145
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
260
- /**
261
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
262
- * read-back verification, same shape as the crawler lease). At most one worker
263
- * instance may execute jobs for a wallet at any time.
264
- */
146
+ /** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
265
147
  export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
266
148
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
267
149
  export declare function renewWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;