@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

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 (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -1,23 +1,7 @@
1
1
  /**
2
- * Keeps a per-wallet lease alive for as long as a job execution runs.
3
- *
4
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
5
- * multi-backend build plus an HSM round-trip); a single renewal before the build
6
- * is therefore not enough. Without a heartbeat the lease silently expires
7
- * mid-execution, another instance adopts the wallet, fails this executor's row as
8
- * orphaned and starts the next job — two executors on one wallet, which is exactly
9
- * what the per-wallet lease exists to prevent.
10
- *
11
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
12
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
13
- * wedged stops beating and correctly loses the wallet.
14
- *
15
- * Two failure semantics, on purpose:
16
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
17
- * only a definitive "not yours" marks the lease lost.
18
- * - `fence()` is strict: it is called right before an irreversible step, where
19
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
20
- * free (nothing has been sent yet); guessing wrong is a double spend.
2
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
3
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
4
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
21
5
  */
22
6
  export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
23
7
  export declare class LeaseHeartbeat {
@@ -33,7 +17,7 @@ export declare class LeaseHeartbeat {
33
17
  constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
34
18
  start(): void;
35
19
  stop(): void;
36
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
20
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
37
21
  isLost(): boolean;
38
22
  /** Renew now; false means "do not touch this wallet any further". */
39
23
  fence(): Promise<boolean>;
@@ -8,25 +8,9 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const job_store_1 = require("./job-store");
9
9
  const logger = cds_1.default.log('CardanoWalletWorker');
10
10
  /**
11
- * Keeps a per-wallet lease alive for as long as a job execution runs.
12
- *
13
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
14
- * multi-backend build plus an HSM round-trip); a single renewal before the build
15
- * is therefore not enough. Without a heartbeat the lease silently expires
16
- * mid-execution, another instance adopts the wallet, fails this executor's row as
17
- * orphaned and starts the next job — two executors on one wallet, which is exactly
18
- * what the per-wallet lease exists to prevent.
19
- *
20
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
21
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
22
- * wedged stops beating and correctly loses the wallet.
23
- *
24
- * Two failure semantics, on purpose:
25
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
26
- * only a definitive "not yours" marks the lease lost.
27
- * - `fence()` is strict: it is called right before an irreversible step, where
28
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
29
- * free (nothing has been sent yet); guessing wrong is a double spend.
11
+ * Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
12
+ * Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
13
+ * (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
30
14
  */
31
15
  exports.LEASE_HEARTBEAT_INTERVAL_MS = Math.floor(job_store_1.WORKER_LEASE_TTL_MS / 3);
32
16
  class LeaseHeartbeat {
@@ -56,7 +40,7 @@ class LeaseHeartbeat {
56
40
  this.timer = null;
57
41
  }
58
42
  }
59
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
43
+ /** True once a renewal proved the lease is not ours anymore — abort the execution. */
60
44
  isLost() {
61
45
  return this.lost;
62
46
  }
@@ -1,16 +1,8 @@
1
1
  import type { WorkerSignerTypeValue } from './job-store';
2
2
  /**
3
- * Wallet-worker signers (v2.0).
4
- *
5
- * `WorkerSigner` is the signer-agnostic surface the worker engine executes against:
6
- * - `hsm` (production): thin wrapper around the already-initialized `HsmSigner`
7
- * (PKCS#11 — keys never leave the module).
8
- * - `software` (dev/test): operator-configured Ed25519 key from an environment
9
- * variable, either plain 64-char hex or AES-256-GCM encrypted
10
- * (`iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY — see srv/utils/crypto.ts).
11
- *
12
- * Keys are NEVER accepted through the OData surface and never persisted; the
13
- * software key lives only in this process's memory.
3
+ * Wallet-worker signers: `hsm` wraps the process-wide HsmSigner (PKCS#11), `software` holds an
4
+ * Ed25519 key from an env var (plain hex or AES-256-GCM `iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY).
5
+ * Keys are never accepted via OData and never persisted.
14
6
  */
15
7
  export interface WorkerSigner {
16
8
  readonly type: WorkerSignerTypeValue;
@@ -25,17 +17,12 @@ export interface WorkerSigner {
25
17
  export interface WorkerWalletConfig {
26
18
  walletId: string;
27
19
  signerType: WorkerSignerTypeValue;
28
- /**
29
- * software only: name of the environment variable holding the Ed25519 signing
30
- * key — plain 64-char hex, or AES-256-GCM `iv:authTag:ciphertext` (base64 parts).
31
- */
20
+ /** software only: env var holding the Ed25519 key — 64-char hex or AES-256-GCM `iv:authTag:ciphertext` (base64). */
32
21
  keyEnv?: string;
33
22
  }
34
23
  /**
35
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
36
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
37
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
38
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
24
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
25
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
39
26
  */
40
27
  export declare function mergeVkeyWitness(unsignedTxCbor: string, publicKeyHex: string, signatureHex: string): string;
41
28
  /** Derive the bech32 enterprise key-hash address for a 28-byte key hash. */
@@ -17,10 +17,8 @@ const errors_1 = require("../../utils/errors");
17
17
  const crypto_2 = require("../../utils/crypto");
18
18
  const logger = cds_1.default.log('CardanoWalletWorker');
19
19
  /**
20
- * Merge a single VKey witness [publicKey, signature] into an unsigned transaction's
21
- * witness set at the raw CBOR level, preserving all non-vkey entries (scripts,
22
- * datums, redeemers) and encoding metadata. Same single-signer semantics as
23
- * HsmSigner.signTransaction — the worker wallet is the sole signer of its builds.
20
+ * Merge a single VKey witness into the witness set at the raw CBOR level, preserving
21
+ * non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
24
22
  */
25
23
  function mergeVkeyWitness(unsignedTxCbor, publicKeyHex, signatureHex) {
26
24
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
@@ -99,10 +97,7 @@ class SoftwareWorkerSigner {
99
97
  }
100
98
  }
101
99
  exports.SoftwareWorkerSigner = SoftwareWorkerSigner;
102
- /**
103
- * Resolve the software key material for a wallet: plain hex passes through,
104
- * the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY.
105
- */
100
+ /** Plain hex passes through; the AES-256-GCM combined format (contains ':') is decrypted with ENCRYPTION_KEY. */
106
101
  function resolveSoftwareKey(wallet) {
107
102
  if (!wallet.keyEnv) {
108
103
  throw new errors_1.ConfigError(`Wallet worker: wallet "${wallet.walletId}" is signerType=software but has no keyEnv configured`);
@@ -2,32 +2,9 @@ import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { type WorkerSigner, type WorkerWalletConfig } from './signers';
4
4
  /**
5
- * Wallet worker engine (v2.0, design §6).
6
- *
7
- * Dispatch loop over `CardanoWalletJobs`: per tick, for every configured wallet
8
- * with pending work and NO active job (building or submitted — the queue stays
9
- * blocked until the previous job CONFIRMS, which makes per-wallet UTxO contention
10
- * impossible by construction), acquire the per-wallet DB lease and execute:
11
- *
12
- * building → CardanoIndexer.index<Kind>BuildResult (build + TransactionBuilds row)
13
- * → signer.signTransaction
14
- * submitting → signed CBOR + hash committed, THEN client.submitTransaction
15
- * submitted → hand to the ConfirmationTracker (crawler hook or polling)
16
- *
17
- * The `submitting` commit is what makes the submit boundary crash-safe: the exact
18
- * bytes that may be on-chain are durable before the network call, and the row stays
19
- * non-terminal, so it keeps holding its idempotency key. Anything that goes wrong
20
- * from there on is reconciled against the chain (`reconcileSubmitting`) — the same
21
- * transaction is re-submitted, never a rebuild.
22
- *
23
- * Transient failures BEFORE the signed tx exists (provider outages, rate limits,
24
- * HSM hiccups during build/sign) re-queue the job with exponential backoff up to
25
- * `maxAttempts`; deterministic rejections (validation, insufficient funds) fail
26
- * immediately.
27
- *
28
- * All DB access runs in short fresh transactions (ambient context cleared —
29
- * NIGHTGATE lesson 2) so the single pooled SQLite connection is never held
30
- * across build/submit round-trips.
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.
31
8
  */
32
9
  export interface WalletWorkerConfig {
33
10
  enabled: boolean;
@@ -48,10 +25,7 @@ export interface WalletWorkerDeps {
48
25
  }
49
26
  /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
50
27
  export declare function retryBackoffMs(attempt: number): number;
51
- /**
52
- * Transient errors are worth a bounded retry; everything else is deterministic
53
- * (a retry cannot change the outcome) and fails the job immediately.
54
- */
28
+ /** Transient errors get a bounded retry; everything else fails the job immediately. */
55
29
  export declare function isTransientJobError(err: unknown): boolean;
56
30
  export declare class CardanoWalletWorker {
57
31
  private readonly deps;
@@ -79,66 +53,36 @@ export declare class CardanoWalletWorker {
79
53
  /** One dispatch round; serialized (overlapping timers collapse into one run). */
80
54
  private tickSafe;
81
55
  private tick;
82
- /**
83
- * Adopt `submitting` rows left behind by a dead executor (this process before a
84
- * restart, or another instance whose lease expired) and resolve them against the
85
- * chain. Runs per wallet under the same lease the executor would hold.
86
- */
56
+ /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
87
57
  private reconcileOrphanedSubmissions;
88
58
  /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
89
59
  private spawn;
90
60
  /** A heartbeat that keeps this instance's lease on `walletId` alive while it works. */
91
61
  private leaseHeartbeat;
92
62
  /**
93
- * Execute one job: building → (build → sign) → submitting → submit → submitted,
94
- * then hand to the tracker. The wallet lease is held for the duration — renewed by
95
- * a heartbeat, because build+sign can outlast its TTL — and released afterwards
96
- * (queue serialization continues via the job row, not the lease).
97
- *
98
- * Everything up to and including the `submitting` commit may fail freely — nothing
99
- * has been sent, so the job re-queues or fails normally. Past that commit the job
100
- * belongs to `reconcileSubmitting`.
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`.
101
66
  */
102
67
  private executeJob;
103
68
  /**
104
- * Send a transaction that is already durable in its `submitting` row and advance
105
- * the job to `submitted`.
106
- *
107
- * A submit failure is NEVER propagated as a job failure here: a rejection from one
108
- * backend does not prove the tx is absent from every mempool (failover, timeouts,
109
- * a node that accepted before the connection dropped). The row simply stays
110
- * `submitting` and the next tick reconciles it against the chain.
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.
111
72
  */
112
73
  private submitStoredTransaction;
113
74
  /** submitting → submitted + hand to the confirmation tracker. */
114
75
  private adoptSubmitted;
115
76
  /**
116
- * Resolve a `submitting` job whose submit outcome is unknown (process died around
117
- * the network call, or the call failed ambiguously). The stored transaction is the
118
- * only one this job may ever have — it is re-submitted verbatim, never rebuilt.
119
- *
120
- * 1. Re-submit the same CBOR: mempool/ledger dedup makes this a no-op if it was
121
- * accepted before, so success (or "already known") simply promotes the job.
122
- * 2. If that fails, ask the chain: found → the tx did make it, promote it.
123
- * 3. Only when the chain proves absence AND the node rejects the tx for good (or
124
- * it has been absent past the confirmation timeout) is the job failed —
125
- * failing releases the idempotency key, so it needs that proof.
126
- * Anything else leaves the row as-is; the next tick tries again.
127
- *
128
- * Runs under the same heartbeat-kept wallet lease as an execution: the chain
129
- * lookups here are slow enough to outlive the raw TTL. Losing the lease mid-way
130
- * is not dangerous (the re-submit is the same transaction, and every terminal
131
- * transition is row-guarded), so it only stops further work.
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.
132
80
  */
133
81
  private reconcileSubmitting;
134
82
  private failReconciled;
135
83
  /** Dispatch the job kind to the matching indexer build method. */
136
84
  private buildForKind;
137
- /**
138
- * Submit tolerant of "already known": after a crash between submit and the
139
- * `submitted` transition, the retry re-submits the same CBOR — mempool dedup
140
- * answers with an already-submitted error that IS our success case.
141
- */
85
+ /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
142
86
  private submitWithAlreadyKnownTolerance;
143
87
  private handleExecutionFailure;
144
88
  }
@@ -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,8 +389,7 @@ 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
395
  await this.deps.client.getTransaction(job.txHash);
@@ -461,9 +413,7 @@ class CardanoWalletWorker {
461
413
  logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain — retrying next tick:`, submitError);
462
414
  return;
463
415
  }
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.
416
+ // Proven absent and not submittable anymore: releasing the idempotency key is safe.
467
417
  const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
468
418
  logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}) — failing:`, submitError);
469
419
  await this.failReconciled(job, code, submitError);
@@ -494,11 +444,7 @@ class CardanoWalletWorker {
494
444
  throw new errors_1.BackendError(`Unsupported job kind "${job.kind}"`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
495
445
  }
496
446
  }
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
- */
447
+ /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
502
448
  async submitWithAlreadyKnownTolerance(signedTxCbor) {
503
449
  try {
504
450
  return await this.deps.client.submitTransaction(signedTxCbor);
@@ -513,10 +459,8 @@ class CardanoWalletWorker {
513
459
  }
514
460
  }
515
461
  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.
462
+ // Only a pre-submit (`building`) job may be re-queued or failed here; a `submitting` row's
463
+ // tx may be in a mempool, so it goes to reconciliation.
520
464
  const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
521
465
  .catch(() => null);
522
466
  if (current && current.status !== 'building') {
@@ -4,7 +4,7 @@ using {odatano.cardano as db} from '../db/schema';
4
4
  * Cardano Agent Service (v2.0)
5
5
  *
6
6
  * Agent grants: scoped, budgeted bearer capabilities an Admin hands to an agent
7
- * instead of a full user (see AGENT_GRANTS_DESIGN.md).
7
+ * instead of a full user.
8
8
  *
9
9
  * - CreateAgentGrant / UpdateAgentGrant / RotateAgentGrantToken / RevokeAgentGrant:
10
10
  * Admin-only administration, rate limited per principal per hour
@@ -18,10 +18,6 @@ using {odatano.cardano as db} from '../db/schema';
18
18
  * - GetGrantUsage: admitted calls per service and action over a window — an Admin
19
19
  * for any grant, a token for its own (a partner usage view, ledger reconciliation).
20
20
  *
21
- * Names are this repo's PascalCase; semantics mirror NIGHTGATE's agent grants
22
- * (createAgentGrant / updateAgentGrant / rotateAgentGrantToken / revokeAgentGrant /
23
- * getGrantUsage), so a gateway drives both products with one code path.
24
- *
25
21
  * A token request never inherits the operator's roles: `@requires: 'Admin'` on the
26
22
  * four actions, on PauseWorker / ResumeWorker / pauseCrawler / resumeCrawler and on
27
23
  * every other Admin surface therefore refuses it by construction. The allow list,
@@ -2,13 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const agent_grants_1 = require("./utils/agent-grants");
4
4
  /**
5
- * CardanoAgentService handlers — grant administration (Admin) and token
6
- * self-service. Everything lives in srv/utils/agent-grants.ts so the
7
- * programmatic API (`issueAgentGrant`, used by @odatano/x402 to sell grants) and
8
- * the OData actions share one code path.
9
- *
10
- * The enforcement hook for token requests is attached to all six services from
11
- * src/plugin.ts (cds.on('serving')), not here.
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.
12
8
  */
13
9
  module.exports = (srv) => {
14
10
  (0, agent_grants_1.registerAgentGrantHandlers)(srv);