@odatano/core 2.0.0-rc.49 → 2.0.0-rc.50

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 (120) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +6 -12
  2. package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
  3. package/@cds-models/CardanoIndexerService/index.js +24 -0
  4. package/@cds-models/CardanoODataService/index.d.ts +49 -6
  5. package/@cds-models/CardanoODataService/index.js +4 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -3
  7. package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
  8. package/@cds-models/index.d.ts +9 -1
  9. package/@cds-models/index.js +2 -1
  10. package/@cds-models/odatano/cardano/index.d.ts +59 -5
  11. package/@cds-models/odatano/cardano/index.js +6 -0
  12. package/README.md +29 -17
  13. package/db/schema.cds +117 -24
  14. package/db/types.cds +8 -0
  15. package/package.json +17 -15
  16. package/scripts/migrate-schema.mjs +334 -0
  17. package/src/index.d.ts +7 -5
  18. package/src/index.js +12 -10
  19. package/src/plugin.js +6 -7
  20. package/srv/blockchain/backends/blockfrost-backend.js +9 -1
  21. package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
  22. package/srv/blockchain/backends/cardano-backend.js +5 -0
  23. package/srv/blockchain/backends/koios-backend.js +16 -10
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
  25. package/srv/blockchain/backends/ogmios-backend.js +60 -18
  26. package/srv/blockchain/cardano-client.d.ts +5 -4
  27. package/srv/blockchain/cardano-client.js +46 -13
  28. package/srv/blockchain/cardano-indexer.d.ts +116 -9
  29. package/srv/blockchain/cardano-indexer.js +436 -189
  30. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  31. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  32. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
  33. package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
  34. package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
  35. package/srv/blockchain/crawler/certificate-backfill.js +10 -3
  36. package/srv/blockchain/crawler/crawler.d.ts +15 -0
  37. package/srv/blockchain/crawler/crawler.js +68 -3
  38. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  39. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  40. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  41. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  42. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  43. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  44. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  45. package/srv/blockchain/crawler/transaction-backfill.js +12 -8
  46. package/srv/blockchain/pool-metadata.d.ts +15 -0
  47. package/srv/blockchain/pool-metadata.js +132 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
  49. package/srv/blockchain/signing/cose-verifier.js +144 -56
  50. package/srv/blockchain/signing/hsm-signer.js +2 -1
  51. package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
  52. package/srv/blockchain/signing/submission-finalizer.js +201 -69
  53. package/srv/blockchain/stored-chain.js +1 -1
  54. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
  55. package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
  56. package/srv/blockchain/transaction-presence.d.ts +5 -0
  57. package/srv/blockchain/transaction-presence.js +29 -0
  58. package/srv/blockchain/transaction-rows.js +1 -1
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
  60. package/srv/blockchain/wallet-worker/build-request.js +25 -0
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
  62. package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
  63. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  64. package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
  67. package/srv/cardano-agent-service.cds +11 -12
  68. package/srv/cardano-agent-service.js +2 -0
  69. package/srv/cardano-backend-service.cds +34 -1
  70. package/srv/cardano-backend-service.js +20 -17
  71. package/srv/cardano-indexer-service.cds +153 -12
  72. package/srv/cardano-indexer-service.js +175 -29
  73. package/srv/cardano-service.cds +67 -3
  74. package/srv/cardano-service.js +132 -67
  75. package/srv/cardano-sign-service.cds +30 -20
  76. package/srv/cardano-sign-service.js +13 -10
  77. package/srv/cardano-tx-service.cds +15 -1
  78. package/srv/cardano-tx-service.js +4 -1
  79. package/srv/cardano-worker-service.cds +16 -7
  80. package/srv/cardano-worker-service.js +31 -22
  81. package/srv/cbor/parse.js +11 -34
  82. package/srv/config.d.ts +113 -0
  83. package/srv/config.js +409 -0
  84. package/srv/server.d.ts +9 -14
  85. package/srv/server.js +32 -316
  86. package/srv/utils/agent-access.d.ts +9 -0
  87. package/srv/utils/agent-access.js +67 -0
  88. package/srv/utils/agent-grants-config.d.ts +0 -17
  89. package/srv/utils/agent-grants-config.js +6 -81
  90. package/srv/utils/agent-grants.d.ts +6 -19
  91. package/srv/utils/agent-grants.js +69 -130
  92. package/srv/utils/const.d.ts +4 -0
  93. package/srv/utils/const.js +5 -1
  94. package/srv/utils/db-indexes.js +11 -3
  95. package/srv/utils/error-codes.d.ts +4 -0
  96. package/srv/utils/error-codes.js +4 -0
  97. package/srv/utils/errors.d.ts +6 -0
  98. package/srv/utils/errors.js +23 -1
  99. package/srv/utils/liveness.js +2 -5
  100. package/srv/utils/mappers.d.ts +5 -7
  101. package/srv/utils/mappers.js +22 -9
  102. package/srv/utils/pg-order-nulls.js +4 -3
  103. package/srv/utils/readiness.d.ts +12 -0
  104. package/srv/utils/readiness.js +29 -0
  105. package/srv/utils/result-numbers.d.ts +15 -0
  106. package/srv/utils/result-numbers.js +61 -0
  107. package/srv/utils/tx-request-parsers.d.ts +1 -1
  108. package/srv/utils/tx-request-parsers.js +3 -3
  109. package/srv/utils/tx-utils.d.ts +3 -0
  110. package/srv/utils/tx-utils.js +17 -3
  111. package/srv/utils/types.d.ts +16 -3
  112. package/scripts/migrate-txseq.mjs +0 -138
  113. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
  114. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
  115. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
  116. package/srv/blockchain/transaction-building/caller-datums.js +0 -133
  117. package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
  118. package/srv/cbor/redeemer-tag-patch.js +0 -61
  119. package/srv/utils/legacy-service-paths.d.ts +0 -11
  120. package/srv/utils/legacy-service-paths.js +0 -58
