@odatano/core 2.0.0-rc.43 → 2.0.0-rc.45

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 (171) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +36 -20
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +19 -47
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  7. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  8. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  9. package/@cds-models/index.d.ts +17 -0
  10. package/@cds-models/index.js +2 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +1 -34
  12. package/README.md +6 -6
  13. package/db/schema.cds +29 -44
  14. package/db/types.cds +22 -5
  15. package/package.json +3 -1
  16. package/scripts/migrate-slot-leader.mjs +3 -11
  17. package/scripts/migrate-txseq.mjs +3 -12
  18. package/src/index.d.ts +0 -4
  19. package/src/index.js +3 -5
  20. package/src/plugin.js +4 -8
  21. package/srv/blockchain/asset-decimals.d.ts +7 -0
  22. package/srv/blockchain/asset-decimals.js +91 -0
  23. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  24. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  25. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  26. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  27. package/srv/blockchain/backends/koios-backend.js +40 -164
  28. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  29. package/srv/blockchain/backends/odatano-backend.js +11 -12
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  31. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  32. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  33. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  34. package/srv/blockchain/cardano-client.d.ts +12 -80
  35. package/srv/blockchain/cardano-client.js +36 -88
  36. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  37. package/srv/blockchain/cardano-indexer.js +132 -222
  38. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  39. package/srv/blockchain/cardano-tx-builder.js +17 -34
  40. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  41. package/srv/blockchain/circuit-breaker.js +5 -15
  42. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  43. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  45. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  46. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  47. package/srv/blockchain/crawler/crawler.js +85 -160
  48. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -9
  49. package/srv/blockchain/crawler/credential-backfill.js +6 -6
  50. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  51. package/srv/blockchain/crawler/index.d.ts +0 -12
  52. package/srv/blockchain/crawler/index.js +6 -20
  53. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  54. package/srv/blockchain/crawler/sync-state.js +18 -53
  55. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  56. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  57. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  58. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  59. package/srv/blockchain/ledger-state.d.ts +10 -54
  60. package/srv/blockchain/ledger-state.js +11 -27
  61. package/srv/blockchain/pending-spends.d.ts +0 -12
  62. package/srv/blockchain/pending-spends.js +4 -12
  63. package/srv/blockchain/request-coalescer.d.ts +2 -16
  64. package/srv/blockchain/request-coalescer.js +2 -16
  65. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  66. package/srv/blockchain/signing/cose-verifier.js +4 -10
  67. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  68. package/srv/blockchain/signing/external-signer.js +2 -8
  69. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  70. package/srv/blockchain/signing/hsm-signer.js +16 -28
  71. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  72. package/srv/blockchain/signing/signature-verifier.js +9 -19
  73. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  74. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  75. package/srv/blockchain/stored-chain.d.ts +1 -14
  76. package/srv/blockchain/stored-chain.js +3 -8
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  78. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  79. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  80. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  81. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  82. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  83. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  84. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  85. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  87. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  88. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  89. package/srv/blockchain/wallet-worker/index.js +3 -5
  90. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  91. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  93. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  94. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  95. package/srv/blockchain/wallet-worker/signers.js +3 -6
  96. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  97. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  98. package/srv/cardano-agent-service.cds +123 -146
  99. package/srv/cardano-agent-service.js +2 -5
  100. package/srv/cardano-backend-service.cds +10 -17
  101. package/srv/cardano-backend-service.js +7 -12
  102. package/srv/cardano-indexer-service.cds +35 -37
  103. package/srv/cardano-indexer-service.d.ts +5 -1
  104. package/srv/cardano-indexer-service.js +64 -33
  105. package/srv/cardano-service.cds +56 -40
  106. package/srv/cardano-service.js +42 -69
  107. package/srv/cardano-sign-service.cds +14 -23
  108. package/srv/cardano-sign-service.js +18 -24
  109. package/srv/cardano-tx-service.cds +27 -29
  110. package/srv/cardano-tx-service.js +60 -122
  111. package/srv/cardano-worker-service.cds +109 -125
  112. package/srv/cardano-worker-service.js +21 -31
  113. package/srv/cbor/cip68.d.ts +13 -0
  114. package/srv/cbor/cip68.js +56 -0
  115. package/srv/cbor/index.d.ts +1 -0
  116. package/srv/cbor/index.js +6 -1
  117. package/srv/cbor/parse.d.ts +3 -18
  118. package/srv/cbor/parse.js +2 -7
  119. package/srv/cbor/plutus-data-json.d.ts +0 -4
  120. package/srv/server.d.ts +5 -36
  121. package/srv/server.js +30 -51
  122. package/srv/utils/agent-grants-config.d.ts +0 -18
  123. package/srv/utils/agent-grants-config.js +6 -13
  124. package/srv/utils/agent-grants.d.ts +14 -68
  125. package/srv/utils/agent-grants.js +42 -60
  126. package/srv/utils/agent-token-auth.d.ts +0 -5
  127. package/srv/utils/agent-token-auth.js +2 -5
  128. package/srv/utils/backend-request-handler.d.ts +1 -1
  129. package/srv/utils/collections.d.ts +1 -4
  130. package/srv/utils/collections.js +1 -4
  131. package/srv/utils/const.d.ts +0 -18
  132. package/srv/utils/const.js +7 -18
  133. package/srv/utils/crypto.js +3 -5
  134. package/srv/utils/db-indexes.d.ts +2 -0
  135. package/srv/utils/db-indexes.js +22 -9
  136. package/srv/utils/db-sanitize.d.ts +1 -8
  137. package/srv/utils/db-sanitize.js +3 -8
  138. package/srv/utils/epoch-slots.d.ts +1 -8
  139. package/srv/utils/epoch-slots.js +3 -8
  140. package/srv/utils/error-codes.d.ts +0 -4
  141. package/srv/utils/error-codes.js +2 -4
  142. package/srv/utils/errors.d.ts +2 -22
  143. package/srv/utils/errors.js +13 -27
  144. package/srv/utils/liveness.d.ts +0 -4
  145. package/srv/utils/liveness.js +2 -4
  146. package/srv/utils/mappers.d.ts +0 -37
  147. package/srv/utils/mappers.js +22 -39
  148. package/srv/utils/network-context.js +2 -4
  149. package/srv/utils/paging.d.ts +31 -0
  150. package/srv/utils/paging.js +43 -0
  151. package/srv/utils/pg-inline-json.js +3 -7
  152. package/srv/utils/pg-order-nulls.js +2 -5
  153. package/srv/utils/plutus-placeholders.d.ts +0 -13
  154. package/srv/utils/plutus-placeholders.js +6 -13
  155. package/srv/utils/rate-limiter.d.ts +0 -8
  156. package/srv/utils/rate-limiter.js +2 -4
  157. package/srv/utils/reference-script.d.ts +0 -18
  158. package/srv/utils/reference-script.js +8 -19
  159. package/srv/utils/service-events.d.ts +0 -4
  160. package/srv/utils/service-events.js +2 -4
  161. package/srv/utils/signing-helper.d.ts +1 -8
  162. package/srv/utils/signing-helper.js +3 -8
  163. package/srv/utils/tx-build-helper.d.ts +2 -32
  164. package/srv/utils/tx-build-helper.js +26 -40
  165. package/srv/utils/tx-request-parsers.d.ts +1 -25
  166. package/srv/utils/tx-request-parsers.js +10 -25
  167. package/srv/utils/tx-utils.d.ts +0 -8
  168. package/srv/utils/tx-utils.js +10 -13
  169. package/srv/utils/types.d.ts +2 -37
  170. package/srv/utils/validators.d.ts +0 -4
  171. package/srv/utils/validators.js +2 -4
