@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21

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 (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -1,38 +1,20 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  /**
3
- * Wallet-worker job store (v2.0).
3
+ * Persistence for `CardanoWalletJobs` + `CardanoWorkerWallets`. `insertJob` runs on the caller's
4
+ * ambient tx (a detached insert would deadlock on the SQLite write lock); transition helpers run in
5
+ * short fresh txs so the pooled connection is never held across a job execution.
4
6
  *
5
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
6
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
7
- *
8
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
9
- * handler in its own root tx which may already hold the SQLite write lock; a
10
- * detached insert would deadlock against it. The row simply commits together
11
- * with the handler, and the worker's dispatch loop only sees it once visible.
12
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
13
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
14
- * never held across the seconds-to-minutes job execution.
15
- *
16
- * State machine (see WALLET_WORKER_DESIGN.md §5):
7
+ * State machine:
17
8
  * pending → building → submitting → submitted → confirmed
18
9
  * │ │ │ └────→ failed
19
10
  * │ │ └→ submitted (reconciled) | failed (proven absent)
20
11
  * │ └→ pending (transient retry) | failed
21
12
  * └→ cancelled
22
13
  *
23
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
24
- * fee are committed BEFORE the transaction can reach the network, so a process
25
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
26
- * against the chain (or re-submitted verbatim) instead of a `building` row that
27
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
28
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
29
- *
30
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
31
- * a read-back verification — the wallet lease already fences concurrent workers,
32
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
33
- * all reads coerce via `num()` so callers get clean numbers.
14
+ * `submitting` commits the signed CBOR, hash and fee BEFORE the network call and keeps the idempotency
15
+ * key held; transitions are conditional UPDATEs on the expected source status.
34
16
  */
35
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
17
+ /** Per-wallet DB lease TTL. */
36
18
  export declare const WORKER_LEASE_TTL_MS = 15000;
37
19
  export declare const JOB_ERROR_CODES: {
38
20
  readonly PROCESS_RESTART: "PROCESS_RESTART";
@@ -104,30 +86,21 @@ export interface InsertJobResult {
104
86
  deduplicated: boolean;
105
87
  }
106
88
  /**
107
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
108
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
109
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
110
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
111
- * intended work never reached the chain, so re-using the key must be able to
112
- * actually execute it (a cancelled job would otherwise burn its key forever).
113
- *
114
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
115
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
116
- * app instances, or two HANA sessions — can both read "no such job" before either
117
- * commits, and would both insert. The read is only a fast path; the constraint is
118
- * what makes it correct, and the loser of the race returns the winner's job.
119
- *
120
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
121
- * otherwise, so keyless jobs never collide and terminated jobs free their key
122
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
123
- * inside a unique index.
89
+ * Stored dedup claim for an idempotency key, scoped to the submitting principal: an owned key
90
+ * becomes `o:` + hash(owner, key) (fits String(100), never collides with a plain key); an
91
+ * owner-less key stays as-is. The `idempotencyKey` column keeps the raw key.
92
+ */
93
+ export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
94
+ /**
95
+ * Insert a job row on the caller's transaction; an active-or-confirmed row with the same
96
+ * (walletId, kind, dedupKey) is returned instead, `failed`/`cancelled` rows never block a retry.
97
+ * The UNIQUE constraint decides concurrent inserts (the loser returns the winner's job).
124
98
  */
125
99
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
126
100
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
127
101
  /**
128
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
129
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
130
- * avoids adapter-specific NULL/OR predicate quirks.
102
+ * Pending jobs ordered by (priority, createdAt). `notBefore` is filtered in JS to avoid
103
+ * adapter-specific NULL/OR predicate quirks.
131
104
  */
132
105
  export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
133
106
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
@@ -135,31 +108,20 @@ export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJob
135
108
  /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
136
109
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
137
110
  /**
138
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
139
- * executor — its submit outcome is unknown (crash, or a submit call that failed
140
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
141
- * wallet lease is still held are being worked on right now and are left alone.
111
+ * Oldest `submitting` row of a wallet whose lease is expired/unowned: its submit outcome is
112
+ * unknown and needs chain reconciliation. Rows under a held lease are being worked on.
142
113
  */
143
114
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
144
115
  /**
145
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
146
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
147
- * which is what lets a caller re-use the key for a fresh attempt while the row
148
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
149
- *
150
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
151
- * request resolves to it instead of paying again.
116
+ * Free a job's idempotency key by pointing `dedupKey` at its own ID; `idempotencyKey` stays for
117
+ * the audit trail. Not called for `confirmed`: a completed job keeps its key.
152
118
  */
153
119
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
154
120
  /** pending → building. Increments the attempt counter. Returns false when lost. */
155
121
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
156
122
  /**
157
- * building → submitting. Commits the signed transaction, its hash, the unsigned
158
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
159
- * state: whatever happens to the process during `submitTransaction`, the exact
160
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
161
- * key so a caller retry can never turn into a second, differently-built payment.
162
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
123
+ * building → submitting. Commits the signed tx, hash, unsigned CBOR and fee BEFORE the network
124
+ * call, so the exact bytes survive a crash. `submittedAt` is the attempt time, not proof of acceptance.
163
125
  */
164
126
  export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
165
127
  txHash: string;
@@ -167,19 +129,11 @@ export declare function markSubmitting(db: CapTransaction, jobId: string, artifa
167
129
  signedTxCbor: string;
168
130
  fee: string | number | null;
169
131
  }): Promise<boolean>;
170
- /**
171
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
172
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
173
- * is re-asserted, in case the backend canonicalized it.
174
- */
132
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
175
133
  export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
176
134
  /**
177
- * building → pending (transient failure, attempts left). Keeps the error visible
178
- * and defers the next attempt via `notBefore` (exponential backoff).
179
- *
180
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
181
- * mempool, and re-queueing it would rebuild a different transaction from the same
182
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
135
+ * building → pending (transient failure), deferring via `notBefore`. Guarded on `building` only:
136
+ * a `submitting` tx may be in a mempool and a rebuild would double-pay; those rows are reconciled.
183
137
  */
184
138
  export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
185
139
  /** Record where the submitted tx was seen on-chain (not yet at depth). */
@@ -192,9 +146,8 @@ export declare function clearConfirmationPoint(db: CapTransaction, jobId: string
192
146
  /** submitted → confirmed (depth reached). */
193
147
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
194
148
  /**
195
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
196
- * only safe once the chain has been consulted — a failed row releases the
197
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
149
+ * Any active state → failed. Releases the idempotency key, so a `submitting`/`submitted` row
150
+ * may only be failed once the chain has been consulted.
198
151
  */
199
152
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
200
153
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
@@ -208,33 +161,14 @@ export interface RecoveryResult {
208
161
  submittingToReconcile: WalletJobRow[];
209
162
  }
210
163
  /**
211
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
212
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
213
- * lease is held belong to a running executor (possibly on another instance) and
214
- * must not be touched.
215
- *
216
- * Safe by construction: a `building` row is pre-submit by definition — the worker
217
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
218
- * backend, so nothing that is still `building` has ever been sent. Rows that made
219
- * it past that point are `submitting` and are reconciled, never failed here.
164
+ * Fail a wallet's orphaned `building` rows, only when its lease is expired/unowned. A `building`
165
+ * row is pre-submit by definition (the signed CBOR is committed as `submitting` first), so nothing sent is failed.
220
166
  */
221
167
  export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
222
168
  /**
223
- * Boot-time recovery (design §8), by state:
224
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
225
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
226
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
227
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
228
- * chain and re-submits those exact bytes if needed.
229
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
230
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
231
- *
232
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
233
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
234
- * job right now (rolling deploy) — failing it here while its submit succeeds
235
- * would leave a failed row for an on-chain tx, and since failed rows don't block
236
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
237
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
169
+ * Boot-time recovery: `building` → failed PROCESS_RESTART (never sent; only when the wallet lease
170
+ * is expired/unowned, a held lease means another live instance owns it); `submitting` → returned
171
+ * for chain reconciliation, never rebuilt; `submitted` → handed to the confirmation tracker.
238
172
  */
239
173
  export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
240
174
  /** Idempotently register/refresh a configured wallet row (no key material). */
@@ -247,9 +181,8 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
247
181
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
248
182
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
249
183
  /**
250
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
251
- * read-back verification, same shape as the crawler lease). At most one worker
252
- * instance may execute jobs for a wallet at any time.
184
+ * Acquire an expired/unowned per-wallet lease (compare-and-swap + read-back verification).
185
+ * At most one worker instance may execute jobs for a wallet at any time.
253
186
  */
254
187
  export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
255
188
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
@@ -1,23 +1,7 @@
1
1
  /**
2
- * Keeps a per-wallet lease alive for as long as a job execution runs.
3
- *
4
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
5
- * multi-backend build plus an HSM round-trip); a single renewal before the build
6
- * is therefore not enough. Without a heartbeat the lease silently expires
7
- * mid-execution, another instance adopts the wallet, fails this executor's row as
8
- * orphaned and starts the next job — two executors on one wallet, which is exactly
9
- * what the per-wallet lease exists to prevent.
10
- *
11
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
12
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
13
- * wedged stops beating and correctly loses the wallet.
14
- *
15
- * Two failure semantics, on purpose:
16
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
17
- * only a definitive "not yours" marks the lease lost.
18
- * - `fence()` is strict: it is called right before an irreversible step, where
19
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
20
- * free (nothing has been sent yet); guessing wrong is a double spend.
2
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
3
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
4
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
21
5
  */
22
6
  export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
23
7
  export declare class LeaseHeartbeat {
@@ -33,7 +17,7 @@ export declare class LeaseHeartbeat {
33
17
  constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
34
18
  start(): void;
35
19
  stop(): void;
36
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
20
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
37
21
  isLost(): boolean;
38
22
  /** Renew now; false means "do not touch this wallet any further". */
39
23
  fence(): Promise<boolean>;
@@ -8,25 +8,9 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const job_store_1 = require("./job-store");
9
9
  const logger = cds_1.default.log('CardanoWalletWorker');
10
10
  /**
11
- * Keeps a per-wallet lease alive for as long as a job execution runs.
12
- *
13
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
14
- * multi-backend build plus an HSM round-trip); a single renewal before the build
15
- * is therefore not enough. Without a heartbeat the lease silently expires
16
- * mid-execution, another instance adopts the wallet, fails this executor's row as
17
- * orphaned and starts the next job — two executors on one wallet, which is exactly
18
- * what the per-wallet lease exists to prevent.
19
- *
20
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
21
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
22
- * wedged stops beating and correctly loses the wallet.
23
- *
24
- * Two failure semantics, on purpose:
25
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
26
- * only a definitive "not yours" marks the lease lost.
27
- * - `fence()` is strict: it is called right before an irreversible step, where
28
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
29
- * free (nothing has been sent yet); guessing wrong is a double spend.
11
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
12
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
13
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
30
14
  */
31
15
  exports.LEASE_HEARTBEAT_INTERVAL_MS = Math.floor(job_store_1.WORKER_LEASE_TTL_MS / 3);
32
16
  class LeaseHeartbeat {
@@ -56,7 +40,7 @@ class LeaseHeartbeat {
56
40
  this.timer = null;
57
41
  }
58
42
  }
59
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
43
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
60
44
  isLost() {
61
45
  return this.lost;
62
46
  }
@@ -1,16 +1,8 @@
1
1
  import type { WorkerSignerTypeValue } from './job-store';
2
2
  /**
3
- * Wallet-worker signers (v2.0).
4
- *
5
- * `WorkerSigner` is the signer-agnostic surface the worker engine executes against:
6
- * - `hsm` (production): thin wrapper around the already-initialized `HsmSigner`
7
- * (PKCS#11 — keys never leave the module).
8
- * - `software` (dev/test): operator-configured Ed25519 key from an environment
9
- * variable, either plain 64-char hex or AES-256-GCM encrypted
10
- * (`iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY — see srv/utils/crypto.ts).
11
- *
12
- * Keys are NEVER accepted through the OData surface and never persisted; the
13
- * software key lives only in this process's memory.
3
+ * Wallet-worker signers: `hsm` wraps the process-wide HsmSigner (PKCS#11), `software` holds an
4
+ * Ed25519 key from an env var (plain hex or AES-256-GCM `iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY).
5
+ * Keys are never accepted via OData and never persisted.
14
6
  */
15
7
  export interface WorkerSigner {
16
8
  readonly type: WorkerSignerTypeValue;
@@ -25,17 +17,12 @@ export interface WorkerSigner {
25
17
  export interface WorkerWalletConfig {
26
18
  walletId: string;
27
19
  signerType: WorkerSignerTypeValue;
28
- /**
29
- * software only: name of the environment variable holding the Ed25519 signing
30
- * key — plain 64-char hex, or AES-256-GCM `iv:authTag:ciphertext` (base64 parts).
31
- */
20
+ /** software only: env var holding the Ed25519 key — 64-char hex or AES-256-GCM `iv:authTag:ciphertext` (base64). */
32
21
  keyEnv?: string;
33
22
  }
34
23
  /**
35
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
36
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
37
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
38
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
24
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
25
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
39
26
  */
40
27
  export declare function mergeVkeyWitness(unsignedTxCbor: string, publicKeyHex: string, signatureHex: string): string;
41
28
  /** Derive the bech32 enterprise key-hash address for a 28-byte key hash. */
@@ -17,10 +17,8 @@ const errors_1 = require("../../utils/errors");
17
17
  const crypto_2 = require("../../utils/crypto");
18
18
  const logger = cds_1.default.log('CardanoWalletWorker');
19
19
  /**
20
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
21
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
22
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
23
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
20
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
21
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
24
22
  */
25
23
  function mergeVkeyWitness(unsignedTxCbor, publicKeyHex, signatureHex) {
26
24
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
@@ -99,10 +97,7 @@ class SoftwareWorkerSigner {
99
97
  }
100
98
  }
101
99
  exports.SoftwareWorkerSigner = SoftwareWorkerSigner;
102
- /**
103
- * Resolve the software key material for a wallet: plain hex passes through,
104
- * the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY.
105
- */
100
+ /** Plain hex passes through; the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY. */
106
101
  function resolveSoftwareKey(wallet) {
107
102
  if (!wallet.keyEnv) {
108
103
  throw new errors_1.ConfigError(`Wallet worker: wallet "${wallet.walletId}" is signerType=software but has no keyEnv configured`);
@@ -2,32 +2,9 @@ import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { type WorkerSigner, type WorkerWalletConfig } from './signers';
4
4
  /**
5
- * Wallet worker engine (v2.0, design §6).
6
- *
7
- * Dispatch loop over `CardanoWalletJobs`: per tick, for every configured wallet
8
- * with pending work and NO active job (building or submitted — the queue stays
9
- * blocked until the previous job CONFIRMS, which makes per-wallet UTxO contention
10
- * impossible by construction), acquire the per-wallet DB lease and execute:
11
- *
12
- * building → CardanoIndexer.index<Kind>BuildResult (build + TransactionBuilds row)
13
- * → signer.signTransaction
14
- * submitting → signed CBOR + hash committed, THEN client.submitTransaction
15
- * submitted → hand to the ConfirmationTracker (crawler hook or polling)
16
- *
17
- * The `submitting` commit is what makes the submit boundary crash-safe: the exact
18
- * bytes that may be on-chain are durable before the network call, and the row stays
19
- * non-terminal, so it keeps holding its idempotency key. Anything that goes wrong
20
- * from there on is reconciled against the chain (`reconcileSubmitting`) — the same
21
- * transaction is re-submitted, never a rebuild.
22
- *
23
- * Transient failures BEFORE the signed tx exists (provider outages, rate limits,
24
- * HSM hiccups during build/sign) re-queue the job with exponential backoff up to
25
- * `maxAttempts`; deterministic rejections (validation, insufficient funds) fail
26
- * immediately.
27
- *
28
- * All DB access runs in short fresh transactions (ambient context cleared —
29
- * NIGHTGATE lesson 2) so the single pooled SQLite connection is never held
30
- * across build/submit round-trips.
5
+ * Dispatch loop over `CardanoWalletJobs`: each tick leases every wallet with pending work and no active job
6
+ * and runs building → submitting (signed CBOR committed BEFORE submit) → submitted → ConfirmationTracker.
7
+ * After the `submitting` commit failures are reconciled against the chain, never rebuilt; transient pre-sign failures re-queue with backoff.
31
8
  */
32
9
  export interface WalletWorkerConfig {
33
10
  enabled: boolean;
@@ -48,10 +25,7 @@ export interface WalletWorkerDeps {
48
25
  }
49
26
  /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
50
27
  export declare function retryBackoffMs(attempt: number): number;
51
- /**
52
- * Transient errors are worth a bounded retry; everything else is deterministic
53
- * (a retry cannot change the outcome) and fails the job immediately.
54
- */
28
+ /** Transient errors get a bounded retry; everything else fails the job immediately. */
55
29
  export declare function isTransientJobError(err: unknown): boolean;
56
30
  export declare class CardanoWalletWorker {
57
31
  private readonly deps;
@@ -79,66 +53,36 @@ export declare class CardanoWalletWorker {
79
53
  /** One dispatch round; serialized (overlapping timers collapse into one run). */
80
54
  private tickSafe;
81
55
  private tick;
82
- /**
83
- * Adopt `submitting` rows left behind by a dead executor (this process before a
84
- * restart, or another instance whose lease expired) and resolve them against the
85
- * chain. Runs per wallet under the same lease the executor would hold.
86
- */
56
+ /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
87
57
  private reconcileOrphanedSubmissions;
88
58
  /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
89
59
  private spawn;
90
60
  /** A heartbeat that keeps this instance's lease on `walletId` alive while it works. */
91
61
  private leaseHeartbeat;
92
62
  /**
93
- * Execute one job: building → (build → sign) → submitting → submit → submitted,
94
- * then hand to the tracker. The wallet lease is held for the duration — renewed by
95
- * a heartbeat, because build+sign can outlast its TTL — and released afterwards
96
- * (queue serialization continues via the job row, not the lease).
97
- *
98
- * Everything up to and including the `submitting` commit may fail freely — nothing
99
- * has been sent, so the job re-queues or fails normally. Past that commit the job
100
- * belongs to `reconcileSubmitting`.
63
+ * Execute one job: building → (build → sign) → submitting → submit → submitted → tracker.
64
+ * The wallet lease is heartbeat-renewed for the duration. Up to the `submitting` commit failures
65
+ * re-queue or fail normally; past it the job belongs to `reconcileSubmitting`.
101
66
  */
102
67
  private executeJob;
103
68
  /**
104
- * Send a transaction that is already durable in its `submitting` row and advance
105
- * the job to `submitted`.
106
- *
107
- * A submit failure is NEVER propagated as a job failure here: a rejection from one
108
- * backend does not prove the tx is absent from every mempool (failover, timeouts,
109
- * a node that accepted before the connection dropped). The row simply stays
110
- * `submitting` and the next tick reconciles it against the chain.
69
+ * Send a tx already durable in its `submitting` row and advance to `submitted`. A submit failure
70
+ * never fails the job here (one rejection does not prove absence from every mempool); the row
71
+ * stays `submitting` for the next tick's reconciliation.
111
72
  */
112
73
  private submitStoredTransaction;
113
74
  /** submitting → submitted + hand to the confirmation tracker. */
114
75
  private adoptSubmitted;
115
76
  /**
116
- * Resolve a `submitting` job whose submit outcome is unknown (process died around
117
- * the network call, or the call failed ambiguously). The stored transaction is the
118
- * only one this job may ever have — it is re-submitted verbatim, never rebuilt.
119
- *
120
- * 1. Re-submit the same CBOR: mempool/ledger dedup makes this a no-op if it was
121
- * accepted before, so success (or "already known") simply promotes the job.
122
- * 2. If that fails, ask the chain: found → the tx did make it, promote it.
123
- * 3. Only when the chain proves absence AND the node rejects the tx for good (or
124
- * it has been absent past the confirmation timeout) is the job failed —
125
- * failing releases the idempotency key, so it needs that proof.
126
- * Anything else leaves the row as-is; the next tick tries again.
127
- *
128
- * Runs under the same heartbeat-kept wallet lease as an execution: the chain
129
- * lookups here are slow enough to outlive the raw TTL. Losing the lease mid-way
130
- * is not dangerous (the re-submit is the same transaction, and every terminal
131
- * transition is row-guarded), so it only stops further work.
77
+ * Resolve a `submitting` job with an unknown submit outcome; the stored tx is re-submitted verbatim,
78
+ * never rebuilt. Order: re-submit (already-known = success) → chain lookup (found = promote) →
79
+ * fail only when proven absent AND rejected for good or past the confirmation timeout; else retry next tick.
132
80
  */
133
81
  private reconcileSubmitting;
134
82
  private failReconciled;
135
83
  /** Dispatch the job kind to the matching indexer build method. */
136
84
  private buildForKind;
137
- /**
138
- * Submit tolerant of "already known": after a crash between submit and the
139
- * `submitted` transition, the retry re-submits the same CBOR — mempool dedup
140
- * answers with an already-submitted error that IS our success case.
141
- */
85
+ /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
142
86
  private submitWithAlreadyKnownTolerance;
143
87
  private handleExecutionFailure;
144
88
  }