@@ -0,0 +1,29 @@
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.isTransactionOnChain = isTransactionOnChain;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const errors_1 = require("../utils/errors");
9
+ const tx_utils_1 = require("../utils/tx-utils");
10
+ // True when the transaction is on chain, false when every backend answers not found, null when
11
+ // no configured backend can look transactions up. Throws when the lookup itself fails.
12
+ async function isTransactionOnChain(indexer, client, txHash) {
13
+ // the local index first (filled by the crawler), then the backends
14
+ const indexed = await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => indexer.findIndexedTransaction(t, txHash)));
15
+ if (indexed)
16
+ return true;
17
+ if (!client.supports('getTransaction'))
18
+ return null;
19
+ try {
20
+ await client.getTransaction(txHash);
21
+ return true;
22
+ }
23
+ catch (err) {
24
+ if ((0, errors_1.isNotFoundOnAllBackends)(err))
25
+ return false;
26
+ throw err;
27
+ }
28
+ }
29
+ //# sourceMappingURL=transaction-presence.js.map
@@ -28,7 +28,7 @@ async function deleteTransactionRows(tx, keys) {
28
28
  const hashes = keyChunk.map(k => k.hash);
29
29
  const seqs = keyChunk.filter(k => k.txSeq != null).map(k => k.txSeq);
30
30
  if (seqs.length) {
31
- await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: { in: seqs } }));
31
+ await tx.run(DELETE.from(cardano_1.TransactionInputAssetCopies).where({ input_txSeq: { in: seqs } }));
32
32
  await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: { in: seqs } }));
33
33
  await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqs } }));
34
34
  await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: { in: seqs } }));
@@ -1,7 +1,10 @@
1
- import type { TxBuildRequest } from '../../utils/types';
1
+ import type { TxBuildPlutusRequest, TxBuildRequest } from '../../utils/types';
2
2
  import type { Network } from '../cardano-client';