@@ -1,11 +1,6 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { type WorkerSigner, type WorkerWalletConfig } from './signers';
4
- /**
5
- * Dispatch loop over `CardanoWalletJobs`: each tick leases every wallet with pending work and no active job
6
- * and runs building → submitting (signed CBOR committed BEFORE submit) → submitted → ConfirmationTracker.
7
- * After the `submitting` commit failures are reconciled against the chain, never rebuilt; transient pre-sign failures re-queue with backoff.
8
- */
9
4
  export interface WalletWorkerConfig {
10
5
  enabled: boolean;
11
6
  wallets: WorkerWalletConfig[];
@@ -35,7 +30,7 @@ export declare class CardanoWalletWorker {
35
30
  private readonly tracker;
36
31
  private dispatchTimer;
37
32
  private running;
38
- private ticking;
33
+ private tickInFlight;
39
34
  constructor(deps: WalletWorkerDeps);
40
35
  isRunning(): boolean;
41
36
  /** Wallets this instance can sign for (signer init succeeded). */
@@ -59,25 +54,12 @@ export declare class CardanoWalletWorker {
59
54
  private spawn;
60
55
  /** A heartbeat that keeps this instance's lease on `walletId` alive while it works. */
61
56
  private leaseHeartbeat;
62
- /**
63
- * Execute one job: building → (build → sign) → submitting → submit → submitted → tracker.
64
- * The wallet lease is heartbeat-renewed for the duration. Up to the `submitting` commit failures
65
- * re-queue or fail normally; past it the job belongs to `reconcileSubmitting`.
66
- */
57
+ /** Builds, signs and submits one job under a renewed wallet lease. After the submitting commit, reconcileSubmitting owns it. */
67
58
  private executeJob;
68
- /**
69
- * Send a tx already durable in its `submitting` row and advance to `submitted`. A submit failure
70
- * never fails the job here (one rejection does not prove absence from every mempool); the row
71
- * stays `submitting` for the next tick's reconciliation.
72
- */
59
+ /** Sends the stored tx. A failed submit leaves the row submitting, since one rejection proves nothing. */
73
60
  private submitStoredTransaction;
74
61
  /** submitting → submitted + hand to the confirmation tracker. */
75
62
  private adoptSubmitted;
76
- /**
77
- * Resolve a `submitting` job with an unknown submit outcome; the stored tx is re-submitted verbatim,
78
- * never rebuilt. Order: re-submit (already-known = success) → chain lookup (found = promote) →
79
- * fail only when proven absent AND rejected for good or past the confirmation timeout; else retry next tick.
80
- */
81
63
  private reconcileSubmitting;
82
64
  private failReconciled;
83
65
  /** Dispatch the job kind to the matching indexer build method. */
@@ -10,12 +10,14 @@ const cds_1 = __importDefault(require("@sap/cds"));
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
12
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
14
  const confirmation_tracker_1 = require("./confirmation-tracker");
14
15
  const lease_heartbeat_1 = require("./lease-heartbeat");
15
16
  const build_request_1 = require("./build-request");
16
17
  const service_events_1 = require("../../utils/service-events");
17
18
  const signers_1 = require("./signers");
18
19
  const job_store_1 = require("./job-store");
20
+ const { SELECT } = cds_1.default.ql;
19
21
  const logger = cds_1.default.log('CardanoWalletWorker');
20
22
  /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
21
23
  function retryBackoffMs(attempt) {
@@ -48,7 +50,7 @@ class CardanoWalletWorker {
48
50
  tracker;
49
51
  dispatchTimer = null;
50
52
  running = false;
51
- ticking = false;
53
+ tickInFlight = null;
52
54
  constructor(deps) {
53
55
  this.deps = deps;
54
56
  this.tracker = new confirmation_tracker_1.ConfirmationTracker({
@@ -60,7 +62,7 @@ class CardanoWalletWorker {
60
62
  resubmitOnRollback: deps.config.resubmitOnRollback,
61
63
  },
62
64
  onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
63
- logger.debug(`Wallet ${walletId} unblocked (job ${outcome}) — next tick dispatches`);
65
+ logger.debug(`Wallet ${walletId} unblocked (job ${outcome}), next tick dispatches`);
64
66
  // Terminal outcomes only, after the commit, so subscribers reading the row see the announced state.
65
67
  (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
66
68
  jobId,
@@ -99,7 +101,7 @@ class CardanoWalletWorker {
99
101
  logger.warn('Wallet worker refused to start: no wallets configured');
100
102
  return;
101
103
  }
102
- // 1. Initialize signers — a broken wallet config skips that wallet, not the worker.
104
+ // 1. Initialize signers. A broken wallet config skips that wallet, not the worker.
103
105
  for (const walletCfg of this.deps.config.wallets) {
104
106
  try {
105
107
  const signer = (0, signers_1.createWorkerSigner)(walletCfg, this.deps.network);
@@ -112,7 +114,7 @@ class CardanoWalletWorker {
112
114
  }));
113
115
  }
114
116
  catch (err) {
115
- logger.error(`Wallet "${walletCfg.walletId}" skipped — signer initialization failed:`, err);
117
+ logger.error(`Wallet "${walletCfg.walletId}" skipped, signer initialization failed:`, err);
116
118
  }
117
119
  }
118
120
  if (this.signers.size === 0) {
@@ -156,7 +158,8 @@ class CardanoWalletWorker {
156
158
  this.dispatchTimer = null;
157
159
  }
158
160
  this.tracker.stop();
159
- // Await in-flight executions so teardown never races a write.
161
+ // A running tick may still spawn work; let it finish, then await every execution.
162
+ await this.tickInFlight;
160
163
  await Promise.allSettled([...this.executionPromises]);
161
164
  for (const walletId of this.getWalletIds()) {
162
165
  try {
@@ -170,18 +173,12 @@ class CardanoWalletWorker {
170
173
  }
171
174
  /** One dispatch round; serialized (overlapping timers collapse into one run). */
172
175
  async tickSafe() {
173
- if (!this.running || this.ticking)
176
+ if (!this.running || this.tickInFlight)
174
177
  return;
175
- this.ticking = true;
176
- try {
177
- await this.tick();
178
- }
179
- catch (err) {
180
- logger.error('Wallet worker dispatch tick failed:', err);
181
- }
182
- finally {
183
- this.ticking = false;
184
- }
178
+ this.tickInFlight = this.tick()
179
+ .catch((err) => logger.error('Wallet worker dispatch tick failed:', err))
180
+ .finally(() => { this.tickInFlight = null; });
181
+ await this.tickInFlight;
185
182
  }
186
183
  async tick() {
187
184
  // Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
@@ -206,8 +203,8 @@ class CardanoWalletWorker {
206
203
  if (!signer)
207
204
  continue; // job for a wallet this instance cannot sign for
208
205
  const dispatched = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
209
- // A building row whose wallet lease expired belongs to a dead executor — fail it
210
- // so the wallet unblocks without a reboot.
206
+ // A building row with an expired lease belongs to a dead executor.
207
+ // Failing it unblocks the wallet without a reboot.
211
208
  await (0, job_store_1.failOrphanedBuildingJobs)(tx, walletId);
212
209
  // An active job blocks the wallet queue until the tracker finalizes it.
213
210
  if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
@@ -242,6 +239,9 @@ class CardanoWalletWorker {
242
239
  }
243
240
  /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
244
241
  spawn(walletId, work) {
242
+ // stop() began after the lease was taken; stop() releases it
243
+ if (!this.running)
244
+ return;
245
245
  this.executing.add(walletId);
246
246
  const execution = work()
247
247
  .catch((err) => logger.error(`Wallet ${walletId}: unhandled execution error:`, err))
@@ -258,11 +258,7 @@ class CardanoWalletWorker {
258
258
  heartbeat.start();
259
259
  return heartbeat;
260
260
  }
261
- /**
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`.
265
- */
261
+ /** Builds, signs and submits one job under a renewed wallet lease. After the submitting commit, reconcileSubmitting owns it. */
266
262
  async executeJob(job, signer) {
267
263
  const { instanceId } = this.deps;
268
264
  const attempt = job.attempt + 1;
@@ -284,7 +280,7 @@ class CardanoWalletWorker {
284
280
  }
285
281
  else {
286
282
  const rawReq = JSON.parse(job.request ?? '{}');
287
- // The worker wallet is ALWAYS the sender/change target — no spending from foreign addresses.
283
+ // The worker wallet is always the sender and change target. It never spends from foreign addresses.
288
284
  rawReq.network = this.deps.network;
289
285
  rawReq.senderAddress = signer.getAddress();
290
286
  if (!rawReq.changeAddress)
@@ -292,7 +288,7 @@ class CardanoWalletWorker {
292
288
  const buildReq = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, rawReq, this.deps.network);
293
289
  // Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
294
290
  if (!(await heartbeat.fence())) {
295
- logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build — aborting execution`);
291
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build, aborting execution`);
296
292
  return;
297
293
  }
298
294
  const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => this.buildForKind(tx, job, buildReq)));
@@ -306,14 +302,14 @@ class CardanoWalletWorker {
306
302
  // Last fence before the irreversible part: another instance owning the wallet now
307
303
  // may spend the same UTxOs. Nothing has been sent, so standing down costs only a rebuild.
308
304
  if (!(await heartbeat.fence())) {
309
- logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing — NOT submitting tx ${txHash}`);
305
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing, NOT submitting tx ${txHash}`);
310
306
  return;
311
307
  }
312
308
  // Point of no return: commit the signed tx BEFORE it can reach a backend. The guard on
313
309
  // `building` is the second half of the fence: a row already failed by a takeover returns false.
314
310
  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 })));
315
311
  if (!stored) {
316
- logger.warn(`Job ${job.ID}: submitting transition was fenced — not submitting (another executor owns this job)`);
312
+ logger.warn(`Job ${job.ID}: submitting transition was fenced, not submitting (another executor owns this job)`);
317
313
  return;
318
314
  }
319
315
  await this.submitStoredTransaction(job, { txHash, signedTxCbor, buildId, attempt });
@@ -327,32 +323,32 @@ class CardanoWalletWorker {
327
323
  .catch(() => undefined);
328
324
  }
329
325
  }
330
- /**
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.
334
- */
326
+ /** Sends the stored tx. A failed submit leaves the row submitting, since one rejection proves nothing. */
335
327
  async submitStoredTransaction(job, tx) {
336
328
  let submittedHash;
337
329
  try {
338
330
  submittedHash = await this.submitWithAlreadyKnownTolerance(tx.signedTxCbor);
339
331
  }
340
332
  catch (err) {
341
- logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash} — job stays submitting for chain reconciliation:`, err);
333
+ logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash}, job stays submitting for chain reconciliation:`, err);
342
334
  return;
343
335
  }
344
- if (job.kind !== 'submitSigned') {
345
- // Record the submission row as the synchronous flow does.
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));
347
- }
348
- await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor);
336
+ await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor, tx.buildId);
349
337
  logger.info(`Job ${job.ID} (wallet ${job.walletId}, kind ${job.kind}): submitted as ${submittedHash} (attempt ${tx.attempt})`);
350
338
  }
351
339
  /** submitting → submitted + hand to the confirmation tracker. */
352
- async adoptSubmitted(job, txHash, signedTxCbor) {
340
+ async adoptSubmitted(job, txHash, signedTxCbor, buildId = null) {
341
+ if (job.kind !== 'submitSigned') {
342
+ // Record the submission row as the synchronous flow does, once per tx.
343
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (t) => {
344
+ const known = await t.run(SELECT.one.from(cardano_1.TransactionSubmissions).columns('id').where({ txHash }));
345
+ if (!known)
346
+ await this.deps.indexer.persistTransactionSubmission(t, { signedTxCbor, txHash, buildId, status: 'submitted' });
347
+ })).catch((err) => logger.warn(`Job ${job.ID}: submission bookkeeping failed (job continues):`, err));
348
+ }
353
349
  const submitted = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitted)(tx, job.ID, txHash)));
