@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,287 @@
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.CRAWLER_LEASE_TTL_MS = exports.MAX_CONSECUTIVE_ERRORS = exports.SINGLETON_ID = void 0;
7
+ exports.ensureSyncStateSingleton = ensureSyncStateSingleton;
8
+ exports.readCursor = readCursor;
9
+ exports.isCrawlerLeaseActive = isCrawlerLeaseActive;
10
+ exports.tryAcquireCrawlerLease = tryAcquireCrawlerLease;
11
+ exports.renewCrawlerLease = renewCrawlerLease;
12
+ exports.releaseCrawlerLease = releaseCrawlerLease;
13
+ exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
+ exports.latchPoisonBlock = latchPoisonBlock;
15
+ exports.advanceCursor = advanceCursor;
16
+ exports.resetCursorTo = resetCursorTo;
17
+ exports.setSyncStatus = setSyncStatus;
18
+ exports.recordError = recordError;
19
+ const cds_1 = __importDefault(require("@sap/cds"));
20
+ const cardano_1 = require("#cds-models/odatano/cardano");
21
+ const errors_1 = require("../../utils/errors");
22
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
23
+ const logger = cds_1.default.log('CardanoCrawler');
24
+ /**
25
+ * Chain crawler cursor helpers (v2.0 pre-sync).
26
+ *
27
+ * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
28
+ * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
29
+ *
30
+ * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
31
+ * STRINGS, not JS numbers — the same change that makes them strings over OData.
32
+ * Every read here therefore coerces numeric fields with `num()`; callers get a
33
+ * clean numeric `SyncCursor` and never have to think about it.
34
+ */
35
+ exports.SINGLETON_ID = 'SINGLETON';
36
+ /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
37
+ exports.MAX_CONSECUTIVE_ERRORS = 10;
38
+ /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
39
+ exports.CRAWLER_LEASE_TTL_MS = 15_000;
40
+ /**
41
+ * Coerce a CAP-10 numeric-as-string (or number/bigint/null) into a JS number.
42
+ * Separate optional/required helpers avoid overload declarations (and the
43
+ * no-redeclare lint false-positive they caused).
44
+ */
45
+ function optionalNum(v) {
46
+ if (v === null || v === undefined || v === '')
47
+ return null;
48
+ const n = Number(v);
49
+ return Number.isNaN(n) ? null : n;
50
+ }
51
+ function requiredNum(v, fallback = 0) {
52
+ return optionalNum(v) ?? fallback;
53
+ }
54
+ function timestamp(v) {
55
+ if (v === null || v === undefined || v === '')
56
+ return null;
57
+ if (v instanceof Date)
58
+ return v.toISOString();
59
+ return String(v);
60
+ }
61
+ function leaseDeadlineReached(cursor, owner, expectedMs) {
62
+ if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
63
+ return false;
64
+ const actualMs = Date.parse(cursor.leaseUntil);
65
+ // Some adapters normalize Timestamp precision/format. One second tolerance covers
66
+ // that representation change without accepting an old lease interval.
67
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
68
+ }
69
+ /** Map a raw DB row into the normalized numeric cursor. */
70
+ function toCursor(row) {
71
+ return {
72
+ network: row.network ?? null,
73
+ startSlot: optionalNum(row.startSlot),
74
+ startBlockHash: row.startBlockHash ?? null,
75
+ lastSlot: requiredNum(row.lastSlot),
76
+ lastBlockHash: row.lastBlockHash ?? null,
77
+ lastHeight: requiredNum(row.lastHeight),
78
+ tipSlot: optionalNum(row.tipSlot),
79
+ tipHeight: optionalNum(row.tipHeight),
80
+ syncStatus: (row.syncStatus ?? 'stopped'),
81
+ consecutiveErrors: requiredNum(row.consecutiveErrors),
82
+ desiredRunning: row.desiredRunning !== false,
83
+ leaseOwner: row.leaseOwner ?? null,
84
+ leaseUntil: timestamp(row.leaseUntil),
85
+ };
86
+ }
87
+ /**
88
+ * Idempotently ensure the singleton cursor row exists and return it.
89
+ * On first call (fresh DB) the row is created with the configured start point
90
+ * (if given) and status 'stopped'. Subsequent calls just return the current row.
91
+ * Safe to call from both the crawler and the control service.
92
+ */
93
+ async function ensureSyncStateSingleton(db, network, start) {
94
+ const existing = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
95
+ if (existing) {
96
+ const cursor = toCursor(existing);
97
+ if (cursor.network !== network) {
98
+ throw new errors_1.ConfigError(`Crawler cursor network mismatch: persisted cursor tracks ${cursor.network ?? 'an unknown network'}, configured client is ${network}.`);
99
+ }
100
+ return cursor;
101
+ }
102
+ const row = {
103
+ ID: exports.SINGLETON_ID,
104
+ network,
105
+ startSlot: start?.slot ?? null,
106
+ startBlockHash: start?.hash ?? null,
107
+ lastSlot: start?.slot ?? 0,
108
+ lastBlockHash: start?.hash ?? null,
109
+ lastHeight: start?.height ?? 0,
110
+ tipSlot: null,
111
+ tipHeight: null,
112
+ syncStatus: 'stopped',
113
+ consecutiveErrors: 0,
114
+ desiredRunning: true,
115
+ leaseOwner: null,
116
+ leaseUntil: null,
117
+ };
118
+ await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
119
+ logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
120
+ return toCursor(row);
121
+ }
122
+ /** Read the current cursor, or null if it has not been initialized yet. */
123
+ async function readCursor(db) {
124
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
125
+ return row ? toCursor(row) : null;
126
+ }
127
+ /** Whether the shared lease currently represents a live cluster-wide crawler. */
128
+ function isCrawlerLeaseActive(cursor, now = new Date()) {
129
+ if (!cursor?.desiredRunning || !cursor.leaseOwner || !cursor.leaseUntil)
130
+ return false;
131
+ const deadline = Date.parse(cursor.leaseUntil);
132
+ return Number.isFinite(deadline) && deadline > now.getTime();
133
+ }
134
+ /**
135
+ * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
136
+ * The post-update read is intentional: CAP adapters consistently return the row
137
+ * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
138
+ */
139
+ async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
140
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
141
+ if (!raw)
142
+ return false;
143
+ const current = toCursor(raw);
144
+ if (!current.desiredRunning)
145
+ return false;
146
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
147
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
148
+ return false;
149
+ // CAS on the observed OWNER only (a plain string that round-trips identically
150
+ // on every adapter). If two instances race, the first writer changes leaseOwner
151
+ // and the loser's UPDATE matches 0 rows → its read-back verification fails.
152
+ // Deliberately NOT comparing leaseUntil: HANA/driver timestamp normalization can
153
+ // make the read-back representation differ from what the WHERE serializes, so a
154
+ // timestamp-equality CAS may NEVER match again after a leader crash — the lease
155
+ // would be stuck until the row is cleared by hand. The residual race (the old
156
+ // owner renewing concurrently) resolves via fencing: its next renew no longer
157
+ // matches leaseOwner and it halts.
158
+ const where = {
159
+ ID: exports.SINGLETON_ID,
160
+ leaseOwner: raw.leaseOwner ?? null,
161
+ };
162
+ if (Object.prototype.hasOwnProperty.call(raw, 'desiredRunning')) {
163
+ where.desiredRunning = raw.desiredRunning;
164
+ }
165
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
166
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where(where));
167
+ const verified = await readCursor(db);
168
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
169
+ }
170
+ /**
171
+ * Renew/fence a lease. Call this inside the same transaction as every crawler write:
172
+ * the conditional UPDATE serializes a former leader against a newly elected one.
173
+ */
174
+ async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
175
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
176
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({
177
+ ID: exports.SINGLETON_ID,
178
+ leaseOwner: owner,
179
+ desiredRunning: true,
180
+ }));
181
+ const verified = await readCursor(db);
182
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
183
+ }
184
+ /**
185
+ * Release only the caller's lease; a stale process can never clear a successor.
186
+ *
187
+ * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
188
+ * then refuses to start until an operator calls resumeCrawler. Reserve it for
189
+ * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
190
+ * crashed stream, a provider outage or a node restart must NOT latch: those are
191
+ * exactly the cases where coming back up should resume the pre-sync by itself.
192
+ */
193
+ async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
194
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
195
+ leaseOwner: null,
196
+ leaseUntil: null,
197
+ syncStatus: status,
198
+ ...(pauseCluster ? { desiredRunning: false } : {}),
199
+ }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
200
+ }
201
+ /**
202
+ * Persist the pause/resume intent shared by every app instance. Resuming also clears
203
+ * the error streak: the operator says the cause is fixed, and a stale streak would
204
+ * otherwise keep the standby backoff at its cap for the first retry.
205
+ */
206
+ async function setCrawlerDesiredRunning(db, desiredRunning) {
207
+ const set = { desiredRunning };
208
+ if (desiredRunning)
209
+ set.consecutiveErrors = 0;
210
+ else
211
+ set.syncStatus = 'stopped';
212
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
213
+ }
214
+ /**
215
+ * Latch the cluster off because of a poison block (a block whose data the database
216
+ * deterministically rejects). Deliberately NOT lease-scoped, unlike releaseCrawlerLease:
217
+ * the poison is a property of the block, not of the instance that observed it, and
218
+ * that instance may have lost its lease while the failure was being recorded. Only
219
+ * an operator's resumeCrawler brings the crawler back.
220
+ */
221
+ async function latchPoisonBlock(db, message) {
222
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
223
+ desiredRunning: false,
224
+ syncStatus: 'error',
225
+ lastError: message.slice(0, 500),
226
+ lastErrorAt: new Date().toISOString(),
227
+ }).where({ ID: exports.SINGLETON_ID }));
228
+ }
229
+ /**
230
+ * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
231
+ * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
232
+ * lastIndexedAt. Optionally records the latest known tip (for progress).
233
+ */
234
+ async function advanceCursor(db, block, tip, status = 'syncing') {
235
+ const set = {
236
+ lastSlot: block.slot,
237
+ lastBlockHash: block.hash,
238
+ lastHeight: block.height ?? 0,
239
+ lastIndexedAt: new Date().toISOString(),
240
+ syncStatus: status,
241
+ consecutiveErrors: 0,
242
+ lastError: null,
243
+ };
244
+ if (tip) {
245
+ set.tipSlot = tip.slot;
246
+ if (tip.height !== undefined)
247
+ set.tipHeight = tip.height;
248
+ }
249
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
250
+ }
251
+ /** Reset the cursor to a rollback point (used by reorg handling). */
252
+ async function resetCursorTo(db, point) {
253
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
254
+ lastSlot: point.slot,
255
+ lastBlockHash: point.hash,
256
+ lastHeight: point.height ?? 0,
257
+ lastIndexedAt: new Date().toISOString(),
258
+ }).where({ ID: exports.SINGLETON_ID }));
259
+ logger.warn(`Sync cursor reset to fork point ${point.slot}/${point.hash}`);
260
+ }
261
+ /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
262
+ async function setSyncStatus(db, status, pauseCluster = false) {
263
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
264
+ syncStatus: status,
265
+ ...(pauseCluster ? { desiredRunning: false } : {}),
266
+ }).where({ ID: exports.SINGLETON_ID }));
267
+ }
268
+ /**
269
+ * Record a crawler error. Increments the consecutive-error counter and flips status
270
+ * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
271
+ * length so the caller can decide whether to back off / stop.
272
+ */
273
+ async function recordError(db, err, leaseOwner) {
274
+ if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
275
+ return -1;
276
+ const current = await readCursor(db);
277
+ const streak = (current?.consecutiveErrors ?? 0) + 1;
278
+ const message = err instanceof Error ? err.message : String(err);
279
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
280
+ consecutiveErrors: streak,
281
+ lastError: message.slice(0, 500),
282
+ lastErrorAt: new Date().toISOString(),
283
+ syncStatus: streak >= exports.MAX_CONSECUTIVE_ERRORS ? 'error' : 'syncing',
284
+ }).where({ ID: exports.SINGLETON_ID }));
285
+ return streak;
286
+ }
287
+ //# sourceMappingURL=sync-state.js.map
@@ -1,4 +1,48 @@
1
1
  import { HsmConfig, HsmSignResult } from '../../utils/types';