3
3
  import type { WalletJobKindValue } from './job-store';
4
4
  type RawRequest = Record<string, unknown>;
5
+ /** Most recipients one payout job takes; the transaction size limit may be reached earlier. */
6
+ export declare const MAX_PAYOUT_OUTPUTS = 150;
7
+ export declare function preparePayoutRequest(raw: RawRequest): TxBuildPlutusRequest;
5
8
  /** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
6
9
  export declare function prepareWorkerBuildRequest(kind: WalletJobKindValue, raw: RawRequest, network: Network): TxBuildRequest;
7
10
  export {};
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_PAYOUT_OUTPUTS = void 0;
4
+ exports.preparePayoutRequest = preparePayoutRequest;
3
5
  exports.prepareWorkerBuildRequest = prepareWorkerBuildRequest;
4
6
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
5
7
  const errors_1 = require("../../utils/errors");
@@ -347,6 +349,29 @@ function preparePlutusSpend(raw, network) {
347
349
  delete clean.lockOnScript;
348
350
  return clean;
349
351
  }
352
+ /** Most recipients one payout job takes; the transaction size limit may be reached earlier. */
353
+ exports.MAX_PAYOUT_OUTPUTS = 150;
354
+ // payout: the outputs of `outputsJson` in the given order, paid from the wallet in one transaction.
355
+ // Entries read like those of BuildPlutusTransaction. No script runs.
356
+ function preparePayoutRequest(raw) {
357
+ requirePresent(raw, ['senderAddress', 'outputsJson']);
358
+ if (typeof raw.outputsJson !== 'string')
359
+ fail('outputsJson must be a JSON string');
360
+ const outputs = takeParsed((0, tx_request_parsers_1.parseOutputList)(raw.outputsJson, 'outputsJson', exports.MAX_PAYOUT_OUTPUTS));
361
+ if (!outputs)
362
+ fail('outputsJson must list at least one output');
363
+ return {
364
+ network: raw.network,
365
+ senderAddress: raw.senderAddress,
366
+ changeAddress: raw.changeAddress,
367
+ scriptInputs: [],
368
+ outputs,
369
+ forceInputs: takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson')),
370
+ protectInputs: takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.protectInputsJson, 'protectInputsJson')),
371
+ validityStartMs: raw.validityStartMs,
372
+ validityEndMs: raw.validityEndMs,
373
+ };
374
+ }
350
375
  /** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
351
376
  function prepareWorkerBuildRequest(kind, raw, network) {
352
377
  switch (kind) {
@@ -235,7 +235,7 @@ class ConfirmationTracker {
235
235
  await cds_1.default.tx(async (tx) => {
236
236
  transitioned = outcome === 'confirmed'
237
237
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
238
- : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
238
+ : await (0, job_store_1.markFailedAfterSend)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
239
239
  if (transitioned) {
240
240
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
241
241
  if (outcome === 'confirmed') {
@@ -10,7 +10,7 @@ export declare const JOB_ERROR_CODES: {
10
10
  readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
11
11
  };
12
12
  export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
13
- export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'submitSigned';
13
+ export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'payout' | 'submitSigned';
14
14
  export type WorkerSignerTypeValue = 'hsm' | 'software';
15
15
  export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
16
16
  /** Normalized, number-typed view of a job row. */