354
350
  if (!submitted) {
355
- logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced — tracker adopts the tx anyway`);
351
+ logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced, tracker adopts the tx anyway`);
356
352
  }
357
353
  this.tracker.track({
358
354
  jobId: job.ID,
@@ -363,18 +359,15 @@ class CardanoWalletWorker {
363
359
  submittedAt: job.submittedAt ?? new Date().toISOString(),
364
360
  });
365
361
  }
366
- /**
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.
370
- */
362
+ // Resolves a submitting job by re-submitting the stored tx, then looking it up on chain.
363
+ // Fails only when the tx is absent and rejected for good or timed out. Otherwise retries next tick.
371
364
  async reconcileSubmitting(job) {
372
365
  const { instanceId } = this.deps;
373
366
  const heartbeat = this.leaseHeartbeat(job.walletId);
374
367
  try {
375
368
  if (!job.signedTxCbor || !job.txHash) {
376
369
  // Cannot happen via markSubmitting; treat as never sent rather than blocking the wallet queue forever.
377
- logger.error(`Job ${job.ID}: submitting row without signed transaction — failing as PROCESS_RESTART`);
370
+ logger.error(`Job ${job.ID}: submitting row without signed transaction, failing as PROCESS_RESTART`);
378
371
  await this.failReconciled(job, job_store_1.JOB_ERROR_CODES.PROCESS_RESTART, new Error('Job was interrupted before its signed transaction was stored.'));
379
372
  return;
380
373
  }
@@ -383,7 +376,7 @@ class CardanoWalletWorker {
383
376
  try {
384
377
  const txHash = await this.submitWithAlreadyKnownTolerance(job.signedTxCbor);
385
378
  await this.adoptSubmitted(job, txHash, job.signedTxCbor);
386
- logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}) — now awaiting confirmation`);
379
+ logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}), now awaiting confirmation`);
387
380
  return;
388
381
  }
