@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,597 @@
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.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES = exports.WORKER_LEASE_TTL_MS = void 0;
7
+ exports.dedupKeyFor = dedupKeyFor;
8
+ exports.insertJob = insertJob;
9
+ exports.getJobById = getJobById;
10
+ exports.findDueJobs = findDueJobs;
11
+ exports.findSubmittedJobs = findSubmittedJobs;
12
+ exports.walletHasActiveJob = walletHasActiveJob;
13
+ exports.findOrphanedSubmittingJob = findOrphanedSubmittingJob;
14
+ exports.releaseDedupClaim = releaseDedupClaim;
15
+ exports.markBuilding = markBuilding;
16
+ exports.markSubmitting = markSubmitting;
17
+ exports.markSubmitted = markSubmitted;
18
+ exports.requeueForRetry = requeueForRetry;
19
+ exports.recordConfirmationPoint = recordConfirmationPoint;
20
+ exports.clearConfirmationPoint = clearConfirmationPoint;
21
+ exports.markConfirmed = markConfirmed;
22
+ exports.markFailed = markFailed;
23
+ exports.markCancelled = markCancelled;
24
+ exports.failOrphanedBuildingJobs = failOrphanedBuildingJobs;
25
+ exports.recoverInterruptedJobs = recoverInterruptedJobs;
26
+ exports.upsertWalletRegistration = upsertWalletRegistration;
27
+ exports.readWallet = readWallet;
28
+ exports.listWallets = listWallets;
29
+ exports.tryAcquireWalletLease = tryAcquireWalletLease;
30
+ exports.renewWalletLease = renewWalletLease;
31
+ exports.releaseWalletLease = releaseWalletLease;
32
+ exports.bumpWalletStats = bumpWalletStats;
33
+ const cds_1 = __importDefault(require("@sap/cds"));
34
+ const node_crypto_1 = require("node:crypto");
35
+ const cardano_1 = require("#cds-models/odatano/cardano");
36
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
37
+ const logger = cds_1.default.log('CardanoWalletWorker');
38
+ /**
39
+ * Wallet-worker job store (v2.0).
40
+ *
41
+ * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
42
+ * hard-won CAP lessons from NIGHTGATE's background-job runner:
43
+ *
44
+ * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
45
+ * handler in its own root tx which may already hold the SQLite write lock; a
46
+ * detached insert would deadlock against it. The row simply commits together
47
+ * with the handler, and the worker's dispatch loop only sees it once visible.
48
+ * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
49
+ * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
50
+ * never held across the seconds-to-minutes job execution.
51
+ *
52
+ * State machine (see WALLET_WORKER_DESIGN.md §5):
53
+ * pending → building → submitting → submitted → confirmed
54
+ * │ │ │ └────→ failed
55
+ * │ │ └→ submitted (reconciled) | failed (proven absent)
56
+ * │ └→ pending (transient retry) | failed
57
+ * └→ cancelled
58
+ *
59
+ * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
60
+ * fee are committed BEFORE the transaction can reach the network, so a process
61
+ * death anywhere around `submitTransaction` leaves a row that can be reconciled
62
+ * against the chain (or re-submitted verbatim) instead of a `building` row that
63
+ * looks un-submitted. It is a NON-terminal state, so it keeps holding the
64
+ * idempotency key — a caller retry gets the same job back rather than a rebuild.
65
+ *
66
+ * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
67
+ * a read-back verification — the wallet lease already fences concurrent workers,
68
+ * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
69
+ * all reads coerce via `num()` so callers get clean numbers.
70
+ */
71
+ /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
72
+ exports.WORKER_LEASE_TTL_MS = 15_000;
73
+ exports.JOB_ERROR_CODES = {
74
+ PROCESS_RESTART: 'PROCESS_RESTART',
75
+ TX_DROPPED: 'TX_DROPPED',
76
+ RETRIES_EXHAUSTED: 'RETRIES_EXHAUSTED',
77
+ CANCELLED: 'CANCELLED',
78
+ /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
79
+ SUBMIT_REJECTED: 'SUBMIT_REJECTED',
80
+ };
81
+ exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
82
+ function optionalNum(v) {
83
+ if (v === null || v === undefined || v === '')
84
+ return null;
85
+ const n = Number(v);
86
+ return Number.isNaN(n) ? null : n;
87
+ }
88
+ function requiredNum(v, fallback = 0) {
89
+ return optionalNum(v) ?? fallback;
90
+ }
91
+ function timestamp(v) {
92
+ if (v === null || v === undefined || v === '')
93
+ return null;
94
+ if (v instanceof Date)
95
+ return v.toISOString();
96
+ return String(v);
97
+ }
98
+ function toJobRow(row) {
99
+ return {
100
+ ID: String(row.ID),
101
+ walletId: String(row.walletId),
102
+ kind: row.kind,
103
+ status: row.status,
104
+ idempotencyKey: row.idempotencyKey ?? null,
105
+ request: row.request ?? null,
106
+ priority: requiredNum(row.priority, 100),
107
+ notBefore: timestamp(row.notBefore),
108
+ attempt: requiredNum(row.attempt),
109
+ maxAttempts: requiredNum(row.maxAttempts, 3),
110
+ txHash: row.txHash ?? null,
111
+ unsignedTxCbor: row.unsignedTxCbor ?? null,
112
+ signedTxCbor: row.signedTxCbor ?? null,
113
+ fee: optionalNum(row.fee),
114
+ submittedAt: timestamp(row.submittedAt),
115
+ confirmedAt: timestamp(row.confirmedAt),
116
+ confirmedSlot: optionalNum(row.confirmedSlot),
117
+ confirmedHeight: optionalNum(row.confirmedHeight),
118
+ errorCode: row.errorCode ?? null,
119
+ errorMessage: row.errorMessage ?? null,
120
+ createdAt: timestamp(row.createdAt),
121
+ createdBy: row.createdBy ?? null,
122
+ finishedAt: timestamp(row.finishedAt),
123
+ };
124
+ }
125
+ function toWalletRow(row) {
126
+ return {
127
+ walletId: String(row.walletId),
128
+ signerType: row.signerType,
129
+ address: row.address ?? null,
130
+ publicKeyHash: row.publicKeyHash ?? null,
131
+ enabled: row.enabled !== false,
132
+ leaseOwner: row.leaseOwner ?? null,
133
+ leaseUntil: timestamp(row.leaseUntil),
134
+ lastJobAt: timestamp(row.lastJobAt),
135
+ jobsConfirmed: requiredNum(row.jobsConfirmed),
136
+ jobsFailed: requiredNum(row.jobsFailed),
137
+ };
138
+ }
139
+ // Moved to srv/utils/tx-utils.ts (shared with the sign-service's deadlock
140
+ // guard); re-exported here so existing imports keep working.
141
+ var tx_utils_1 = require("../../utils/tx-utils");
142
+ Object.defineProperty(exports, "runWithoutAmbientTx", { enumerable: true, get: function () { return tx_utils_1.runWithoutAmbientTx; } });
143
+ /**
144
+ * Recognize a unique-constraint rejection across the adapters we support —
145
+ * SQLite (`SQLITE_CONSTRAINT_UNIQUE`, "UNIQUE constraint failed") and HANA
146
+ * (code 301, "unique constraint violated").
147
+ *
148
+ * Errors it does not recognize are deliberately NOT treated as duplicates: they
149
+ * propagate, and the caller's retry dedups through the read path. Swallowing an
150
+ * unrelated insert failure as "already exists" would drop the job silently.
151
+ */
152
+ function isUniqueViolation(err) {
153
+ if (!err || typeof err !== 'object')
154
+ return false;
155
+ const { code, errno, message } = err;
156
+ if (String(code ?? '').includes('SQLITE_CONSTRAINT'))
157
+ return true;
158
+ if (String(code ?? '') === '301' || String(errno ?? '') === '301')
159
+ return true;
160
+ const text = String(message ?? '').toLowerCase();
161
+ return text.includes('unique constraint') || text.includes('duplicate key');
162
+ }
163
+ /** The job that currently owns an idempotency key, or null when it is free. */
164
+ /**
165
+ * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
166
+ * submits. Two agents (two grants, two users) may both use `order-1` on the
167
+ * same wallet: each must get its own job, never a "deduplicated" answer that
168
+ * hands one the other's job id. A key from an owner-less caller (privileged
169
+ * test context) stays as-is; an owned key becomes a hash of owner + key, which
170
+ * fits the String(100) column whatever the owner id's length and never collides
171
+ * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
172
+ */
173
+ function dedupKeyFor(owner, idempotencyKey) {
174
+ const scope = owner?.trim() ?? '';
175
+ if (!scope)
176
+ return idempotencyKey;
177
+ return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
178
+ }
179
+ async function readDedupHolder(db, walletId, kind, dedupKey) {
180
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
181
+ return row ? toJobRow(row) : null;
182
+ }
183
+ /**
184
+ * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
185
+ * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
186
+ * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
187
+ * `cancelled` rows do NOT block a retry — both are terminal states in which the
188
+ * intended work never reached the chain, so re-using the key must be able to
189
+ * actually execute it (a cancelled job would otherwise burn its key forever).
190
+ *
191
+ * The deduplication is enforced by the `dedup` UNIQUE constraint on
192
+ * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
193
+ * app instances, or two HANA sessions — can both read "no such job" before either
194
+ * commits, and would both insert. The read is only a fast path; the constraint is
195
+ * what makes it correct, and the loser of the race returns the winner's job.
196
+ *
197
+ * `dedupKey` holds the caller's key while the job owns it and the job's own ID
198
+ * otherwise, so keyless jobs never collide and terminated jobs free their key
199
+ * (see releaseDedupClaim) — without depending on how a database treats NULLs
200
+ * inside a unique index.
201
+ */
202
+ async function insertJob(db, args) {
203
+ const idempotencyKey = args.idempotencyKey ?? null;
204
+ // The claim is per principal: the same key from another owner is another job.
205
+ const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
206
+ if (claim) {
207
+ // Fast path: an owner exists (by construction it is non-terminal). Terminal
208
+ // jobs release their claim, so they never show up here.
209
+ const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
210
+ if (holder) {
211
+ if (holder.status !== 'failed' && holder.status !== 'cancelled') {
212
+ return { jobId: holder.ID, status: holder.status, deduplicated: true };
213
+ }
214
+ // Defensive: a terminal row that still owns the key would block retries
215
+ // forever. Free it and continue with a fresh job.
216
+ logger.warn(`Job ${holder.ID} is ${holder.status} but still held idempotency key "${idempotencyKey}" — releasing it`);
217
+ await releaseDedupClaim(db, holder.ID);
218
+ }
219
+ }
220
+ const jobId = (0, node_crypto_1.randomUUID)();
221
+ const entry = {
222
+ ID: jobId,
223
+ walletId: args.walletId,
224
+ kind: args.kind,
225
+ status: 'pending',
226
+ idempotencyKey,
227
+ // No key → the row's own ID: unique by construction, so keyless jobs never
228
+ // contend for the constraint.
229
+ dedupKey: claim ?? jobId,
230
+ request: args.request,
231
+ priority: args.priority ?? 100,
232
+ notBefore: args.notBefore ?? null,
233
+ attempt: 0,
234
+ maxAttempts: args.maxAttempts ?? 3,
235
+ createdAt: new Date().toISOString(),
236
+ createdBy: args.createdBy ?? null,
237
+ };
238
+ try {
239
+ await db.run(INSERT.into(cardano_1.CardanoWalletJobs).entries(entry));
240
+ }
241
+ catch (err) {
242
+ // Lost the race: another transaction committed the same key first. Its job is
243
+ // the one and only job for this key — hand it back instead of paying twice.
244
+ if (!claim || !isUniqueViolation(err))
245
+ throw err;
246
+ const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
247
+ if (!winner)
248
+ throw err; // constraint fired for some other reason — do not mask it
249
+ logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
250
+ return { jobId: winner.ID, status: winner.status, deduplicated: true };
251
+ }
252
+ return { jobId, status: 'pending', deduplicated: false };
253
+ }
254
+ // ---- Job reads -----------------------------------------------------------------
255
+ async function getJobById(db, jobId) {
256
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ ID: jobId }));
257
+ return row ? toJobRow(row) : null;
258
+ }
259
+ /**
260
+ * All dispatchable jobs: status pending, ordered by (priority, createdAt).
261
+ * `notBefore` gating happens in JS — queue depths are small and the JS filter
262
+ * avoids adapter-specific NULL/OR predicate quirks.
263
+ */
264
+ async function findDueJobs(db, now = new Date()) {
265
+ const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'pending' }).orderBy('priority', 'createdAt'));
266
+ return (rows ?? [])
267
+ .map(toJobRow)
268
+ .filter(j => !j.notBefore || Date.parse(j.notBefore) <= now.getTime());
269
+ }
270
+ /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
271
+ async function findSubmittedJobs(db) {
272
+ const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitted' }));
273
+ return (rows ?? []).map(toJobRow);
274
+ }
275
+ /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
276
+ async function walletHasActiveJob(db, walletId) {
277
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, status: { in: ['building', 'submitting', 'submitted'] } }));
278
+ return !!row;
279
+ }
280
+ /**
281
+ * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
282
+ * executor — its submit outcome is unknown (crash, or a submit call that failed
283
+ * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
284
+ * wallet lease is still held are being worked on right now and are left alone.
285
+ */
286
+ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
287
+ const wallet = await readWallet(db, walletId);
288
+ if (walletLeaseHeld(wallet, now))
289
+ return null;
290
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, status: 'submitting' }).orderBy('createdAt'));
291
+ return row ? toJobRow(row) : null;
292
+ }
293
+ // ---- Guarded transitions ---------------------------------------------------------
294
+ /**
295
+ * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
296
+ * (unique by construction). Called on every terminal-but-unsuccessful transition,
297
+ * which is what lets a caller re-use the key for a fresh attempt while the row
298
+ * itself — including its `idempotencyKey` — stays intact for the audit trail.
299
+ *
300
+ * Not called for `confirmed`: a completed job keeps its key so a late duplicate
301
+ * request resolves to it instead of paying again.
302
+ */
303
+ async function releaseDedupClaim(db, jobId) {
304
+ await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
305
+ }
306
+ /**
307
+ * Move a job from one of `fromStatuses` to `set.status` and report whether THIS
308
+ * call did it. The guard is the conditional UPDATE; the answer is its affected
309
+ * row count (every @cap-js adapter returns a number). A second caller that
310
+ * finds the row already in the target state gets `false`: the transition, the
311
+ * wallet-stats bump and the terminal event belong to the first one only.
312
+ * Two trackers confirming the same job used to count it twice.
313
+ *
314
+ * Fallback for an adapter that returns something that is not a count: read
315
+ * the row back, and accept the target state only if the row was NOT already
316
+ * there before this call (checked with a pre-read in that branch).
317
+ */
318
+ async function guardedTransition(db, jobId, fromStatuses, set) {
319
+ const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
320
+ .set(set)
321
+ .where({ ID: jobId, status: { in: fromStatuses } }));
322
+ const n = typeof affected === 'number' ? affected : Number(affected);
323
+ if (Number.isFinite(n))
324
+ return n > 0;
325
+ // Unknown return shape: the row is in the target state AND that state is not
326
+ // one it could have been in before (the guard excludes it) means we moved it.
327
+ const row = await getJobById(db, jobId);
328
+ return row?.status === set.status && !fromStatuses.includes(set.status);
329
+ }
330
+ /** pending → building. Increments the attempt counter. Returns false when lost. */
331
+ async function markBuilding(db, jobId, attempt) {
332
+ return guardedTransition(db, jobId, ['pending'], { status: 'building', attempt });
333
+ }
334
+ /**
335
+ * building → submitting. Commits the signed transaction, its hash, the unsigned
336
+ * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
337
+ * state: whatever happens to the process during `submitTransaction`, the exact
338
+ * bytes that may be on-chain survive, and the job keeps holding its idempotency
339
+ * key so a caller retry can never turn into a second, differently-built payment.
340
+ * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
341
+ */
342
+ async function markSubmitting(db, jobId, artifacts) {
343
+ return guardedTransition(db, jobId, ['building'], {
344
+ status: 'submitting',
345
+ txHash: artifacts.txHash,
346
+ unsignedTxCbor: artifacts.unsignedTxCbor,
347
+ signedTxCbor: artifacts.signedTxCbor,
348
+ fee: artifacts.fee,
349
+ submittedAt: new Date().toISOString(),
350
+ });
351
+ }
352
+ /**
353
+ * submitting → submitted: a backend accepted the tx (or reconciliation found it
354
+ * on-chain). The artifacts are already durable from markSubmitting; only the hash
355
+ * is re-asserted, in case the backend canonicalized it.
356
+ */
357
+ async function markSubmitted(db, jobId, txHash) {
358
+ return guardedTransition(db, jobId, ['submitting'], { status: 'submitted', txHash });
359
+ }
360
+ /**
361
+ * building → pending (transient failure, attempts left). Keeps the error visible
362
+ * and defers the next attempt via `notBefore` (exponential backoff).
363
+ *
364
+ * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
365
+ * mempool, and re-queueing it would rebuild a different transaction from the same
366
+ * request — the duplicate-payment path. Those rows go to reconciliation instead.
367
+ */
368
+ async function requeueForRetry(db, jobId, err, notBefore) {
369
+ const message = err instanceof Error ? err.message : String(err);
370
+ return guardedTransition(db, jobId, ['building'], {
371
+ status: 'pending',
372
+ errorMessage: message.slice(0, 500),
373
+ ...(notBefore ? { notBefore } : {}),
374
+ });
375
+ }
376
+ /** Record where the submitted tx was seen on-chain (not yet at depth). */
377
+ async function recordConfirmationPoint(db, jobId, point) {
378
+ await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
379
+ .set({ confirmedSlot: point.slot, confirmedHeight: point.height })
380
+ .where({ ID: jobId, status: 'submitted' }));
381
+ }
382
+ /** A rollback invalidated the recorded confirmation point — back to watching. */
383
+ async function clearConfirmationPoint(db, jobId) {
384
+ await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
385
+ .set({ confirmedSlot: null, confirmedHeight: null })
386
+ .where({ ID: jobId, status: 'submitted' }));
387
+ }
388
+ /** submitted → confirmed (depth reached). */
389
+ async function markConfirmed(db, jobId) {
390
+ const now = new Date().toISOString();
391
+ return guardedTransition(db, jobId, ['submitted'], {
392
+ status: 'confirmed',
393
+ confirmedAt: now,
394
+ finishedAt: now,
395
+ errorCode: null,
396
+ errorMessage: null,
397
+ });
398
+ }
399
+ /**
400
+ * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
401
+ * only safe once the chain has been consulted — a failed row releases the
402
+ * idempotency key, so a premature failure invites the caller's retry to pay twice.
403
+ */
404
+ async function markFailed(db, jobId, code, err) {
405
+ const message = err instanceof Error ? err.message : String(err);
406
+ return guardedTransition(db, jobId, ['pending', 'building', 'submitting', 'submitted'], {
407
+ status: 'failed',
408
+ errorCode: code.slice(0, 50),
409
+ errorMessage: message.slice(0, 500),
410
+ finishedAt: new Date().toISOString(),
411
+ dedupKey: jobId, // free the idempotency key for the caller's retry
412
+ });
413
+ }
414
+ /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
415
+ async function markCancelled(db, jobId) {
416
+ return guardedTransition(db, jobId, ['pending'], {
417
+ status: 'cancelled',
418
+ errorCode: exports.JOB_ERROR_CODES.CANCELLED,
419
+ finishedAt: new Date().toISOString(),
420
+ dedupKey: jobId, // free the idempotency key for the caller's retry
421
+ });
422
+ }
423
+ /** True when the wallet's lease is currently held (unexpired) by SOME instance. */
424
+ function walletLeaseHeld(wallet, now) {
425
+ if (!wallet?.leaseOwner || !wallet.leaseUntil)
426
+ return false;
427
+ const deadline = Date.parse(wallet.leaseUntil);
428
+ return Number.isFinite(deadline) && deadline > now.getTime();
429
+ }
430
+ /**
431
+ * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
432
+ * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
433
+ * lease is held belong to a running executor (possibly on another instance) and
434
+ * must not be touched.
435
+ *
436
+ * Safe by construction: a `building` row is pre-submit by definition — the worker
437
+ * transitions to `submitting` (with the signed CBOR) before anything can reach a
438
+ * backend, so nothing that is still `building` has ever been sent. Rows that made
439
+ * it past that point are `submitting` and are reconciled, never failed here.
440
+ */
441
+ async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
442
+ const wallet = await readWallet(db, walletId);
443
+ if (walletLeaseHeld(wallet, now))
444
+ return 0;
445
+ const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID').where({ walletId, status: 'building' }));
446
+ if (!building?.length)
447
+ return 0;
448
+ // Per row rather than one bulk UPDATE: each row releases its idempotency key to
449
+ // its OWN ID (see releaseDedupClaim), which a single statement cannot express
450
+ // portably. Orphan sets are one row in practice — a wallet runs one job at a time.
451
+ for (const { ID } of building) {
452
+ await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
453
+ .set({
454
+ status: 'failed',
455
+ errorCode: exports.JOB_ERROR_CODES.PROCESS_RESTART,
456
+ errorMessage: 'Job was interrupted before submission (executor died or lost its wallet lease).',
457
+ finishedAt: now.toISOString(),
458
+ dedupKey: ID,
459
+ })
460
+ .where({ ID, status: 'building' }));
461
+ }
462
+ logger.warn(`Wallet ${walletId}: failed ${building.length} orphaned building job(s) as failed:PROCESS_RESTART`);
463
+ return building.length;
464
+ }
465
+ /**
466
+ * Boot-time recovery (design §8), by state:
467
+ * - `building` — nothing was signed and stored yet, so nothing was submitted:
468
+ * fail with PROCESS_RESTART (caller retries via idempotencyKey).
469
+ * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
470
+ * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
471
+ * chain and re-submits those exact bytes if needed.
472
+ * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
473
+ * decides (found → confirm; absent past the timeout → TX_DROPPED).
474
+ *
475
+ * Multi-instance safety: a `building` row is only failed when its wallet's lease
476
+ * is expired/unowned. A held lease means ANOTHER live instance is executing that
477
+ * job right now (rolling deploy) — failing it here while its submit succeeds
478
+ * would leave a failed row for an on-chain tx, and since failed rows don't block
479
+ * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
480
+ * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
481
+ */
482
+ async function recoverInterruptedJobs(db, now = new Date()) {
483
+ const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID', 'walletId').where({ status: 'building' }));
484
+ let failedBuilding = 0;
485
+ const skippedWallets = [];
486
+ for (const walletId of new Set((building ?? []).map((row) => row.walletId))) {
487
+ const failed = await failOrphanedBuildingJobs(db, walletId, now);
488
+ if (failed > 0)
489
+ failedBuilding += failed;
490
+ else
491
+ skippedWallets.push(walletId);
492
+ }
493
+ if (skippedWallets.length) {
494
+ logger.info(`Recovery skipped building job(s) for wallet(s) ${skippedWallets.join(', ')} — lease still held by a live instance`);
495
+ }
496
+ const submitted = await findSubmittedJobs(db);
497
+ if (submitted.length) {
498
+ logger.info(`${submitted.length} submitted job(s) pending chain reconciliation after restart`);
499
+ }
500
+ const submitting = (await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitting' })) ?? []).map(toJobRow);
501
+ if (submitting.length) {
502
+ logger.warn(`${submitting.length} job(s) interrupted around submit — the dispatch loop will reconcile them against the chain (never a rebuild)`);
503
+ }
504
+ return { failedBuilding, submittedToReconcile: submitted, submittingToReconcile: submitting };
505
+ }
506
+ // ---- Worker wallets --------------------------------------------------------------
507
+ /** Idempotently register/refresh a configured wallet row (no key material). */
508
+ async function upsertWalletRegistration(db, wallet) {
509
+ const existing = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId: wallet.walletId }));
510
+ if (existing) {
511
+ await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({
512
+ signerType: wallet.signerType,
513
+ address: wallet.address,
514
+ publicKeyHash: wallet.publicKeyHash,
515
+ }).where({ walletId: wallet.walletId }));
516
+ return;
517
+ }
518
+ await db.run(INSERT.into(cardano_1.CardanoWorkerWallets).entries({
519
+ walletId: wallet.walletId,
520
+ signerType: wallet.signerType,
521
+ address: wallet.address,
522
+ publicKeyHash: wallet.publicKeyHash,
523
+ enabled: true,
524
+ jobsConfirmed: 0,
525
+ jobsFailed: 0,
526
+ }));
527
+ }
528
+ async function readWallet(db, walletId) {
529
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId }));
530
+ return row ? toWalletRow(row) : null;
531
+ }
532
+ async function listWallets(db) {
533
+ const rows = await db.run(SELECT.from(cardano_1.CardanoWorkerWallets));
534
+ return (rows ?? []).map(toWalletRow);
535
+ }
536
+ function leaseDeadlineReached(wallet, owner, expectedMs) {
537
+ if (!wallet || wallet.leaseOwner !== owner || !wallet.leaseUntil)
538
+ return false;
539
+ const actualMs = Date.parse(wallet.leaseUntil);
540
+ // One second tolerance for adapter timestamp normalization (crawler lease pattern).
541
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
542
+ }
543
+ /**
544
+ * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
545
+ * read-back verification, same shape as the crawler lease). At most one worker
546
+ * instance may execute jobs for a wallet at any time.
547
+ */
548
+ async function tryAcquireWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
549
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId }));
550
+ if (!raw)
551
+ return false;
552
+ const current = toWalletRow(raw);
553
+ if (!current.enabled)
554
+ return false;
555
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
556
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
557
+ return false;
558
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
559
+ // CAS on the observed owner only — timestamp equality is adapter-fragile and
560
+ // could make an expired lease permanently untakeable (see tryAcquireCrawlerLease).
561
+ await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: owner, leaseUntil }).where({
562
+ walletId,
563
+ leaseOwner: raw.leaseOwner ?? null,
564
+ }));
565
+ const verified = await readWallet(db, walletId);
566
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
567
+ }
568
+ /** Renew/fence the caller's lease. Call before every job-advancing write. */
569
+ async function renewWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
570
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
571
+ await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseUntil }).where({
572
+ walletId,
573
+ leaseOwner: owner,
574
+ }));
575
+ const verified = await readWallet(db, walletId);
576
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
577
+ }
578
+ /** Release only the caller's lease; a stale process can never clear a successor. */
579
+ async function releaseWalletLease(db, walletId, owner) {
580
+ await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: null, leaseUntil: null }).where({
581
+ walletId,
582
+ leaseOwner: owner,
583
+ }));
584
+ }
585
+ /** Bump rolling per-wallet stats on a terminal job state. */
586
+ async function bumpWalletStats(db, walletId, outcome) {
587
+ const wallet = await readWallet(db, walletId);
588
+ if (!wallet)
589
+ return;
590
+ await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({
591
+ lastJobAt: new Date().toISOString(),
592
+ ...(outcome === 'confirmed'
593
+ ? { jobsConfirmed: wallet.jobsConfirmed + 1 }
594
+ : { jobsFailed: wallet.jobsFailed + 1 }),
595
+ }).where({ walletId }));
596
+ }
597
+ //# sourceMappingURL=job-store.js.map
@@ -0,0 +1,43 @@
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.
21
+ */
22
+ export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
23
+ export declare class LeaseHeartbeat {
24
+ private readonly renew;
25
+ private readonly label;
26
+ private readonly intervalMs;
27
+ private timer;
28
+ private lost;
29
+ /**
30
+ * @param renew renews the lease and reports whether it is (still) ours
31
+ * @param label what the lease covers, for log messages
32
+ */
33
+ constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
34
+ start(): void;
35
+ stop(): void;
36
+ /** True once a renewal proved the lease is no longer ours — abort the execution. */
37
+ isLost(): boolean;
38
+ /** Renew now; false means "do not touch this wallet any further". */
39
+ fence(): Promise<boolean>;
40
+ private beat;
41
+ private markLost;
42
+ }
43
+ //# sourceMappingURL=lease-heartbeat.d.ts.map