@@ -45,6 +45,7 @@ export interface WorkerWalletRow {
45
45
  signerType: WorkerSignerTypeValue;
46
46
  address: string | null;
47
47
  publicKeyHash: string | null;
48
+ requiresRole: string | null;
48
49
  enabled: boolean;
49
50
  leaseOwner: string | null;
50
51
  leaseUntil: string | null;
@@ -67,16 +68,23 @@ export interface InsertJobArgs {
67
68
  export interface InsertJobResult {
68
69
  jobId: string;
69
70
  status: WalletJobStatusValue;
70
- /** True when an idempotent retry matched an existing non-failed job. */
71
+ /** True when an idempotent retry matched the job that holds the key. */
71
72
  deduplicated: boolean;
72
73
  }
73
74
  /** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
74
75
  export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
75
- /** Inserts a job, or returns the active or confirmed job with the same dedup key. The UNIQUE constraint settles races. */
76
+ /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
76
77
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
77
78
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
78
- /** Pending jobs by priority and age. notBefore is filtered in JS, since NULL predicates differ per database. */
79
- export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
79
+ /** A due job's place in the dispatch order, without its payload. */
80
+ export interface DueJobRef {
81
+ ID: string;
82
+ walletId: string;
83
+ priority: number;
84
+ createdAt: string | null;
85
+ }
86
+ /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
87
+ export declare function findNextDueJob(db: CapTransaction, walletId: string, now?: Date): Promise<DueJobRef | null>;
80
88
  /** Number of pending jobs, due or not. */
81
89
  export declare function countPendingJobs(db: CapTransaction): Promise<number>;
82
90
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
@@ -85,7 +93,7 @@ export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJob
85
93
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
86
94
  /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
87
95
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
88
- /** Frees the idempotency key by pointing dedupKey at the job ID. Confirmed jobs keep their key. */
96
+ /** Frees the idempotency key by pointing dedupKey at the job ID. */
89
97
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
90
98
  /** pending → building. Increments the attempt counter. Returns false when lost. */
91
99
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
@@ -109,8 +117,9 @@ export declare function recordConfirmationPoint(db: CapTransaction, jobId: strin
109
117
  export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
110
118
  /** submitted → confirmed (depth reached). */
111
119
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
112
- /** Fails an active job and frees its key. Fail a submitted job only after checking the chain. */
120
+ /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
113
121
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
122
+ export declare function markFailedAfterSend(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
114
123
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
115
124
  export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
116
125
  export interface RecoveryResult {
@@ -130,6 +139,7 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
130
139
  signerType: WorkerSignerTypeValue;
131
140
  address: string;
132
141
  publicKeyHash: string;
142
+ requiresRole?: string | null;
133
143
  }): Promise<void>;
134
144
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
135
145
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
@@ -14,6 +14,8 @@ export interface WorkerWalletConfig {
14
14
  signerType: WorkerSignerTypeValue;
15
15
  /** software only. Env var with the Ed25519 key as 64 hex chars or AES-256-GCM `iv:authTag:ciphertext` in base64. */
16
16
  keyEnv?: string;
17
+ /** Role a caller needs to queue jobs for this wallet. Absent = any authenticated user. */
18
+ requiresRole?: string;
17
19
  }
18
20
  /** Replaces the vkey witnesses in the raw CBOR witness set with this one. Other entries and encoding stay. */
19
21
  export declare function mergeVkeyWitness(unsignedTxCbor: string, publicKeyHex: string, signatureHex: string): string;
@@ -62,6 +62,8 @@ export declare class CardanoWalletWorker {
62
62
  private adoptSubmitted;
63
63
  private reconcileSubmitting;
64
64
  private failReconciled;
65
+ /** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
66
+ private buildOf;
65
67
  /** Dispatch the job kind to the matching indexer build method. */
66
68
  private buildForKind;
67
69
  /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
@@ -10,6 +10,7 @@ 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 transaction_presence_1 = require("../transaction-presence");
13
14
  const cardano_1 = require("#cds-models/odatano/cardano");
14
15
  const confirmation_tracker_1 = require("./confirmation-tracker");
15
16
  const lease_heartbeat_1 = require("./lease-heartbeat");
@@ -111,6 +112,7 @@ class CardanoWalletWorker {
111
112
  signerType: walletCfg.signerType,
112
113
  address: signer.getAddress(),
113
114
  publicKeyHash: signer.getPublicKeyHash(),
115
+ requiresRole: walletCfg.requiresRole ?? null,
114
116
  }));
115
117
  }
116
118
  catch (err) {
@@ -183,35 +185,42 @@ class CardanoWalletWorker {
183
185
  async tick() {
184
186
  // Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
185
187
  await this.reconcileOrphanedSubmissions();
186
- const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findDueJobs)(tx)));
187
- if (!due.length)
188
+ // The next due job of every idle wallet this instance signs for: one row per wallet.
189
+ const idle = this.getWalletIds().filter(walletId => !this.executing.has(walletId));
190
+ if (!idle.length)
188
191
  return;
189
- // First runnable job per wallet, dispatch order (priority, createdAt) preserved.
190
- const nextPerWallet = new Map();
191
- for (const job of due) {
192
- if (!nextPerWallet.has(job.walletId))
193
- nextPerWallet.set(job.walletId, job);
194
- }
195
- for (const [walletId, job] of nextPerWallet) {
192
+ const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
193
+ const next = [];
194
+ for (const walletId of idle) {
195
+ const ref = await (0, job_store_1.findNextDueJob)(tx, walletId);
196
+ if (ref)
197
+ next.push(ref);
198
+ }
199
+ return next;
200
+ }));
201
+ // dispatch order across wallets: priority, then age
202
+ due.sort((a, b) => a.priority - b.priority || String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? '')));
203
+ for (const { ID, walletId } of due) {
196
204
  if (!this.running)
197
205
  return;
198
206
  if (this.executing.size >= this.deps.config.maxConcurrentWallets)
199
207
  return;
200
- if (this.executing.has(walletId))
201
- continue;
202
208
  const signer = this.signers.get(walletId);
203
209
  if (!signer)
204
- continue; // job for a wallet this instance cannot sign for
205
- const dispatched = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
210
+ continue;
211
+ const job = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
206
212
  // A building row with an expired lease belongs to a dead executor.
207
213
  // Failing it unblocks the wallet without a reboot.
208
214
  await (0, job_store_1.failOrphanedBuildingJobs)(tx, walletId);
209
215
  // An active job blocks the wallet queue until the tracker finalizes it.
210
216
  if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
211
- return false;
212
- return (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId);
217
+ return null;
218
+ const next = await (0, job_store_1.getJobById)(tx, ID);
219
+ if (next?.status !== 'pending')
220
+ return null;
221
+ return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId)) ? next : null;
213
222
  }));