389
382
  catch (err) {
@@ -402,25 +395,25 @@ class CardanoWalletWorker {
402
395
  }
403
396
  catch (lookupErr) {
404
397
  if (!(0, errors_1.isNotFoundOnAllBackends)(lookupErr)) {
405
- logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive — retrying next tick:`, lookupErr);
398
+ logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive, retrying next tick:`, lookupErr);
406
399
  return;
407
400
  }
408
401
  onChain = false;
409
402
  }
410
403
  if (onChain) {
411
- logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit — awaiting confirmation`);
404
+ logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit, awaiting confirmation`);
412
405
  await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
413
406
  return;
414
407
  }
415
408
  const ageMs = job.submittedAt ? Date.now() - Date.parse(job.submittedAt) : 0;
416
409
  const expired = ageMs > this.deps.config.confirmationTimeoutMs;
417
410
  if (isTransientJobError(submitError) && !expired) {
418
- logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain — retrying next tick:`, submitError);
411
+ logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain, retrying next tick:`, submitError);
419
412
  return;
420
413
  }
421
414
  // Proven absent and not submittable anymore: releasing the idempotency key is safe.
422
415
  const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
423
- logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}) — failing:`, submitError);
416
+ logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}), failing:`, submitError);
424
417
  await this.failReconciled(job, code, submitError);