2
+ /**
3
+ * HsmSigner - PKCS#11 Hardware Security Module integration for Cardano transaction signing
4
+ *
5
+ * Wraps a PKCS#11 compliant HSM (YubiHSM 2, AWS CloudHSM, Thales Luna, etc.)
6
+ * to provide Ed25519 signing for Cardano transactions. Private keys never leave
7
+ * the HSM chip — only signatures are returned.
8
+ *
9
+ * Lifecycle:
10
+ * 1. constructor(config) — stores config
11
+ * 2. init(network) — connects to HSM, locates key, exports public key, derives Cardano address
12
+ * 3. sign() / signTransaction() — signing operations
13
+ * 4. shutdown() — closes session
14
+ */
15
+ /** Minimal PKCS#11 module surface used here. Loaded dynamically; no static type
16
+ * package is depended on. We narrow to the actual handful of methods invoked. */
17
+ interface PKCS11Instance {
18
+ load(path: string): void;
19
+ C_Initialize(): void;
20
+ C_Finalize(): void;
21
+ C_OpenSession(slot: Buffer, flags: number): Buffer;
22
+ C_CloseSession(session: Buffer): void;
23
+ C_Login(session: Buffer, userType: number, pin: string): void;
24
+ C_Logout(session: Buffer): void;
25
+ C_FindObjectsInit(session: Buffer, template: Pkcs11Attribute[]): void;
26
+ C_FindObjects(session: Buffer, count: number): Buffer[];
27
+ C_FindObjectsFinal(session: Buffer): void;
28
+ C_GetAttributeValue(session: Buffer, handle: Buffer, template: Pkcs11Attribute[]): Pkcs11Attribute[];
29
+ C_SignInit(session: Buffer, mechanism: {
30
+ mechanism: number;
31
+ }, key: Buffer): void;
32
+ C_Sign(session: Buffer, data: Buffer, signature: Buffer): Buffer;
33
+ C_GetSlotList(tokenPresent: boolean): Buffer[];
34
+ }
35
+ interface Pkcs11Attribute {
36
+ type: number;
37
+ value?: Buffer | number | boolean | string;
38
+ }
39
+ type Pkcs11JsModule = {
40
+ PKCS11: new () => PKCS11Instance;
41
+ [k: string]: unknown;
42
+ };
43
+ type Pkcs11Loader = () => Pkcs11JsModule;
44
+ /** Test seam: inject a fake pkcs11js module loader (null restores the default). */
45
+ export declare function setPkcs11Loader(loader: Pkcs11Loader | null): void;
2
46
  export declare class HsmSigner {
3
47
  private pkcs11;
4
48
  private session;
@@ -71,4 +115,5 @@ export declare function getHsmSigner(): HsmSigner | null;
71
115
  * Set the HsmSigner instance (called during initialization and shutdown).
72
116
  */
73
117
  export declare function setHsmSigner(signer: HsmSigner | null): void;
118
+ export {};
74
119
  //# sourceMappingURL=hsm-signer.d.ts.map
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.HsmSigner = void 0;
7
+ exports.setPkcs11Loader = setPkcs11Loader;
7
8
  exports.getHsmSigner = getHsmSigner;
8
9
  exports.setHsmSigner = setHsmSigner;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
@@ -17,6 +18,12 @@ const logger = cds_1.default.log('HsmSigner');
17
18
  * Used for Ed25519 signing operations
18
19
  */
19
20
  const CKM_EDDSA = 0x00001057;
21
+ const defaultPkcs11Loader = () => require('pkcs11js');
22
+ let pkcs11Loader = defaultPkcs11Loader;
23
+ /** Test seam: inject a fake pkcs11js module loader (null restores the default). */
24
+ function setPkcs11Loader(loader) {
25
+ pkcs11Loader = loader ?? defaultPkcs11Loader;
26
+ }
20
27
  class HsmSigner {
21
28
  pkcs11;
22
29
  session;
@@ -39,7 +46,7 @@ class HsmSigner {
39
46
  // Dynamic import — pkcs11js is only loaded when HSM is configured
40
47
  let pkcs11js;
41
48
  try {
42
- pkcs11js = require('pkcs11js');
49
+ pkcs11js = pkcs11Loader();
43
50
  }
44
51
  catch {
45
52
  throw new errors_1.HsmError('pkcs11js is not installed. Install it with: npm install pkcs11js', 500, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
@@ -140,10 +140,30 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
140
140
  * Returns empty array when no reference inputs are provided.
141
141
  */
142
142
  private _mapReferenceInputs;
143
+ /**
144
+ * Funding requirement contributed by extra outputs on a mint build:
145
+ * the summed lovelace of all entries plus, per asset unit, the demand the
146
+ * transaction's own positive mints do NOT cover. Minted quantities are
147
+ * aggregated per unit and subtracted from the aggregated output demand;
148
+ * only a positive remainder is requested from the wallet (a fully covered
149
+ * unit is not requested at all — it does not exist before this tx).
150
+ */
151
+ private _extraOutputsFundingAfterMint;
152
+ /**
153
+ * The script an individual mint action executes under: its own
154
+ * per-action policy when set (multi-policy mint FR), else the request's
155
+ * top-level policy script.
156
+ */
157
+ private _mintActionScript;
143
158
  /**
144
159
  * Build the Buildooor mint-entry array shared by the mint-only flow and the
145
160
  * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
146
161
  * they are stamped into the redeemers post-build by _buildScriptTx).
162
+ *
163
+ * Multi-policy mint FR: each action may carry its own policy script and
164
+ * redeemer; absent fields fall back to the request-level ones. The ledger
165
+ * carries ONE redeemer per policy, so actions resolving to the same policy
166
+ * must agree on their redeemer, checked here.
147
167
  */
148
168
  private _buildMintEntries;
149
169
  /**
@@ -246,13 +246,15 @@ class BuildooorTxBuilder {
246
246
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
247
  // Parse the minting policy script once
248
248
  const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
249
- // Calculate total mint value for output (only positive quantities - mints, not burns)
249
+ // Calculate total mint value for output (only positive quantities - mints, not burns).
250
+ // Multi-policy mint FR: each action mints under ITS script (own or top-level).
250
251
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
251
- for (const mintAction of req.mintActions) {
252
+ for (const [index, mintAction] of req.mintActions.entries()) {
252
253
  const quantity = BigInt(mintAction.quantity);
253
254
  if (quantity > 0n) {
255
+ const actionScript = this._mintActionScript(mintAction, script, index);
254
256
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
255
- mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), quantity));
257
+ mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), quantity));
256
258
  }
257
259
  }
258
260
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
@@ -264,8 +266,15 @@ class BuildooorTxBuilder {
264
266
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
265
267
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
266
268
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
267
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
268
- const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
269
+ // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
270
+ // thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
271
+ // demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
272
+ // from the wallet).
273
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
274
+ if (req.extraOutputs && req.extraOutputs.length > 0) {
275
+ const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
276
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
277
+ }
269
278
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
270
279
  const inputs = [...forcedInputs, ...selectedFunding];
271
280
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
@@ -281,15 +290,24 @@ class BuildooorTxBuilder {
281
290
  const resolvedInlineDatum = req.inlineDatum
282
291
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
283
292
  : undefined;
284
- // Build output — recipient gets the minted assets + min ADA
293
+ const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
294
+ // Build output — recipient gets the minted assets + min ADA. When extra
295
+ // outputs are declared (FR-2 on mint) THEY carry the minted assets (each
296
+ // token on its own output with its own datum, e.g. datum-bound predicate
297
+ // tokens), so the primary output stays ADA(+datum)-only.
285
298
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
286
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
299
+ if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
300
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
301
+ }
287
302
  const refScript = this._parseReferenceScript(req.referenceScript);
288
303
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
289
- // Mint entries for the build args (uses pre-resolved redeemer). Note: Buildooor
290
- // ignores caller-supplied execution units — the real units are stamped into the
304
+ // Append extra outputs, each independently min-ADA checked.
305
+ this._appendExtraOutputs(outputs, resolvedExtraOutputs);
306
+ // Mint entries for the build args (uses pre-resolved redeemers; per-action
307
+ // redeemers resolve their own placeholders). Note: Buildooor ignores
308
+ // caller-supplied execution units — the real units are stamped into the
291
309
  // redeemers post-build by _buildScriptTx.
292
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
310
+ const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
293
311
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
294
312
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
295
313
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
@@ -394,11 +412,12 @@ class BuildooorTxBuilder {
394
412
  }
395
413
  // If mints are present and no extraOutputs handle the minted assets, attach positive mints to the primary output.
396
414
  if (hasMint && (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0)) {
397
- for (const action of req.mintActions) {
415
+ for (const [index, action] of req.mintActions.entries()) {
398
416
  const qty = BigInt(action.quantity);
399
417
  if (qty > 0n) {
418
+ const actionScript = this._mintActionScript(action, mintScript, index);
400
419
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
401
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), qty));
420
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), qty));
402
421
  }
403
422
  }
404
423
  }
@@ -411,7 +430,7 @@ class BuildooorTxBuilder {
411
430
  // caller-supplied execution units — the real units are stamped into the
412
431
  // redeemers post-build by _buildScriptTx.
413
432
  const mints = hasMint
414
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
433
+ ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
415
434
  : undefined;
416
435
  const scriptInput = {
417
436
  utxo: scriptLedgerUtxo,
@@ -760,21 +779,86 @@ class BuildooorTxBuilder {
760
779
  return [];
761
780
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
762
781
  }
782
+ /**
783
+ * Funding requirement contributed by extra outputs on a mint build:
784
+ * the summed lovelace of all entries plus, per asset unit, the demand the
785
+ * transaction's own positive mints do NOT cover. Minted quantities are
786
+ * aggregated per unit and subtracted from the aggregated output demand;
787
+ * only a positive remainder is requested from the wallet (a fully covered
788
+ * unit is not requested at all — it does not exist before this tx).
789
+ */
790
+ _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
791
+ const mintedByUnit = new Map();
792
+ for (const action of mintActions) {
793
+ const quantity = BigInt(action.quantity);
794
+ if (quantity > 0n) {
795
+ const unit = action.assetUnit.toLowerCase();
796
+ mintedByUnit.set(unit, (mintedByUnit.get(unit) ?? 0n) + quantity);
797
+ }
798
+ }
799
+ const demandByUnit = new Map();
800
+ let lovelace = 0n;
801
+ for (const extra of extraOutputs) {
802
+ lovelace += BigInt(extra.lovelaceAmount);
803
+ for (const asset of extra.assets ?? []) {
804
+ const unit = asset.unit.toLowerCase();
805
+ demandByUnit.set(unit, (demandByUnit.get(unit) ?? 0n) + BigInt(asset.quantity));
806
+ }
807
+ }
808
+ const assets = [];
809
+ for (const [unit, demand] of demandByUnit) {
810
+ const uncovered = demand - (mintedByUnit.get(unit) ?? 0n);
811
+ if (uncovered > 0n)
812
+ assets.push({ unit, quantity: uncovered.toString() });
813
+ }
814
+ return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
815
+ }
816
+ /**
817
+ * The script an individual mint action executes under: its own
818
+ * per-action policy when set (multi-policy mint FR), else the request's
819
+ * top-level policy script.
820
+ */
821
+ _mintActionScript(action, defaultScript, index) {
822
+ if (!action.mintingPolicyScript)
823
+ return defaultScript;
824
+ return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
825
+ }
763
826
  /**
764
827
  * Build the Buildooor mint-entry array shared by the mint-only flow and the
765
828
  * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
766
829
  * they are stamped into the redeemers post-build by _buildScriptTx).
830
+ *
831
+ * Multi-policy mint FR: each action may carry its own policy script and
832
+ * redeemer; absent fields fall back to the request-level ones. The ledger
833
+ * carries ONE redeemer per policy, so actions resolving to the same policy
834
+ * must agree on their redeemer, checked here.
767
835
  */
768
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
769
- return mintActions.map(action => {
836
+ _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
837
+ const redeemerByPolicy = new Map();
838
+ return mintActions.map((action, index) => {
839
+ const script = this._mintActionScript(action, mintScript, index);
840
+ const actionRedeemer = action.redeemerJson !== undefined
841
+ ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
842
+ : resolvedMintRedeemer;
843
+ const redeemerData = actionRedeemer !== undefined
844
+ ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
845
+ : new plutus_data_1.DataI(action.redeemer ?? 0);
846
+ const policyId = script.hash.toString();
847
+ // Canonical comparison over the encoded PlutusData: JSON key order must
848
+ // not matter, and a JSON {int:0} equals the DataI(0) fallback.
849
+ const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
850
+ const seen = redeemerByPolicy.get(policyId);
851
+ if (seen !== undefined && seen !== redeemerFingerprint) {
852
+ throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
853
+ 'split them into separate transactions or align the redeemers');
854
+ }
855
+ redeemerByPolicy.set(policyId, redeemerFingerprint);
770
856
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
771
857
  return {
772
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
858
+ value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
773
859
  script: {
774
- inline: mintScript,
775
- redeemer: resolvedMintRedeemer
776
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
777
- : new plutus_data_1.DataI(action.redeemer ?? 0)
860
+ inline: script,
861
+ redeemer: redeemerData
778
862
  }
779
863
  };
780
864
  });
@@ -0,0 +1,26 @@
1
+ import type { TxBuildRequest } from '../../utils/types';
2
+ import type { Network } from '../cardano-client';
3
+ import type { WalletJobKindValue } from './job-store';
4
+ /**
5
+ * Transform a stored wallet-job `requestJson` (the documented Build*-action
6
+ * payload shape — assetsJson, mintActionsJson, metadataJson strings, …) into
7
+ * the TxBuildRequest shape the CardanoIndexer build methods expect (assets,
8
+ * mintActions with bigint quantities, parsed metadata, assembled
9
+ * plutusScriptExecution, …).
10
+ *
11
+ * The synchronous CardanoTransactionService handlers do this transformation
12
+ * inline per action; the worker executes the SAME payload asynchronously, so
13
+ * this module mirrors that logic using the shared parsers
14
+ * (srv/utils/tx-request-parsers.ts). Validation failures throw
15
+ * BackendError 400 INVALID_INPUT — deterministic, so the job fails terminally
16
+ * instead of burning retries.
17
+ */
18
+ type RawRequest = Record<string, unknown>;
19
+ /**
20
+ * Transform the raw job request (documented Build*-action payload) into the
21
+ * TxBuildRequest the matching CardanoIndexer build method expects. Throws
22
+ * BackendError 400 INVALID_INPUT for malformed payloads (terminal job failure).
23
+ */
24
+ export declare function prepareWorkerBuildRequest(kind: WalletJobKindValue, raw: RawRequest, network: Network): TxBuildRequest;
25
+ export {};
26
+ //# sourceMappingURL=build-request.d.ts.map