214
- if (!dispatched)
223
+ if (!job)
215
224
  continue;
216
225
  this.spawn(walletId, () => this.executeJob(job, signer));
217
226
  }
@@ -285,13 +294,13 @@ class CardanoWalletWorker {
285
294
  rawReq.senderAddress = signer.getAddress();
286
295
  if (!rawReq.changeAddress)
287
296
  rawReq.changeAddress = signer.getAddress();
288
- const buildReq = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, rawReq, this.deps.network);
297
+ const build = this.buildOf(job, rawReq);
289
298
  // Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
290
299
  if (!(await heartbeat.fence())) {
291
300
  logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build, aborting execution`);
292
301
  return;
293
302
  }
294
- const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => this.buildForKind(tx, job, buildReq)));
303
+ const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(build));
295
304
  unsignedTxCbor = buildResult.unsignedTxCbor;
296
305
  fee = buildResult.fee ?? null;
297
306
  buildId = buildResult.id ?? null;
@@ -385,20 +394,12 @@ class CardanoWalletWorker {
385
394
  // A rejection may mean the tx is already on-chain (inputs spent), so the chain decides.
386
395
  let onChain;
387
396
  try {
388
- // the local index first (filled by the crawler), then the backends
389
- const txHash = job.txHash;
390
- const indexed = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => this.deps.indexer.findIndexedTransaction(t, txHash)));
391
- if (!indexed) {
392
- await this.deps.client.getTransaction(txHash);
393
- }
394
- onChain = true;
397
+ // null: no backend can look transactions up, so the re-submit above is the only evidence
398
+ onChain = await (0, transaction_presence_1.isTransactionOnChain)(this.deps.indexer, this.deps.client, job.txHash) === true;
395
399
  }
396
400
  catch (lookupErr) {
397
- if (!(0, errors_1.isNotFoundOnAllBackends)(lookupErr)) {
398
- logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive, retrying next tick:`, lookupErr);
399
- return;
400
- }
401
- onChain = false;
401
+ logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive, retrying next tick:`, lookupErr);
402
+ return;
402
403
  }
403
404
  if (onChain) {
404
405
  logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit, awaiting confirmation`);
