@odatano/core 1.11.0 → 2.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,290 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ConfirmationTracker = void 0;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const errors_1 = require("../../utils/errors");
9
+ const hooks_1 = require("../crawler/hooks");
10
+ const job_store_1 = require("./job-store");
11
+ const logger = cds_1.default.log('CardanoWalletWorker');
12
+ class ConfirmationTracker {
13
+ deps;
14
+ pending = new Map();
15
+ blockListener = (event) => this.onBlockIndexed(event);
16
+ reorgListener = (event) => { void this.onReorg(event); };
17
+ pollTimer = null;
18
+ running = false;
19
+ polling = false;
20
+ lastKnownTipHeight = null;
21
+ /** Polling round counter; see TrackedJob.seenRound. */
22
+ round = 0;
23
+ constructor(deps) {
24
+ this.deps = deps;
25
+ }
26
+ start() {
27
+ if (this.running)
28
+ return;
29
+ this.running = true;
30
+ (0, hooks_1.registerBlockIndexedListener)(this.blockListener);
31
+ (0, hooks_1.registerReorgListener)(this.reorgListener);
32
+ this.pollTimer = setInterval(() => { void this.pollOnce(); }, this.deps.options.pollIntervalMs);
33
+ this.pollTimer.unref?.();
34
+ }
35
+ stop() {
36
+ this.running = false;
37
+ (0, hooks_1.unregisterBlockIndexedListener)(this.blockListener);
38
+ (0, hooks_1.unregisterReorgListener)(this.reorgListener);
39
+ if (this.pollTimer) {
40
+ clearInterval(this.pollTimer);
41
+ this.pollTimer = null;
42
+ }
43
+ this.pending.clear();
44
+ }
45
+ /** Number of jobs currently awaiting confirmation. */
46
+ size() {
47
+ return this.pending.size;
48
+ }
49
+ /** Register a submitted job for confirmation watching. Idempotent per jobId. */
50
+ track(job) {
51
+ if (this.pending.has(job.jobId))
52
+ return;
53
+ this.pending.set(job.jobId, {
54
+ jobId: job.jobId,
55
+ walletId: job.walletId,
56
+ kind: job.kind ?? null,
57
+ txHash: job.txHash,
58
+ signedTxCbor: job.signedTxCbor,
59
+ submittedAt: job.submittedAt ?? new Date().toISOString(),
60
+ foundSlot: job.confirmedSlot ?? null,
61
+ foundHeight: job.confirmedHeight ?? null,
62
+ });
63
+ }
64
+ // ---- Crawler hook path -----------------------------------------------------
65
+ onBlockIndexed(event) {
66
+ if (!this.running || this.pending.size === 0)
67
+ return;
68
+ const tipHeight = event.tipHeight ?? event.height;
69
+ if (tipHeight != null) {
70
+ this.lastKnownTipHeight = Math.max(this.lastKnownTipHeight ?? 0, tipHeight);
71
+ }
72
+ const txHashes = new Set(event.txHashes);
73
+ 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.
75
+ void (async () => {
76
+ for (const job of found) {
77
+ job.foundSlot = event.slot;
78
+ job.foundHeight = event.height;
79
+ try {
80
+ await cds_1.default.tx((tx) => (0, job_store_1.recordConfirmationPoint)(tx, job.jobId, { slot: event.slot, height: event.height }));
81
+ logger.info(`Job ${job.jobId}: tx ${job.txHash} included in block ${event.hash} (height ${event.height})`);
82
+ }
83
+ catch (err) {
84
+ logger.warn(`Job ${job.jobId}: failed to persist confirmation point (will retry via polling):`, err);
85
+ }
86
+ }
87
+ await this.confirmMature();
88
+ })();
89
+ }
90
+ async onReorg(event) {
91
+ if (!this.running)
92
+ 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.
97
+ if (event.forkHeight != null) {
98
+ if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
99
+ this.lastKnownTipHeight = event.forkHeight;
100
+ }
101
+ }
102
+ else {
103
+ this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
104
+ }
105
+ for (const job of this.pending.values()) {
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`);
108
+ await this.forgetInclusion(job);
109
+ }
110
+ }
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
+ */
119
+ async forgetInclusion(job) {
120
+ job.foundSlot = null;
121
+ job.foundHeight = null;
122
+ job.seenRound = undefined;
123
+ try {
124
+ await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
125
+ }
126
+ catch (err) {
127
+ logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
128
+ }
129
+ if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
130
+ try {
131
+ await this.deps.client.submitTransaction(job.signedTxCbor);
132
+ logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
133
+ }
134
+ catch (err) {
135
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
136
+ logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
137
+ }
138
+ else {
139
+ logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
140
+ }
141
+ }
142
+ }
143
+ }
144
+ // ---- Polling path ------------------------------------------------------------
145
+ /** One polling round. Public for tests; guarded against overlapping rounds. */
146
+ async pollOnce() {
147
+ if (!this.running || this.polling || this.pending.size === 0)
148
+ return;
149
+ this.polling = true;
150
+ this.round++;
151
+ try {
152
+ // Tip first — also serves the depth check for hook-found entries when the
153
+ // crawler is off.
154
+ try {
155
+ const tip = await this.deps.client.getLatestBlock();
156
+ if (tip.height != null) {
157
+ this.lastKnownTipHeight = Math.max(this.lastKnownTipHeight ?? 0, tip.height);
158
+ }
159
+ }
160
+ catch (err) {
161
+ logger.debug('Confirmation polling: tip lookup failed (skipping round):', err);
162
+ return;
163
+ }
164
+ for (const job of [...this.pending.values()]) {
165
+ if (job.foundHeight != null)
166
+ continue;
167
+ try {
168
+ const tx = await this.deps.client.getTransaction(job.txHash);
169
+ job.foundSlot = tx.slot ?? null;
170
+ job.foundHeight = tx.blockHeight ?? null;
171
+ job.seenRound = this.round;
172
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
173
+ logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
174
+ }
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
+ }
189
+ }
190
+ }
191
+ // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
+ // round is re-checked before it counts (see stillIncluded).
193
+ await this.confirmMature(true);
194
+ }
195
+ finally {
196
+ this.polling = false;
197
+ }
198
+ }
199
+ // ---- 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
+ */
207
+ async confirmMature(revalidate = false) {
208
+ const tip = this.lastKnownTipHeight;
209
+ if (tip == null)
210
+ return;
211
+ for (const job of [...this.pending.values()]) {
212
+ if (job.foundHeight == null)
213
+ continue;
214
+ if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
215
+ continue;
216
+ if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
217
+ continue;
218
+ await this.finalize(job, 'confirmed');
219
+ }
220
+ }
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
+ */
228
+ async stillIncluded(job, tip) {
229
+ try {
230
+ const tx = await this.deps.client.getTransaction(job.txHash);
231
+ const height = tx.blockHeight ?? null;
232
+ job.seenRound = this.round;
233
+ if (height != null && height !== job.foundHeight) {
234
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
235
+ job.foundHeight = height;
236
+ job.foundSlot = tx.slot ?? null;
237
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
238
+ return tip - height + 1 >= this.deps.options.confirmationDepth;
239
+ }
240
+ return true;
241
+ }
242
+ catch (err) {
243
+ 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`);
245
+ this.lastKnownTipHeight = null;
246
+ await this.forgetInclusion(job);
247
+ return false;
248
+ }
249
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
250
+ return false;
251
+ }
252
+ }
253
+ async finalize(job, outcome, errorCode, err) {
254
+ let transitioned = false;
255
+ try {
256
+ await cds_1.default.tx(async (tx) => {
257
+ transitioned = outcome === 'confirmed'
258
+ ? 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'));
260
+ if (transitioned) {
261
+ await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
262
+ }
263
+ });
264
+ }
265
+ catch (persistErr) {
266
+ 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
268
+ }
269
+ this.pending.delete(job.jobId);
270
+ 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`);
275
+ return;
276
+ }
277
+ logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
278
+ this.deps.onFinal?.({
279
+ jobId: job.jobId,
280
+ walletId: job.walletId,
281
+ outcome,
282
+ kind: job.kind,
283
+ txHash: job.txHash,
284
+ errorCode,
285
+ errorMessage: err instanceof Error ? err.message : err != null ? String(err) : undefined,
286
+ });
287
+ }
288
+ }
289
+ exports.ConfirmationTracker = ConfirmationTracker;
290
+ //# sourceMappingURL=confirmation-tracker.js.map
@@ -0,0 +1,14 @@
1
+ import { CardanoWalletWorker, type WalletWorkerConfig, type WalletWorkerDeps } from './wallet-worker';
2
+ export type StartWalletWorkerDeps = Omit<WalletWorkerDeps, 'instanceId'> & {
3
+ instanceId?: string;
4
+ };
5
+ export type { WalletWorkerConfig };
6
+ /** Start the worker (idempotent — a no-op when one is already running). */
7
+ export declare function startWalletWorker(deps: StartWalletWorkerDeps): Promise<void>;
8
+ /** Stop the local worker (in-flight execution steps are awaited). */
9
+ export declare function stopWalletWorker(): Promise<void>;
10
+ /** Whether a worker is currently running in this process. */
11
+ export declare function isWalletWorkerRunning(): boolean;
12
+ /** The active worker instance, or null. */
13
+ export declare function getWalletWorker(): CardanoWalletWorker | null;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.startWalletWorker = startWalletWorker;
7
+ exports.stopWalletWorker = stopWalletWorker;
8
+ exports.isWalletWorkerRunning = isWalletWorkerRunning;
9
+ exports.getWalletWorker = getWalletWorker;
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ const node_crypto_1 = require("node:crypto");
12
+ const wallet_worker_1 = require("./wallet-worker");
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
+ */
24
+ let active = null;
25
+ let lifecycleQueue = Promise.resolve();
26
+ /** Start the worker (idempotent — a no-op when one is already running). */
27
+ async function startWalletWorker(deps) {
28
+ return serializeLifecycle(async () => {
29
+ if (active?.isRunning()) {
30
+ logger.debug('startWalletWorker: already running');
31
+ return;
32
+ }
33
+ if (active) {
34
+ const previous = active;
35
+ await previous.stop();
36
+ if (active === previous)
37
+ active = null;
38
+ }
39
+ const candidate = new wallet_worker_1.CardanoWalletWorker({
40
+ ...deps,
41
+ instanceId: deps.instanceId ?? `${process.pid}:${(0, node_crypto_1.randomUUID)()}`,
42
+ });
43
+ active = candidate;
44
+ try {
45
+ await candidate.start();
46
+ }
47
+ catch (err) {
48
+ if (active === candidate)
49
+ active = null;
50
+ throw err;
51
+ }
52
+ if (!candidate.isRunning() && active === candidate)
53
+ active = null;
54
+ });
55
+ }
56
+ /** Stop the local worker (in-flight execution steps are awaited). */
57
+ async function stopWalletWorker() {
58
+ return serializeLifecycle(async () => {
59
+ const worker = active;
60
+ if (!worker)
61
+ return;
62
+ await worker.stop();
63
+ if (active === worker)
64
+ active = null;
65
+ });
66
+ }
67
+ /** Whether a worker is currently running in this process. */
68
+ function isWalletWorkerRunning() {
69
+ return active?.isRunning() ?? false;
70
+ }
71
+ /** The active worker instance, or null. */
72
+ function getWalletWorker() {
73
+ return active;
74
+ }
75
+ function serializeLifecycle(operation) {
76
+ const result = lifecycleQueue.then(operation, operation);
77
+ lifecycleQueue = result.catch(() => undefined);
78
+ return result;
79
+ }
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,272 @@
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. */
36
+ export declare const WORKER_LEASE_TTL_MS = 15000;
37
+ export declare const JOB_ERROR_CODES: {
38
+ readonly PROCESS_RESTART: "PROCESS_RESTART";
39
+ readonly TX_DROPPED: "TX_DROPPED";
40
+ readonly RETRIES_EXHAUSTED: "RETRIES_EXHAUSTED";
41
+ readonly CANCELLED: "CANCELLED";
42
+ /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
43
+ readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
44
+ };
45
+ export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
46
+ export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'submitSigned';
47
+ export type WorkerSignerTypeValue = 'hsm' | 'software';
48
+ export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
49
+ /** Normalized, number-typed view of a job row. */
50
+ export interface WalletJobRow {
51
+ ID: string;
52
+ walletId: string;
53
+ kind: WalletJobKindValue;
54
+ status: WalletJobStatusValue;
55
+ idempotencyKey: string | null;
56
+ request: string | null;
57
+ priority: number;
58
+ notBefore: string | null;
59
+ attempt: number;
60
+ maxAttempts: number;
61
+ txHash: string | null;
62
+ unsignedTxCbor: string | null;
63
+ signedTxCbor: string | null;
64
+ fee: number | null;
65
+ submittedAt: string | null;
66
+ confirmedAt: string | null;
67
+ confirmedSlot: number | null;
68
+ confirmedHeight: number | null;
69
+ errorCode: string | null;
70
+ errorMessage: string | null;
71
+ createdAt: string | null;
72
+ createdBy: string | null;
73
+ finishedAt: string | null;
74
+ }
75
+ /** Normalized view of a worker-wallet row. */
76
+ export interface WorkerWalletRow {
77
+ walletId: string;
78
+ signerType: WorkerSignerTypeValue;
79
+ address: string | null;
80
+ publicKeyHash: string | null;
81
+ enabled: boolean;
82
+ leaseOwner: string | null;
83
+ leaseUntil: string | null;
84
+ lastJobAt: string | null;
85
+ jobsConfirmed: number;
86
+ jobsFailed: number;
87
+ }
88
+ export { runWithoutAmbientTx } from '../../utils/tx-utils';
89
+ export interface InsertJobArgs {
90
+ walletId: string;
91
+ kind: WalletJobKindValue;
92
+ /** Build-action payload as a JSON string (already validated + size-limited). */
93
+ request: string;
94
+ idempotencyKey?: string | null;
95
+ priority?: number;
96
+ notBefore?: string | null;
97
+ maxAttempts?: number;
98
+ createdBy?: string | null;
99
+ }
100
+ export interface InsertJobResult {
101
+ jobId: string;
102
+ status: WalletJobStatusValue;
103
+ /** True when an idempotent retry matched an existing non-failed job. */
104
+ deduplicated: boolean;
105
+ }
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
+ */
116
+ 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
+ */
136
+ export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
137
+ 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[]>;
144
+ /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
145
+ export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
146
+ /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
147
+ 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
+ */
154
+ 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
+ */
164
+ export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
165
+ /** pending → building. Increments the attempt counter. Returns false when lost. */
166
+ 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
+ */
175
+ export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
176
+ txHash: string;
177
+ unsignedTxCbor: string | null;
178
+ signedTxCbor: string;
179
+ fee: string | number | null;
180
+ }): 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
+ */
186
+ 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
+ */
195
+ export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
196
+ /** Record where the submitted tx was seen on-chain (not yet at depth). */
197
+ export declare function recordConfirmationPoint(db: CapTransaction, jobId: string, point: {
198
+ slot: number | null;
199
+ height: number | null;
200
+ }): Promise<void>;
201
+ /** A rollback invalidated the recorded confirmation point — back to watching. */
202
+ export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
203
+ /** submitted → confirmed (depth reached). */
204
+ 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
+ */
210
+ export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
211
+ /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
212
+ export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
213
+ export interface RecoveryResult {
214
+ /** `building` rows flipped to failed (never signed+stored, so never submitted). */
215
+ failedBuilding: number;
216
+ /** `submitted` rows to re-enqueue into the confirmation tracker — the chain decides. */
217
+ submittedToReconcile: WalletJobRow[];
218
+ /** `submitting` rows with an unknown submit outcome — reconciled by the dispatch loop. */
219
+ submittingToReconcile: WalletJobRow[];
220
+ }
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
+ */
232
+ 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
+ export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
251
+ /** Idempotently register/refresh a configured wallet row (no key material). */
252
+ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
253
+ walletId: string;
254
+ signerType: WorkerSignerTypeValue;
255
+ address: string;
256
+ publicKeyHash: string;
257
+ }): Promise<void>;
258
+ export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
259
+ 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
+ */
265
+ export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
266
+ /** Renew/fence the caller's lease. Call before every job-advancing write. */
267
+ export declare function renewWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
268
+ /** Release only the caller's lease; a stale process can never clear a successor. */
269
+ export declare function releaseWalletLease(db: CapTransaction, walletId: string, owner: string): Promise<void>;
270
+ /** Bump rolling per-wallet stats on a terminal job state. */
271
+ export declare function bumpWalletStats(db: CapTransaction, walletId: string, outcome: 'confirmed' | 'failed'): Promise<void>;
272
+ //# sourceMappingURL=job-store.d.ts.map