425
418
  }
426
419
  finally {
@@ -457,7 +450,7 @@ class CardanoWalletWorker {
457
450
  catch (err) {
458
451
  if (err instanceof errors_1.TransactionAlreadySubmittedError) {
459
452
  const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
460
- logger.info(`Submit reported tx already known — treating as success (${txHash})`);
453
+ logger.info(`Submit reported tx already known, treating as success (${txHash})`);
461
454
  return txHash;
462
455
  }
463
456
  throw err;
@@ -469,12 +462,12 @@ class CardanoWalletWorker {
469
462
  const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
470
463
  .catch(() => null);
471
464
  if (current && current.status !== 'building') {
472
- logger.error(`Job ${job.ID}: execution error while ${current.status} — leaving the outcome to reconciliation:`, err);
465
+ logger.error(`Job ${job.ID}: execution error while ${current.status}, leaving the outcome to reconciliation:`, err);
473
466
  return;
474
467
  }
475
468
  if (isTransientJobError(err) && attempt < job.maxAttempts) {
476
469
  const backoff = retryBackoffMs(attempt);
477
- logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts} — retrying in ${backoff}ms:`, err);
470
+ logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts}, retrying in ${backoff}ms:`, err);
478
471
  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));
479
472
  return;
480
473
  }