@@ -411,7 +412,7 @@ class CardanoWalletWorker {
411
412
  logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain, retrying next tick:`, submitError);
412
413
  return;
413
414
  }
414
- // Proven absent and not submittable anymore: releasing the idempotency key is safe.
415
+ // Not on-chain and not submittable now. The job fails and keeps its idempotency key.
415
416
  const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
416
417
  logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}), failing:`, submitError);
417
418
  await this.failReconciled(job, code, submitError);
@@ -424,11 +425,20 @@ class CardanoWalletWorker {
424
425
  }
425
426
  async failReconciled(job, code, err) {
426
427
  await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
427
- const transitioned = await (0, job_store_1.markFailed)(tx, job.ID, code, err ?? new Error(code));
428
+ const transitioned = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, code, err ?? new Error(code));
428
429
  if (transitioned)
429
430
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
430
431
  })).catch((persistErr) => logger.error(`Job ${job.ID}: failure persist failed:`, persistErr));
431
432
  }
433
+ /** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
434
+ buildOf(job, raw) {
435
+ if (job.kind === 'payout') {
436
+ const request = (0, build_request_1.preparePayoutRequest)(raw);
437
+ return (tx) => this.deps.indexer.indexPlutusBuildResult(tx, request);
438
+ }
439
+ const request = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, raw, this.deps.network);
440
+ return (tx) => this.buildForKind(tx, job, request);
441
+ }
432
442
  /** Dispatch the job kind to the matching indexer build method. */
433
443
  buildForKind(tx, job, buildReq) {
434
444
  const indexer = this.deps.indexer;
@@ -2,7 +2,7 @@ using {odatano.cardano as db} from '../db/schema';
2
2
 
3
3
  // Agent grants: scoped, budgeted bearer tokens an Admin issues instead of a full user.
4
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.
5
+ // The allow list and the daily budget are enforced in srv/utils/agent-grants.ts.
6
6
  @requires: 'authenticated-user'
7
7
  service CardanoAgentService @(impl: './cardano-agent-service') {
8
8
 
@@ -20,8 +20,6 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
20
20
  grantId : UUID;
21
21
  agentLabel : String(100);
22
22
  allowedActions : many String;
23
- walletId : String(50);
24
- allowedJobKinds : many String;
25
23
  maxJobsPerDay : Integer;
26
24
  jobsUsedToday : Integer;
27
25
  budgetWindow : String(10);
@@ -34,23 +32,21 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
34
32
  grantId : UUID;
35
33
  token : String; // shown once, never stored
36
34
  allowedActions : many String;
37
- walletId : String(50);
38
- allowedJobKinds : many String;
39
35
  maxJobsPerDay : Integer;
40
36
  validUntil : Timestamp;
41
37
  }
42
38
 
43
39
  @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.'
40
+ @description: 'The calling token''s own grant: allow list, remaining daily budget, expiry. 400 without a token; an operator lists AgentGrants instead.'
41
+ @odatano.agent: 'read'
45
42
  function GetGrantStatus() returns GrantStatus;
46
43
 
47
44
  @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.'
45
+ @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. Worker wallets are closed to tokens.'
49
46
  @requires : 'Admin'
47
+ @odatano.agent: 'operator'
50
48
  action CreateAgentGrant(
51
49
  @title: 'Allowed Actions' allowedActions : many String,
52
- @title: 'Wallet Id' walletId : String(50),
53
- @title: 'Allowed Job Kinds' allowedJobKinds : many String,
54
50
  @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
55
51
  @title: 'Valid Until' validUntil : Timestamp,
56
52
  @title: 'Agent Label' agentLabel : String(100)
@@ -59,6 +55,7 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
59
55
  @title : 'Revoke Agent Grant'
60
56
  @description: 'Deactivate a grant. Admin only. Its token becomes an unknown token immediately.'
61
57
  @requires : 'Admin'
58
+ @odatano.agent: 'operator'
62
59
  action RevokeAgentGrant(
63
60
  @title: 'Grant Id' grantId : UUID
64
61
  ) returns Boolean;
@@ -70,8 +67,9 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
70
67
  }
71
68
 
72
69
  @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.'
70
+ @description: 'Replace the grant token; the old token is unknown from the next request. Budget, allow list and expiry survive. Admin only. 404 when the grant does not exist or is revoked.'
74
71
  @requires : 'Admin'
72
+ @odatano.agent: 'operator'
75
73
  action RotateAgentGrantToken(
76
74
  @title: 'Grant Id' grantId : UUID
77
75
  ) returns RotatedGrant;
@@ -83,13 +81,13 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
83
81
  }
