@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
@@ -21,10 +21,7 @@ const logger = cds_1.default.log('CardanoWalletWorker');
21
21
  function retryBackoffMs(attempt) {
22
22
  return Math.min(5_000 * 2 ** Math.max(0, attempt - 1), 60_000);
23
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
- */
24
+ /** Transient errors get a bounded retry; everything else fails the job immediately. */
28
25
  function isTransientJobError(err) {
29
26
  if (err instanceof errors_1.ProviderUnavailableError)
30
27
  return true;
@@ -46,7 +43,7 @@ function terminalErrorCode(err) {
46
43
  class CardanoWalletWorker {
47
44
  deps;
48
45
  signers = new Map();
49
- executing = new Set(); // walletIds with an execution in flight in THIS process
46
+ executing = new Set(); // walletIds executing in THIS process
50
47
  executionPromises = new Set();
51
48
  tracker;
52
49
  dispatchTimer = null;
@@ -64,8 +61,7 @@ class CardanoWalletWorker {
64
61
  },
65
62
  onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
66
63
  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.
64
+ // Terminal outcomes only, after the commit, so subscribers reading the row see the announced state.
69
65
  (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
70
66
  jobId,
71
67
  walletId,
@@ -123,9 +119,8 @@ class CardanoWalletWorker {
123
119
  logger.error('Wallet worker not started: no wallet signer could be initialized');
124
120
  return;
125
121
  }
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).
122
+ // 2. Crash recovery: fail interrupted builds, re-watch submitted jobs; `submitting`
123
+ // rows are reconciled by the first tick.
129
124
  const recovery = await cds_1.default.tx((tx) => (0, job_store_1.recoverInterruptedJobs)(tx));
130
125
  if (recovery.submittingToReconcile.length) {
131
126
  logger.warn(`${recovery.submittingToReconcile.length} job(s) with an unresolved submit will be reconciled on the next dispatch tick`);
@@ -161,7 +156,7 @@ class CardanoWalletWorker {
161
156
  this.dispatchTimer = null;
162
157
  }
163
158
  this.tracker.stop();
164
- // Executions are short (build+sign+submit) — await them so teardown never races a write.
159
+ // Await in-flight executions so teardown never races a write.
165
160
  await Promise.allSettled([...this.executionPromises]);
166
161
  for (const walletId of this.getWalletIds()) {
167
162
  try {
@@ -189,8 +184,7 @@ class CardanoWalletWorker {
189
184
  }
190
185
  }
191
186
  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).
187
+ // Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
194
188
  await this.reconcileOrphanedSubmissions();
195
189
  const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findDueJobs)(tx)));
196
190
  if (!due.length)
@@ -212,12 +206,10 @@ class CardanoWalletWorker {
212
206
  if (!signer)
213
207
  continue; // job for a wallet this instance cannot sign for
214
208
  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).
209
+ // A building row whose wallet lease expired belongs to a dead executor — fail it
210
+ // so the wallet unblocks without a reboot.
218
211
  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).
212
+ // An active job blocks the wallet queue until the tracker finalizes it.
221
213
  if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
222
214
  return false;
223
215
  return (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId);
@@ -227,11 +219,7 @@ class CardanoWalletWorker {
227
219
  this.spawn(walletId, () => this.executeJob(job, signer));
228
220
  }
229
221
  }
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
- */
222
+ /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
235
223
  async reconcileOrphanedSubmissions() {
236
224
  const { instanceId } = this.deps;
237
225
  for (const walletId of this.getWalletIds()) {
@@ -271,14 +259,9 @@ class CardanoWalletWorker {
271
259
  return heartbeat;
272
260
  }
273
261
  /**
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`.
262
+ * Execute one job: building → (build → sign) → submitting → submit → submitted → tracker.
263
+ * The wallet lease is heartbeat-renewed for the duration. Up to the `submitting` commit failures
264
+ * re-queue or fail normally; past it the job belongs to `reconcileSubmitting`.
282
265
  */
283
266
  async executeJob(job, signer) {
284
267
  const { instanceId } = this.deps;
@@ -301,19 +284,13 @@ class CardanoWalletWorker {
301
284
  }
302
285
  else {
303
286
  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.
287
+ // The worker wallet is ALWAYS the sender/change target — no spending from foreign addresses.
306
288
  rawReq.network = this.deps.network;
307
289
  rawReq.senderAddress = signer.getAddress();
308
290
  if (!rawReq.changeAddress)
309
291
  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
292
  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.
293
+ // Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
317
294
  if (!(await heartbeat.fence())) {
318
295
  logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build — aborting execution`);
319
296
  return;
@@ -324,22 +301,16 @@ class CardanoWalletWorker {
324
301
  buildId = buildResult.id ?? null;
325
302
  signedTxCbor = signer.signTransaction(unsignedTxCbor, buildResult.txBodyHash);
326
303
  }
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.
304
+ // Hash from the signed bytes, so the row can name the tx before anyone has seen it.
329
305
  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.
306
+ // Last fence before the irreversible part: another instance owning the wallet now
307
+ // may spend the same UTxOs. Nothing has been sent, so standing down costs only a rebuild.
334
308
  if (!(await heartbeat.fence())) {
335
309
  logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing — NOT submitting tx ${txHash}`);
336
310
  return;
337
311
  }
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.
312
+ // Point of no return: commit the signed tx BEFORE it can reach a backend. The guard on
313
+ // `building` is the second half of the fence: a row already failed by a takeover returns false.
343
314
  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
315
  if (!stored) {
345
316
  logger.warn(`Job ${job.ID}: submitting transition was fenced — not submitting (another executor owns this job)`);
@@ -357,13 +328,9 @@ class CardanoWalletWorker {
357
328
  }
358
329
  }
359
330
  /**
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.
331
+ * Send a tx already durable in its `submitting` row and advance to `submitted`. A submit failure
332
+ * never fails the job here (one rejection does not prove absence from every mempool); the row
333
+ * stays `submitting` for the next tick's reconciliation.
367
334
  */
368
335
  async submitStoredTransaction(job, tx) {
369
336
  let submittedHash;
@@ -375,7 +342,7 @@ class CardanoWalletWorker {
375
342
  return;
376
343
  }
377
344
  if (job.kind !== 'submitSigned') {
378
- // Observability parity with the synchronous flow: record the submission row.
345
+ // Record the submission row as the synchronous flow does.
379
346
  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
347
  }
381
348
  await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor);
@@ -397,30 +364,16 @@ class CardanoWalletWorker {
397
364
  });
398
365
  }
399
366
  /**
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.
367
+ * Resolve a `submitting` job with an unknown submit outcome; the stored tx is re-submitted verbatim,
368
+ * never rebuilt. Order: re-submit (already-known = success) → chain lookup (found = promote) →
369
+ * fail only when proven absent AND rejected for good or past the confirmation timeout; else retry next tick.
416
370
  */
417
371
  async reconcileSubmitting(job) {
418
372
  const { instanceId } = this.deps;
419
373
  const heartbeat = this.leaseHeartbeat(job.walletId);
420
374
  try {
421
375
  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.
376
+ // Cannot happen via markSubmitting; treat as never sent rather than blocking the wallet queue forever.
424
377
  logger.error(`Job ${job.ID}: submitting row without signed transaction — failing as PROCESS_RESTART`);
425
378
  await this.failReconciled(job, job_store_1.JOB_ERROR_CODES.PROCESS_RESTART, new Error('Job was interrupted before its signed transaction was stored.'));
426
379
  return;
@@ -436,11 +389,15 @@ class CardanoWalletWorker {
436
389
  catch (err) {
437
390
  submitError = err;
438
391
  }
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.
392
+ // A rejection may mean the tx is already on-chain (inputs spent), so the chain decides.
441
393
  let onChain;
442
394
  try {
443
- await this.deps.client.getTransaction(job.txHash);
395
+ // the local index first (filled by the crawler), then the backends
396
+ const txHash = job.txHash;
397
+ const indexed = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => this.deps.indexer.findIndexedTransaction(t, txHash)));
398
+ if (!indexed) {
399
+ await this.deps.client.getTransaction(txHash);
400
+ }
444
401
  onChain = true;
445
402
  }
446
403
  catch (lookupErr) {
@@ -461,9 +418,7 @@ class CardanoWalletWorker {
461
418
  logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain — retrying next tick:`, submitError);
462
419
  return;
463
420
  }
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.
421
+ // Proven absent and not submittable anymore: releasing the idempotency key is safe.
467
422
  const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
468
423
  logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}) — failing:`, submitError);
469
424
  await this.failReconciled(job, code, submitError);
@@ -494,11 +449,7 @@ class CardanoWalletWorker {
494
449
  throw new errors_1.BackendError(`Unsupported job kind "${job.kind}"`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
495
450
  }
496
451
  }
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
- */
452
+ /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
502
453
  async submitWithAlreadyKnownTolerance(signedTxCbor) {
503
454
  try {
504
455
  return await this.deps.client.submitTransaction(signedTxCbor);
@@ -513,10 +464,8 @@ class CardanoWalletWorker {
513
464
  }
514
465
  }
515
466
  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.
467
+ // Only a pre-submit (`building`) job may be re-queued or failed here; a `submitting` row's
468
+ // tx may be in a mempool, so it goes to reconciliation.
520
469
  const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
521
470
  .catch(() => null);
522
471
  if (current && current.status !== 'building') {
@@ -0,0 +1,146 @@
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Agent Service (v2.0)
5
+ *
6
+ * Agent grants: scoped, budgeted bearer capabilities an Admin hands to an agent
7
+ * instead of a full user.
8
+ *
9
+ * - CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken / RevokeAgentGrant:
10
+ * Admin-only administration, rate limited per principal per hour
11
+ * (AGENT_GRANT_ADMIN_RATE_LIMIT, default 10). The token is returned ONCE from
12
+ * CreateAgentGrant and RotateAgentGrantToken and stored as SHA-256 only.
13
+ * - AgentGrants: Admin-only projection (no token hash). A request carrying a token
14
+ * runs as the principal `agent:<grantId>` with the role `agent-grant` and sees
15
+ * exactly its own row through the row-level restriction below.
16
+ * - GetGrantStatus: token self-service — what am I allowed to do, how much budget
17
+ * is left, when do I expire. What an MCP tool needs to describe itself honestly.
18
+ * - GetGrantUsage: admitted calls per service and action over a window — an Admin
19
+ * for any grant, a token for its own (a partner usage view, ledger reconciliation).
20
+ *
21
+ * A token request never inherits the operator's roles: `@requires: 'Admin'` on the
22
+ * four actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
23
+ * every other Admin surface therefore refuses it by construction. The allow list,
24
+ * wallet pinning and daily budget are enforced by a before('*') hook on all six
25
+ * ODATANO services (srv/utils/agent-grants.ts). The `x-agent-token` header only
26
+ * reaches the services when cds.requires.odatano-core.agentGrants.enabled is set
27
+ * (srv/utils/agent-token-auth.ts).
28
+ */
29
+ @requires: 'authenticated-user'
30
+ service CardanoAgentService @(impl: './cardano-agent-service') {
31
+
32
+ @readonly
33
+ @title : 'Agent Grants'
34
+ @description: 'Issued grants (token hash excluded). Admins see all, a token sees its own row.'
35
+ @restrict : [
36
+ { grant: 'READ', to: 'Admin' },
37
+ { grant: 'READ', to: 'agent-grant', where: 'ID = $user.grantId' }
38
+ ]
39
+ entity AgentGrants as projection on db.CardanoAgentGrants excluding { tokenHash };
40
+
41
+ @title : 'Grant Status'
42
+ type GrantStatus {
43
+ grantId : UUID;
44
+ agentLabel : String(100);
45
+ allowedActions : many String;
46
+ walletId : String(50);
47
+ allowedJobKinds : many String;
48
+ maxJobsPerDay : Integer;
49
+ jobsUsedToday : Integer;
50
+ budgetWindow : String(10);
51
+ validUntil : Timestamp;
52
+ isActive : Boolean;
53
+ }
54
+
55
+ @title : 'Issued Grant'
56
+ type IssuedGrant {
57
+ grantId : UUID;
58
+ token : String; // shown once, never stored
59
+ allowedActions : many String;
60
+ walletId : String(50);
61
+ allowedJobKinds : many String;
62
+ maxJobsPerDay : Integer;
63
+ validUntil : Timestamp;
64
+ }
65
+
66
+ @title : 'Get Grant Status'
67
+ @description: 'The calling token''s own grant: allow list, wallet, remaining daily budget, expiry. 400 without a token — an operator lists AgentGrants instead.'
68
+ function GetGrantStatus() returns GrantStatus;
69
+
70
+ @title : 'Create Agent Grant'
71
+ @description: 'Issue a scoped bearer token for an agent. Admin only. The token is returned once and stored as SHA-256. allowedActions must be a non-empty subset of the grantable set; walletId is required when SubmitWalletJob or CancelJob is allowed.'
72
+ @requires : 'Admin'
73
+ action CreateAgentGrant(
74
+ @title: 'Allowed Actions' allowedActions : many String,
75
+ @title: 'Wallet Id' walletId : String(50),
76
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
77
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
78
+ @title: 'Valid Until' validUntil : Timestamp,
79
+ @title: 'Agent Label' agentLabel : String(100)
80
+ ) returns IssuedGrant;
81
+
82
+ @title : 'Revoke Agent Grant'
83
+ @description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
84
+ @requires : 'Admin'
85
+ action RevokeAgentGrant(
86
+ @title: 'Grant Id' grantId : UUID
87
+ ) returns Boolean;
88
+
89
+ @title : 'Rotated Grant'
90
+ type RotatedGrant {
91
+ grantId : UUID;
92
+ token : String; // shown once, never stored
93
+ }
94
+
95
+ @title : 'Rotate Agent Grant Token'
96
+ @description: 'Replace the grant token; the old token is unknown from the next request. Budget, wallet, allow list and expiry survive. Admin only. 404 when the grant does not exist or is revoked.'
97
+ @requires : 'Admin'
98
+ action RotateAgentGrantToken(
99
+ @title: 'Grant Id' grantId : UUID
100
+ ) returns RotatedGrant;
101
+
102
+ @title : 'Updated Grant'
103
+ type UpdatedGrant {
104
+ grantId : UUID;
105
+ updated : many String; // parameter names that were applied
106
+ }
107
+
108
+ @title : 'Update Agent Grant'
109
+ @description: 'Change label, allow list, job kinds, daily budget or expiry of an active grant. An absent parameter stays as it is; an explicit null clears agentLabel, allowedJobKinds, maxJobsPerDay or validUntil. allowedActions cannot be emptied; the wallet binding is immutable (issue a new grant). Admin only. 404 unknown grant, 409 GRANT_REVOKED.'
110
+ @requires : 'Admin'
111
+ action UpdateAgentGrant(
112
+ @title: 'Grant Id' grantId : UUID,
113
+ @title: 'Agent Label' agentLabel : String(100),
114
+ @title: 'Allowed Actions' allowedActions : many String,
115
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
116
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
117
+ @title: 'Valid Until' validUntil : Timestamp
118
+ ) returns UpdatedGrant;
119
+
120
+ @title : 'Grant Usage Call'
121
+ type GrantUsageCall {
122
+ service : String(60); // CardanoTransactionService, CardanoSignService, ...
123
+ action : String(100); // BuildSimpleAdaTransaction, SubmitTransaction, ...
124
+ count : Integer; // admitted and kept (budget charged and not refunded)
125
+ refunded : Integer; // admitted, then refunded because the handler refused the input
126
+ }
127
+
128
+ @title : 'Grant Usage'
129
+ type GrantUsage {
130
+ grantId : UUID;
131
+ since : Timestamp;
132
+ until : Timestamp;
133
+ calls : many GrantUsageCall;
134
+ total : Integer;
135
+ jobsUsedToday : Integer;
136
+ maxJobsPerDay : Integer;
137
+ }
138
+
139
+ @title : 'Get Grant Usage'
140
+ @description: 'Admitted calls under a grant between since (default until - 30 days) and until (default now), at most 366 days, per UTC day, grouped by service and action. An Admin sees any grant (revoked ones keep their history); a token sees only its own.'
141
+ function GetGrantUsage(
142
+ @title: 'Grant Id' grantId : UUID,
143
+ @title: 'Since' since : Timestamp,
144
+ @title: 'Until' until : Timestamp
145
+ ) returns GrantUsage;
146
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-agent-service.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const agent_grants_1 = require("./utils/agent-grants");
4
+ /**
5
+ * CardanoAgentService handlers. Grant administration and token self-service live in
6
+ * srv/utils/agent-grants.ts so the OData actions and the programmatic API share one path.
7
+ * The token enforcement hook is attached to all services from src/plugin.ts, not here.
8
+ */
9
+ module.exports = (srv) => {
10
+ (0, agent_grants_1.registerAgentGrantHandlers)(srv);
11
+ };
12
+ //# sourceMappingURL=cardano-agent-service.js.map