@odatano/core 1.11.0 → 2.0.0-rc.1

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 (111) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
  2. package/@cds-models/CardanoIndexerService/index.js +23 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  4. package/@cds-models/CardanoODataService/index.js +88 -390
  5. package/@cds-models/CardanoSignService/index.d.ts +443 -1574
  6. package/@cds-models/CardanoSignService/index.js +62 -293
  7. package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
  8. package/@cds-models/CardanoTransactionService/index.js +60 -271
  9. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  10. package/@cds-models/CardanoWorkerService/index.js +32 -0
  11. package/@cds-models/_/index.d.ts +70 -40
  12. package/@cds-models/_/index.js +17 -32
  13. package/@cds-models/cds/outbox/index.d.ts +28 -0
  14. package/@cds-models/index.d.ts +225 -522
  15. package/@cds-models/index.js +35 -218
  16. package/@cds-models/odatano/cardano/index.d.ts +896 -2947
  17. package/@cds-models/odatano/cardano/index.js +109 -536
  18. package/@cds-models/sap/common/index.d.ts +196 -600
  19. package/@cds-models/sap/common/index.js +28 -269
  20. package/README.md +136 -102
  21. package/db/schema.cds +283 -1
  22. package/db/types.cds +48 -0
  23. package/package.json +41 -32
  24. package/src/index.d.ts +1 -1
  25. package/src/index.js +10 -2
  26. package/src/plugin.js +12 -2
  27. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  28. package/srv/blockchain/backends/blockfrost-backend.js +68 -15
  29. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  30. package/srv/blockchain/backends/cardano-backend.js +13 -0
  31. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  32. package/srv/blockchain/backends/koios-backend.js +147 -15
  33. package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
  34. package/srv/blockchain/backends/ogmios-backend.js +254 -5
  35. package/srv/blockchain/cardano-client.d.ts +19 -0
  36. package/srv/blockchain/cardano-client.js +36 -0
  37. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  38. package/srv/blockchain/cardano-indexer.js +191 -0
  39. package/srv/blockchain/crawler/crawler.d.ts +151 -0
  40. package/srv/blockchain/crawler/crawler.js +677 -0
  41. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  42. package/srv/blockchain/crawler/hooks.js +62 -0
  43. package/srv/blockchain/crawler/index.d.ts +26 -0
  44. package/srv/blockchain/crawler/index.js +135 -0
  45. package/srv/blockchain/crawler/sync-state.d.ts +94 -0
  46. package/srv/blockchain/crawler/sync-state.js +265 -0
  47. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  48. package/srv/blockchain/signing/hsm-signer.js +8 -1
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  50. package/srv/blockchain/wallet-worker/build-request.js +341 -0
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
  53. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  54. package/srv/blockchain/wallet-worker/index.js +80 -0
  55. package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
  56. package/srv/blockchain/wallet-worker/job-store.js +564 -0
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  58. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  59. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  60. package/srv/blockchain/wallet-worker/signers.js +131 -0
  61. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  62. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  63. package/srv/cardano-indexer-service.cds +73 -0
  64. package/srv/cardano-indexer-service.d.ts +2 -0
  65. package/srv/cardano-indexer-service.js +76 -0
  66. package/srv/cardano-service.js +22 -1
  67. package/srv/cardano-tx-service.d.ts +1 -11
  68. package/srv/cardano-tx-service.js +11 -162
  69. package/srv/cardano-worker-service.cds +125 -0
  70. package/srv/cardano-worker-service.d.ts +2 -0
  71. package/srv/cardano-worker-service.js +199 -0
  72. package/srv/server.d.ts +32 -1
  73. package/srv/server.js +228 -2
  74. package/srv/utils/collections.d.ts +13 -0
  75. package/srv/utils/collections.js +24 -0
  76. package/srv/utils/crypto.d.ts +16 -0
  77. package/srv/utils/crypto.js +75 -0
  78. package/srv/utils/error-codes.d.ts +6 -0
  79. package/srv/utils/error-codes.js +6 -0
  80. package/srv/utils/errors.d.ts +12 -0
  81. package/srv/utils/errors.js +45 -0
  82. package/srv/utils/mappers.js +13 -3
  83. package/srv/utils/service-events.d.ts +26 -0
  84. package/srv/utils/service-events.js +46 -0
  85. package/srv/utils/tx-request-parsers.d.ts +58 -0
  86. package/srv/utils/tx-request-parsers.js +170 -0
  87. package/srv/utils/tx-utils.d.ts +2 -1
  88. package/srv/utils/tx-utils.js +3 -2
  89. package/srv/utils/types.d.ts +2 -1
  90. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  91. package/@cds-models/CardanoODataService/index.js.map +0 -1
  92. package/@cds-models/CardanoODataService/index.ts +0 -776
  93. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  94. package/@cds-models/CardanoSignService/index.js.map +0 -1
  95. package/@cds-models/CardanoSignService/index.ts +0 -569
  96. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  97. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  98. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  99. package/@cds-models/_/index.d.ts.map +0 -1
  100. package/@cds-models/_/index.js.map +0 -1
  101. package/@cds-models/_/index.ts +0 -96
  102. package/@cds-models/cds/outbox/index.ts +0 -27
  103. package/@cds-models/index.d.ts.map +0 -1
  104. package/@cds-models/index.js.map +0 -1
  105. package/@cds-models/index.ts +0 -245
  106. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  107. package/@cds-models/odatano/cardano/index.js.map +0 -1
  108. package/@cds-models/odatano/cardano/index.ts +0 -789
  109. package/@cds-models/sap/common/index.d.ts.map +0 -1
  110. package/@cds-models/sap/common/index.js.map +0 -1
  111. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,542 @@
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.CardanoWalletWorker = void 0;
7
+ exports.retryBackoffMs = retryBackoffMs;
8
+ exports.isTransientJobError = isTransientJobError;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const errors_1 = require("../../utils/errors");
11
+ const error_codes_1 = require("../../utils/error-codes");
12
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
+ const confirmation_tracker_1 = require("./confirmation-tracker");
14
+ const lease_heartbeat_1 = require("./lease-heartbeat");
15
+ const build_request_1 = require("./build-request");
16
+ const service_events_1 = require("../../utils/service-events");
17
+ const signers_1 = require("./signers");
18
+ const job_store_1 = require("./job-store");
19
+ const logger = cds_1.default.log('CardanoWalletWorker');
20
+ /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
21
+ function retryBackoffMs(attempt) {
22
+ return Math.min(5_000 * 2 ** Math.max(0, attempt - 1), 60_000);
23
+ }
24
+ /**
25
+ * Transient errors are worth a bounded retry; everything else is deterministic
26
+ * (a retry cannot change the outcome) and fails the job immediately.
27
+ */
28
+ function isTransientJobError(err) {
29
+ if (err instanceof errors_1.ProviderUnavailableError)
30
+ return true;
31
+ if (err instanceof errors_1.RateLimitError)
32
+ return true;
33
+ if (err instanceof errors_1.AllBackendsFailedError)
34
+ return true;
35
+ if (err instanceof errors_1.HsmError)
36
+ return true;
37
+ if (err instanceof errors_1.BackendError)
38
+ return err.statusCode >= 500 || err.statusCode === 429;
39
+ return false;
40
+ }
41
+ function terminalErrorCode(err) {
42
+ if (err instanceof errors_1.BackendError && err.code)
43
+ return String(err.code);
44
+ return 'EXECUTION_FAILED';
45
+ }
46
+ class CardanoWalletWorker {
47
+ deps;
48
+ signers = new Map();
49
+ executing = new Set(); // walletIds with an execution in flight in THIS process
50
+ executionPromises = new Set();
51
+ tracker;
52
+ dispatchTimer = null;
53
+ running = false;
54
+ ticking = false;
55
+ constructor(deps) {
56
+ this.deps = deps;
57
+ this.tracker = new confirmation_tracker_1.ConfirmationTracker({
58
+ client: deps.client,
59
+ options: {
60
+ confirmationDepth: deps.config.confirmationDepth,
61
+ confirmationTimeoutMs: deps.config.confirmationTimeoutMs,
62
+ pollIntervalMs: Math.max(deps.config.pollIntervalMs, 5_000),
63
+ resubmitOnRollback: deps.config.resubmitOnRollback,
64
+ },
65
+ onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
66
+ logger.debug(`Wallet ${walletId} unblocked (job ${outcome}) — next tick dispatches`);
67
+ // Fired only on a TERMINAL outcome, after the transition is committed, so a
68
+ // subscriber that reads the job row sees the state the event announces.
69
+ (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
70
+ jobId,
71
+ walletId,
72
+ kind,
73
+ txHash,
74
+ ...(outcome === 'failed' ? { errorCode: errorCode ?? null, errorMessage: errorMessage ?? null } : {}),
75
+ });
76
+ void this.tickSafe();
77
+ },
78
+ });
79
+ }
80
+ isRunning() {
81
+ return this.running;
82
+ }
83
+ /** Wallets this instance can sign for (signer init succeeded). */
84
+ getWalletIds() {
85
+ return [...this.signers.keys()];
86
+ }
87
+ getSigner(walletId) {
88
+ return this.signers.get(walletId);
89
+ }
90
+ /** Live status summary for the control service. */
91
+ getStatusSummary() {
92
+ return {
93
+ running: this.running,
94
+ wallets: this.getWalletIds(),
95
+ executing: [...this.executing],
96
+ awaitingConfirmation: this.tracker.size(),
97
+ };
98
+ }
99
+ async start() {
100
+ if (this.running)
101
+ return;
102
+ if (!this.deps.config.wallets.length) {
103
+ logger.warn('Wallet worker refused to start: no wallets configured');
104
+ return;
105
+ }
106
+ // 1. Initialize signers — a broken wallet config skips that wallet, not the worker.
107
+ for (const walletCfg of this.deps.config.wallets) {
108
+ try {
109
+ const signer = (0, signers_1.createWorkerSigner)(walletCfg, this.deps.network);
110
+ this.signers.set(walletCfg.walletId, signer);
111
+ await cds_1.default.tx((tx) => (0, job_store_1.upsertWalletRegistration)(tx, {
112
+ walletId: walletCfg.walletId,
113
+ signerType: walletCfg.signerType,
114
+ address: signer.getAddress(),
115
+ publicKeyHash: signer.getPublicKeyHash(),
116
+ }));
117
+ }
118
+ catch (err) {
119
+ logger.error(`Wallet "${walletCfg.walletId}" skipped — signer initialization failed:`, err);
120
+ }
121
+ }
122
+ if (this.signers.size === 0) {
123
+ logger.error('Wallet worker not started: no wallet signer could be initialized');
124
+ return;
125
+ }
126
+ // 2. Crash recovery: fail interrupted builds, re-watch submitted jobs. Rows
127
+ // interrupted around the submit call stay `submitting` — the first tick
128
+ // reconciles them against the chain (reconcileOrphanedSubmissions).
129
+ const recovery = await cds_1.default.tx((tx) => (0, job_store_1.recoverInterruptedJobs)(tx));
130
+ if (recovery.submittingToReconcile.length) {
131
+ logger.warn(`${recovery.submittingToReconcile.length} job(s) with an unresolved submit will be reconciled on the next dispatch tick`);
132
+ }
133
+ for (const job of recovery.submittedToReconcile) {
134
+ if (!job.txHash)
135
+ continue; // defensive: submitted implies txHash
136
+ this.tracker.track({
137
+ jobId: job.ID,
138
+ walletId: job.walletId,
139
+ kind: job.kind,
140
+ txHash: job.txHash,
141
+ signedTxCbor: job.signedTxCbor,
142
+ submittedAt: job.submittedAt,
143
+ confirmedSlot: job.confirmedSlot,
144
+ confirmedHeight: job.confirmedHeight,
145
+ });
146
+ }
147
+ // 3. Go.
148
+ this.running = true;
149
+ this.tracker.start();
150
+ this.dispatchTimer = setInterval(() => { void this.tickSafe(); }, this.deps.config.pollIntervalMs);
151
+ this.dispatchTimer.unref?.();
152
+ void this.tickSafe();
153
+ logger.info(`Wallet worker started (wallets=[${this.getWalletIds().join(', ')}], instance=${this.deps.instanceId})`);
154
+ }
155
+ async stop() {
156
+ if (!this.running)
157
+ return;
158
+ this.running = false;
159
+ if (this.dispatchTimer) {
160
+ clearInterval(this.dispatchTimer);
161
+ this.dispatchTimer = null;
162
+ }
163
+ this.tracker.stop();
164
+ // Executions are short (build+sign+submit) — await them so teardown never races a write.
165
+ await Promise.allSettled([...this.executionPromises]);
166
+ for (const walletId of this.getWalletIds()) {
167
+ try {
168
+ await cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, walletId, this.deps.instanceId));
169
+ }
170
+ catch (err) {
171
+ logger.debug(`Lease release for ${walletId} failed (TTL expires it anyway):`, err);
172
+ }
173
+ }
174
+ logger.info('Wallet worker stopped');
175
+ }
176
+ /** One dispatch round; serialized (overlapping timers collapse into one run). */
177
+ async tickSafe() {
178
+ if (!this.running || this.ticking)
179
+ return;
180
+ this.ticking = true;
181
+ try {
182
+ await this.tick();
183
+ }
184
+ catch (err) {
185
+ logger.error('Wallet worker dispatch tick failed:', err);
186
+ }
187
+ finally {
188
+ this.ticking = false;
189
+ }
190
+ }
191
+ async tick() {
192
+ // Interrupted submits first: a stuck `submitting` row blocks its wallet queue
193
+ // and may be the only work there is (no pending job would ever surface it).
194
+ await this.reconcileOrphanedSubmissions();
195
+ const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findDueJobs)(tx)));
196
+ if (!due.length)
197
+ return;
198
+ // First runnable job per wallet, dispatch order (priority, createdAt) preserved.
199
+ const nextPerWallet = new Map();
200
+ for (const job of due) {
201
+ if (!nextPerWallet.has(job.walletId))
202
+ nextPerWallet.set(job.walletId, job);
203
+ }
204
+ for (const [walletId, job] of nextPerWallet) {
205
+ if (!this.running)
206
+ return;
207
+ if (this.executing.size >= this.deps.config.maxConcurrentWallets)
208
+ return;
209
+ if (this.executing.has(walletId))
210
+ continue;
211
+ const signer = this.signers.get(walletId);
212
+ if (!signer)
213
+ continue; // job for a wallet this instance cannot sign for
214
+ const dispatched = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
215
+ // Steady-state orphan cleanup: a building row whose wallet lease expired
216
+ // belongs to a dead executor — fail it here so the wallet unblocks without
217
+ // needing a reboot (boot recovery only covers restarts of THIS instance).
218
+ await (0, job_store_1.failOrphanedBuildingJobs)(tx, walletId);
219
+ // DB truth serializes across restarts and instances: a building OR submitted
220
+ // job blocks the wallet queue until the tracker finalizes it (design §6).
221
+ if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
222
+ return false;
223
+ return (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId);
224
+ }));
225
+ if (!dispatched)
226
+ continue;
227
+ this.spawn(walletId, () => this.executeJob(job, signer));
228
+ }
229
+ }
230
+ /**
231
+ * Adopt `submitting` rows left behind by a dead executor (this process before a
232
+ * restart, or another instance whose lease expired) and resolve them against the
233
+ * chain. Runs per wallet under the same lease the executor would hold.
234
+ */
235
+ async reconcileOrphanedSubmissions() {
236
+ const { instanceId } = this.deps;
237
+ for (const walletId of this.getWalletIds()) {
238
+ if (!this.running)
239
+ return;
240
+ if (this.executing.size >= this.deps.config.maxConcurrentWallets)
241
+ return;
242
+ if (this.executing.has(walletId))
243
+ continue;
244
+ const orphan = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
245
+ const stuck = await (0, job_store_1.findOrphanedSubmittingJob)(tx, walletId);
246
+ if (!stuck)
247
+ return null;
248
+ return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, instanceId)) ? stuck : null;
249
+ }));
250
+ if (!orphan)
251
+ continue;
252
+ this.spawn(walletId, () => this.reconcileSubmitting(orphan));
253
+ }
254
+ }
255
+ /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
256
+ spawn(walletId, work) {
257
+ this.executing.add(walletId);
258
+ const execution = work()
259
+ .catch((err) => logger.error(`Wallet ${walletId}: unhandled execution error:`, err))
260
+ .finally(() => {
261
+ this.executing.delete(walletId);
262
+ this.executionPromises.delete(execution);
263
+ });
264
+ this.executionPromises.add(execution);
265
+ }
266
+ /** A heartbeat that keeps this instance's lease on `walletId` alive while it works. */
267
+ leaseHeartbeat(walletId) {
268
+ const { instanceId } = this.deps;
269
+ const heartbeat = new lease_heartbeat_1.LeaseHeartbeat(async () => await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.renewWalletLease)(tx, walletId, instanceId))), `wallet ${walletId}`);
270
+ heartbeat.start();
271
+ return heartbeat;
272
+ }
273
+ /**
274
+ * Execute one job: building → (build → sign) → submitting → submit → submitted,
275
+ * then hand to the tracker. The wallet lease is held for the duration — renewed by
276
+ * a heartbeat, because build+sign can outlast its TTL — and released afterwards
277
+ * (queue serialization continues via the job row, not the lease).
278
+ *
279
+ * Everything up to and including the `submitting` commit may fail freely — nothing
280
+ * has been sent, so the job re-queues or fails normally. Past that commit the job
281
+ * belongs to `reconcileSubmitting`.
282
+ */
283
+ async executeJob(job, signer) {
284
+ const { instanceId } = this.deps;
285
+ const attempt = job.attempt + 1;
286
+ const claimed = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markBuilding)(tx, job.ID, attempt)));
287
+ if (!claimed)
288
+ return; // cancelled or claimed elsewhere
289
+ const heartbeat = this.leaseHeartbeat(job.walletId);
290
+ try {
291
+ let unsignedTxCbor = null;
292
+ let signedTxCbor;
293
+ let fee = null;
294
+ let buildId = null;
295
+ if (job.kind === 'submitSigned') {
296
+ const request = JSON.parse(job.request ?? '{}');
297
+ if (!request.signedTxCbor) {
298
+ throw new errors_1.BackendError('submitSigned job has no signedTxCbor in its request', 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
299
+ }
300
+ signedTxCbor = request.signedTxCbor;
301
+ }
302
+ else {
303
+ const rawReq = JSON.parse(job.request ?? '{}');
304
+ // The worker wallet is ALWAYS the sender/change target — callers cannot
305
+ // spend from foreign addresses through a worker wallet.
306
+ rawReq.network = this.deps.network;
307
+ rawReq.senderAddress = signer.getAddress();
308
+ if (!rawReq.changeAddress)
309
+ rawReq.changeAddress = signer.getAddress();
310
+ // The stored request has the documented Build*-action payload shape
311
+ // (assetsJson/mintActionsJson/… strings) — transform it into the
312
+ // TxBuildRequest shape the indexer build methods expect.
313
+ const buildReq = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, rawReq, this.deps.network);
314
+ // Fencing: if the lease was lost (instance stalled past the TTL, another
315
+ // instance may have taken over the wallet), abort BEFORE building — the
316
+ // orphan cleanup will fail the row once the lease is provably dead.
317
+ if (!(await heartbeat.fence())) {
318
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build — aborting execution`);
319
+ return;
320
+ }
321
+ const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => this.buildForKind(tx, job, buildReq)));
322
+ unsignedTxCbor = buildResult.unsignedTxCbor;
323
+ fee = buildResult.fee ?? null;
324
+ buildId = buildResult.id ?? null;
325
+ signedTxCbor = signer.signTransaction(unsignedTxCbor, buildResult.txBodyHash);
326
+ }
327
+ // The hash comes from the signed bytes, not from the submit response, so the
328
+ // row can name the transaction before anyone has seen it.
329
+ const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
330
+ // Last fence before the irreversible part. Build+sign just consumed real time;
331
+ // if the wallet moved to another instance meanwhile, that instance is entitled
332
+ // to spend the same UTxOs — submitting now would race it. Nothing has been sent
333
+ // yet, so standing down here costs only a rebuild.
334
+ if (!(await heartbeat.fence())) {
335
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing — NOT submitting tx ${txHash}`);
336
+ return;
337
+ }
338
+ // Point of no return: commit the signed tx BEFORE it can reach a backend.
339
+ // A crash after this leaves a `submitting` row that reconciliation resolves;
340
+ // a crash before it leaves a `building` row that was provably never sent.
341
+ // The guard on `building` is also the second half of the fence: if a takeover
342
+ // already failed this row, the transition returns false and nothing is sent.
343
+ const stored = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitting)(tx, job.ID, { txHash, unsignedTxCbor, signedTxCbor, fee })));
344
+ if (!stored) {
345
+ logger.warn(`Job ${job.ID}: submitting transition was fenced — not submitting (another executor owns this job)`);
346
+ return;
347
+ }
348
+ await this.submitStoredTransaction(job, { txHash, signedTxCbor, buildId, attempt });
349
+ }
350
+ catch (err) {
351
+ await this.handleExecutionFailure(job, attempt, err);
352
+ }
353
+ finally {
354
+ heartbeat.stop();
355
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
356
+ .catch(() => undefined);
357
+ }
358
+ }
359
+ /**
360
+ * Send a transaction that is already durable in its `submitting` row and advance
361
+ * the job to `submitted`.
362
+ *
363
+ * A submit failure is NEVER propagated as a job failure here: a rejection from one
364
+ * backend does not prove the tx is absent from every mempool (failover, timeouts,
365
+ * a node that accepted before the connection dropped). The row simply stays
366
+ * `submitting` and the next tick reconciles it against the chain.
367
+ */
368
+ async submitStoredTransaction(job, tx) {
369
+ let submittedHash;
370
+ try {
371
+ submittedHash = await this.submitWithAlreadyKnownTolerance(tx.signedTxCbor);
372
+ }
373
+ catch (err) {
374
+ logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash} — job stays submitting for chain reconciliation:`, err);
375
+ return;
376
+ }
377
+ if (job.kind !== 'submitSigned') {
378
+ // Observability parity with the synchronous flow: record the submission row.
379
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => this.deps.indexer.persistTransactionSubmission(t, { signedTxCbor: tx.signedTxCbor, txHash: submittedHash, buildId: tx.buildId }))).catch((err) => logger.warn(`Job ${job.ID}: submission bookkeeping failed (job continues):`, err));
380
+ }
381
+ await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor);
382
+ logger.info(`Job ${job.ID} (wallet ${job.walletId}, kind ${job.kind}): submitted as ${submittedHash} (attempt ${tx.attempt})`);
383
+ }
384
+ /** submitting → submitted + hand to the confirmation tracker. */
385
+ async adoptSubmitted(job, txHash, signedTxCbor) {
386
+ const submitted = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitted)(tx, job.ID, txHash)));
387
+ if (!submitted) {
388
+ logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced — tracker adopts the tx anyway`);
389
+ }
390
+ this.tracker.track({
391
+ jobId: job.ID,
392
+ walletId: job.walletId,
393
+ kind: job.kind,
394
+ txHash,
395
+ signedTxCbor,
396
+ submittedAt: job.submittedAt ?? new Date().toISOString(),
397
+ });
398
+ }
399
+ /**
400
+ * Resolve a `submitting` job whose submit outcome is unknown (process died around
401
+ * the network call, or the call failed ambiguously). The stored transaction is the
402
+ * only one this job may ever have — it is re-submitted verbatim, never rebuilt.
403
+ *
404
+ * 1. Re-submit the same CBOR: mempool/ledger dedup makes this a no-op if it was
405
+ * accepted before, so success (or "already known") simply promotes the job.
406
+ * 2. If that fails, ask the chain: found → the tx did make it, promote it.
407
+ * 3. Only when the chain proves absence AND the node rejects the tx for good (or
408
+ * it has been absent past the confirmation timeout) is the job failed —
409
+ * failing releases the idempotency key, so it needs that proof.
410
+ * Anything else leaves the row as-is; the next tick tries again.
411
+ *
412
+ * Runs under the same heartbeat-kept wallet lease as an execution: the chain
413
+ * lookups here are slow enough to outlive the raw TTL. Losing the lease mid-way
414
+ * is not dangerous (the re-submit is the same transaction, and every terminal
415
+ * transition is row-guarded), so it only stops further work.
416
+ */
417
+ async reconcileSubmitting(job) {
418
+ const { instanceId } = this.deps;
419
+ const heartbeat = this.leaseHeartbeat(job.walletId);
420
+ try {
421
+ if (!job.signedTxCbor || !job.txHash) {
422
+ // Cannot happen via markSubmitting; treat as a never-sent job rather than
423
+ // leaving the wallet queue blocked forever.
424
+ logger.error(`Job ${job.ID}: submitting row without signed transaction — failing as PROCESS_RESTART`);
425
+ await this.failReconciled(job, job_store_1.JOB_ERROR_CODES.PROCESS_RESTART, new Error('Job was interrupted before its signed transaction was stored.'));
426
+ return;
427
+ }
428
+ logger.warn(`Job ${job.ID}: reconciling interrupted submit of tx ${job.txHash}`);
429
+ let submitError;
430
+ try {
431
+ const txHash = await this.submitWithAlreadyKnownTolerance(job.signedTxCbor);
432
+ await this.adoptSubmitted(job, txHash, job.signedTxCbor);
433
+ logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}) — now awaiting confirmation`);
434
+ return;
435
+ }
436
+ catch (err) {
437
+ submitError = err;
438
+ }
439
+ // The tx may have been rejected precisely BECAUSE it is already on-chain
440
+ // (its inputs are spent), so the chain — not the rejection — decides.
441
+ let onChain;
442
+ try {
443
+ await this.deps.client.getTransaction(job.txHash);
444
+ onChain = true;
445
+ }
446
+ catch (lookupErr) {
447
+ if (!(0, errors_1.isNotFoundOnAllBackends)(lookupErr)) {
448
+ logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive — retrying next tick:`, lookupErr);
449
+ return;
450
+ }
451
+ onChain = false;
452
+ }
453
+ if (onChain) {
454
+ logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit — awaiting confirmation`);
455
+ await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
456
+ return;
457
+ }
458
+ const ageMs = job.submittedAt ? Date.now() - Date.parse(job.submittedAt) : 0;
459
+ const expired = ageMs > this.deps.config.confirmationTimeoutMs;
460
+ if (isTransientJobError(submitError) && !expired) {
461
+ logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain — retrying next tick:`, submitError);
462
+ return;
463
+ }
464
+ // Proven absent + a rejection that will not change (or a tx that is past its
465
+ // mempool lifetime): no transaction of this job can reach the chain anymore,
466
+ // so releasing the idempotency key is safe.
467
+ const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
468
+ logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}) — failing:`, submitError);
469
+ await this.failReconciled(job, code, submitError);
470
+ }
471
+ finally {
472
+ heartbeat.stop();
473
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
474
+ .catch(() => undefined);
475
+ }
476
+ }
477
+ async failReconciled(job, code, err) {
478
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
479
+ const transitioned = await (0, job_store_1.markFailed)(tx, job.ID, code, err ?? new Error(code));
480
+ if (transitioned)
481
+ await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
482
+ })).catch((persistErr) => logger.error(`Job ${job.ID}: failure persist failed:`, persistErr));
483
+ }
484
+ /** Dispatch the job kind to the matching indexer build method. */
485
+ buildForKind(tx, job, buildReq) {
486
+ const indexer = this.deps.indexer;
487
+ switch (job.kind) {
488
+ case 'simpleAda': return indexer.indexSimpleBuildResult(tx, buildReq);
489
+ case 'metadata': return indexer.indexMetadataBuildResult(tx, buildReq);
490
+ case 'multiAsset': return indexer.indexMultiAssetBuildResult(tx, buildReq);
491
+ case 'mint': return indexer.indexMintBuildResult(tx, buildReq);
492
+ case 'plutusSpend': return indexer.indexPlutusSpendBuildResult(tx, buildReq);
493
+ default:
494
+ throw new errors_1.BackendError(`Unsupported job kind "${job.kind}"`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
495
+ }
496
+ }
497
+ /**
498
+ * Submit tolerant of "already known": after a crash between submit and the
499
+ * `submitted` transition, the retry re-submits the same CBOR — mempool dedup
500
+ * answers with an already-submitted error that IS our success case.
501
+ */
502
+ async submitWithAlreadyKnownTolerance(signedTxCbor) {
503
+ try {
504
+ return await this.deps.client.submitTransaction(signedTxCbor);
505
+ }
506
+ catch (err) {
507
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
508
+ const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
509
+ logger.info(`Submit reported tx already known — treating as success (${txHash})`);
510
+ return txHash;
511
+ }
512
+ throw err;
513
+ }
514
+ }
515
+ async handleExecutionFailure(job, attempt, err) {
516
+ // Only a pre-submit job may be re-queued (rebuild) or failed from here. Once the
517
+ // row is `submitting`, a signed tx exists that may be in a mempool: rebuilding it
518
+ // would double-pay and failing it would release the idempotency key on a
519
+ // transaction the chain has not ruled on. Those rows go to reconciliation.
520
+ const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
521
+ .catch(() => null);
522
+ if (current && current.status !== 'building') {
523
+ logger.error(`Job ${job.ID}: execution error while ${current.status} — leaving the outcome to reconciliation:`, err);
524
+ return;
525
+ }
526
+ if (isTransientJobError(err) && attempt < job.maxAttempts) {
527
+ const backoff = retryBackoffMs(attempt);
528
+ logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts} — retrying in ${backoff}ms:`, err);
529
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.requeueForRetry)(tx, job.ID, err, new Date(Date.now() + backoff).toISOString()))).catch((persistErr) => logger.error(`Job ${job.ID}: retry re-queue failed:`, persistErr));
530
+ return;
531
+ }
532
+ const code = isTransientJobError(err) ? job_store_1.JOB_ERROR_CODES.RETRIES_EXHAUSTED : terminalErrorCode(err);
533
+ logger.error(`Job ${job.ID}: failed terminally (${code}) on attempt ${attempt}:`, err);
534
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
535
+ const transitioned = await (0, job_store_1.markFailed)(tx, job.ID, code, err);
536
+ if (transitioned)
537
+ await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
538
+ })).catch((persistErr) => logger.error(`Job ${job.ID}: failure persist failed:`, persistErr));
539
+ }
540
+ }
541
+ exports.CardanoWalletWorker = CardanoWalletWorker;
542
+ //# sourceMappingURL=wallet-worker.js.map
@@ -0,0 +1,73 @@
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Indexer Service (v2.0)
5
+ *
6
+ * Control + observability surface for the chain crawler / pre-sync engine:
7
+ * - read-only projections of the sync cursor and reorg audit log
8
+ * - status function + pause/resume actions delegating to the crawler singleton
9
+ *
10
+ * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
+ * service-level auth. pause/resume are operational actions — gate behind a dedicated
12
+ * Admin scope. Read-only status and audit data remain available to authenticated users.
13
+ */
14
+ @requires: 'authenticated-user'
15
+ service CardanoIndexerService @(impl: './cardano-indexer-service') {
16
+
17
+ @readonly
18
+ @title : 'Sync State'
19
+ @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
20
+ entity SyncState as projection on db.CardanoSyncState;
21
+
22
+ @readonly
23
+ @title : 'Reorg Log'
24
+ @description: 'Audit trail of chain rollbacks handled by the crawler'
25
+ entity ReorgLog as projection on db.CardanoReorgLog;
26
+
27
+ @title : 'Crawler Status'
28
+ @description: 'Live crawler status summary (numeric fields as strings, CAP-10 aligned)'
29
+ type CrawlerStatus {
30
+ running : Boolean;
31
+ syncStatus : String;
32
+ lastSlot : String;
33
+ lastHeight : String;
34
+ tipHeight : String;
35
+ syncProgress : String;
36
+ consecutiveErrors : Integer;
37
+ }
38
+
39
+ @title : 'Get Crawler Status'
40
+ @description: 'Return the current crawler run state and sync progress'
41
+ /**
42
+ * Emitted AFTER each block is committed. Subscribe instead of polling:
43
+ * (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
44
+ * In-process (plugin mode) this needs no messaging service.
45
+ */
46
+ event blockIndexed {
47
+ hash : String(64);
48
+ slot : Integer64;
49
+ height : Integer64;
50
+ txHashes : many String(64);
51
+ tipSlot : Integer64;
52
+ tipHeight: Integer64;
53
+ }
54
+
55
+ /** Emitted AFTER a rollback is committed. Everything above `forkSlot` was removed. */
56
+ event reorg {
57
+ forkSlot : Integer64;
58
+ forkHeight : Integer64;
59
+ blocksRolledBack : Integer;
60
+ }
61
+
62
+ function getStatus() returns CrawlerStatus;
63
+
64
+ @title : 'Pause Crawler'
65
+ @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
66
+ @requires : 'Admin'
67
+ action pauseCrawler() returns Boolean;
68
+
69
+ @title : 'Resume Crawler'
70
+ @description: 'Start/restart the crawler from the persisted cursor using the configured source.'
71
+ @requires : 'Admin'
72
+ action resumeCrawler() returns Boolean;
73
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-indexer-service.d.ts.map