84
82
 
85
83
  @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.'
84
+ @description: 'Change label, allow list, daily budget or expiry of an active grant. An absent parameter stays as it is; an explicit null clears agentLabel, maxJobsPerDay or validUntil. allowedActions cannot be emptied. Admin only. 404 unknown grant, 409 GRANT_REVOKED.'
87
85
  @requires : 'Admin'
86
+ @odatano.agent: 'operator'
88
87
  action UpdateAgentGrant(
89
88
  @title: 'Grant Id' grantId : UUID,
90
89
  @title: 'Agent Label' agentLabel : String(100),
91
90
  @title: 'Allowed Actions' allowedActions : many String,
92
- @title: 'Allowed Job Kinds' allowedJobKinds : many String,
93
91
  @title: 'Max Jobs Per Day' maxJobsPerDay : Integer,
94
92
  @title: 'Valid Until' validUntil : Timestamp
95
93
  ) returns UpdatedGrant;
@@ -115,6 +113,7 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
115
113
 
116
114
  @title : 'Get Grant Usage'
117
115
  @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.'
116
+ @odatano.agent: 'read'
118
117
  function GetGrantUsage(
119
118
  @title: 'Grant Id' grantId : UUID,
120
119
  @title: 'Since' since : Timestamp,
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const agent_grants_1 = require("./utils/agent-grants");
4
+ const result_numbers_1 = require("./utils/result-numbers");
4
5
  // Handlers live in srv/utils/agent-grants.ts, shared with the programmatic API.
5
6
  // The token enforcement hook is attached to all services in src/plugin.ts.
6
7
  module.exports = (srv) => {
8
+ (0, result_numbers_1.answerNumbersAsText)(srv);
7
9
  (0, agent_grants_1.registerAgentGrantHandlers)(srv);
8
10
  };
9
11
  //# sourceMappingURL=cardano-agent-service.js.map
@@ -1,45 +1,78 @@
1
1
  // Backend data for another ODATANO instance that uses this one with `backends: ["odatano"]`.
2
2
  // Every operation returns the provider shape as a JSON string, mapped like a Koios answer.
3
- @requires: 'authenticated-user'
3
+ @requires: 'Read'
4
4
  service CardanoBackendService @(impl: './cardano-backend-service') {
5
5
 
6
6
  // --- blocks and transactions -------------------------------------------------------------
7
+ @odatano.agent: 'read'
7
8
  action GetTransaction(hash: String) returns LargeString;
9
+ @odatano.agent: 'read'
8
10
  action GetTransactionsBatch(hashes: LargeString) returns LargeString;
11
+ @odatano.agent: 'read'
9
12
  action GetTransactionMetadata(hash: String) returns LargeString;
13
+ @odatano.agent: 'read'
10
14
  action GetBlock(hash: String) returns LargeString;
15
+ @odatano.agent: 'read'
11
16
  action GetBlockByHeight(@assert.range: [0, _] height: Integer64) returns LargeString;
17
+ @odatano.agent: 'read'
12
18
  action GetNextBlocks(afterHash: String, @assert.range: [1, 500] count: Integer,
13
19
  @assert.range: [0, _] afterHeight: Integer64) returns LargeString;
20
+ @odatano.agent: 'read'
14
21
  action GetBlockTransactions(blockHash: String) returns LargeString;
22
+ @odatano.agent: 'read'
15
23
  action GetLatestBlock() returns LargeString;
24
+ @odatano.agent: 'read'
16
25
  action GetCurrentSlot() returns LargeString;
26
+ @odatano.agent: 'read'
17
27
  action GetEpoch(@assert.range: [0, _] epoch: Integer) returns LargeString;
28
+ @odatano.agent: 'read'
18
29
  action GetLatestEpoch() returns LargeString;
19
30
 
20
31
  // --- addresses and UTxOs ------------------------------------------------------------------
32
+ @odatano.agent: 'read'
21
33
  action GetAddress(address: String) returns LargeString;
34
+ @odatano.agent: 'read'
22
35
  action GetAddressUtxos(address: String) returns LargeString;
36
+ @odatano.agent: 'read'
23
37
  action GetAddressTransactions(address: String, @assert.range: [1, 100] limit: Integer) returns LargeString;
38
+ @odatano.agent: 'read'
24
39
  action GetAddressTransactionHashes(address: String, @assert.range: [1, 100] limit: Integer) returns LargeString;
40
+ @odatano.agent: 'read'
25
41
  action GetCredentialUtxos(credential: String) returns LargeString;
42
+ @odatano.agent: 'read'
26
43
  action IsUtxoUnspent(txHash: String, @assert.range: [0, _] outputIndex: Integer) returns LargeString;
44
+ @odatano.agent: 'read'
27
45
  action GetUnspentOutputs(refs: LargeString) returns LargeString;
28
46
 
29
47
  // --- stake, governance, assets, network ------------------------------------------------
48
+ @odatano.agent: 'read'
30
49
  action GetAccount(stakeAddress: String) returns LargeString;
50
+ @odatano.agent: 'read'
31
51
  action GetPool(poolId: String) returns LargeString;
52
+ @odatano.agent: 'read'
32
53
  action GetPoolIds() returns LargeString;
54
+ @odatano.agent: 'read'
33
55
  action GetPools(ids: LargeString) returns LargeString;
56
+ @odatano.agent: 'read'
34
57
  action GetDrep(drepId: String) returns LargeString;
58
+ @odatano.agent: 'read'
35
59
  action GetDrepIds() returns LargeString;
60
+ @odatano.agent: 'read'
36
61
  action GetDreps(ids: LargeString) returns LargeString;
62
+ @odatano.agent: 'read'
37
63
  action GetAssetInfo(unit: String) returns LargeString;
64
+ @odatano.agent: 'read'
38
65
  action GetAssetHistory(unit: String, @assert.range: [1, 100] limit: Integer) returns LargeString;
66
+ @odatano.agent: 'read'
39
67
  action GetNetworkInformation() returns LargeString;
68
+ @odatano.agent: 'read'
40
69
  action GetProtocolParameters() returns LargeString;
41
70
 
42
71
  // --- transactions in flight ------------------------------------------------------------
72
+ @requires : 'Transact'
73
+ @odatano.agent: 'read'
43
74
  action EvaluateTransaction(cbor: LargeString) returns LargeString;
75
+ @requires : 'Transact'
76
+ @odatano.agent: 'grant'
44
77
  action SubmitTransaction(cbor: LargeString) returns LargeString;
45
78
  }