@@ -1,146 +1,123 @@
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
- }
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ // Agent grants: scoped, budgeted bearer tokens an Admin issues instead of a full user.
4
+ // A token request runs as `agent:<grantId>` with the role `agent-grant`, so every Admin gate refuses it.
5
+ // The allow list, wallet binding and daily budget are enforced in srv/utils/agent-grants.ts.
6
+ @requires: 'authenticated-user'
7
+ service CardanoAgentService @(impl: './cardano-agent-service') {
8
+
9
+ @readonly
10
+ @title : 'Agent Grants'
11
+ @description: 'Issued grants (token hash excluded). Admins see all, a token sees its own row.'
12
+ @restrict : [
13
+ { grant: 'READ', to: 'Admin' },
14
+ { grant: 'READ', to: 'agent-grant', where: 'ID = $user.grantId' }
15
+ ]
16
+ entity AgentGrants as projection on db.CardanoAgentGrants excluding { tokenHash };
17
+
18
+ @title : 'Grant Status'
19
+ type GrantStatus {
20
+ grantId : UUID;
21
+ agentLabel : String(100);
22
+ allowedActions : many String;
23
+ walletId : String(50);
24
+ allowedJobKinds : many String;
25
+ maxJobsPerDay : Integer;
26
+ jobsUsedToday : Integer;
27
+ budgetWindow : String(10);
28
+ validUntil : Timestamp;
29
+ isActive : Boolean;
30
+ }
31
+
32
+ @title : 'Issued Grant'
33
+ type IssuedGrant {
34
+ grantId : UUID;
35
+ token : String; // shown once, never stored
36
+ allowedActions : many String;
37
+ walletId : String(50);
38
+ allowedJobKinds : many String;
39
+ maxJobsPerDay : Integer;
40
+ validUntil : Timestamp;
41
+ }
42
+
43
+ @title : 'Get Grant Status'
44
+ @description: 'The calling token''s own grant: allow list, wallet, remaining daily budget, expiry. 400 without a token; an operator lists AgentGrants instead.'
45
+ function GetGrantStatus() returns GrantStatus;
46
+
47
+ @title : 'Create Agent Grant'
48
+ @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.'
49
+ @requires : 'Admin'
50
+ action CreateAgentGrant(
51
+ @title: 'Allowed Actions' allowedActions : many String,
52
+ @title: 'Wallet Id' walletId : String(50),
53
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
54
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
55
+ @title: 'Valid Until' validUntil : Timestamp,
56
+ @title: 'Agent Label' agentLabel : String(100)
57
+ ) returns IssuedGrant;
58
+
59
+ @title : 'Revoke Agent Grant'
60
+ @description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
61
+ @requires : 'Admin'
62
+ action RevokeAgentGrant(
63
+ @title: 'Grant Id' grantId : UUID
64
+ ) returns Boolean;
65
+
66
+ @title : 'Rotated Grant'
67
+ type RotatedGrant {
68
+ grantId : UUID;
69
+ token : String; // shown once, never stored
70
+ }
71
+
72
+ @title : 'Rotate Agent Grant Token'
73
+ @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.'
74
+ @requires : 'Admin'
75
+ action RotateAgentGrantToken(
76
+ @title: 'Grant Id' grantId : UUID
77
+ ) returns RotatedGrant;
78
+
79
+ @title : 'Updated Grant'
80
+ type UpdatedGrant {
81
+ grantId : UUID;
82
+ updated : many String; // parameter names that were applied
83
+ }
84
+
85
+ @title : 'Update Agent Grant'
86
+ @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.'
87
+ @requires : 'Admin'
88
+ action UpdateAgentGrant(
89
+ @title: 'Grant Id' grantId : UUID,
90
+ @title: 'Agent Label' agentLabel : String(100),
91
+ @title: 'Allowed Actions' allowedActions : many String,
92
+ @title: 'Allowed Job Kinds' allowedJobKinds : many String,
93
+ @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
94
+ @title: 'Valid Until' validUntil : Timestamp
95
+ ) returns UpdatedGrant;
96
+
97
+ @title : 'Grant Usage Call'
98
+ type GrantUsageCall {
99
+ service : String(60); // CardanoTransactionService, CardanoSignService, ...
100
+ action : String(100); // BuildSimpleAdaTransaction, SubmitTransaction, ...
101
+ count : Integer; // admitted and kept (budget charged and not refunded)
102
+ refunded : Integer; // admitted, then refunded because the handler refused the input
103
+ }
104
+
105
+ @title : 'Grant Usage'
106
+ type GrantUsage {
107
+ grantId : UUID;
108
+ since : Timestamp;
109
+ until : Timestamp;
110
+ calls : many GrantUsageCall;
111
+ total : Integer;
112
+ jobsUsedToday : Integer;
113
+ maxJobsPerDay : Integer;
114
+ }
115
+
116
+ @title : 'Get Grant Usage'
117
+ @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.'
118
+ function GetGrantUsage(
119
+ @title: 'Grant Id' grantId : UUID,
120
+ @title: 'Since' since : Timestamp,
121
+ @title: 'Until' until : Timestamp
122
+ ) returns GrantUsage;
123
+ }
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
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
- */
4
+ // Handlers live in srv/utils/agent-grants.ts, shared with the programmatic API.
5
+ // The token enforcement hook is attached to all services in src/plugin.ts.
9
6
  module.exports = (srv) => {
10
7
  (0, agent_grants_1.registerAgentGrantHandlers)(srv);
11
8
  };