@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,47 +1,21 @@
1
1
  import { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
2
2
  import { CardanoClient } from "../cardano-client";
3
- /**
4
- * CardanoTxBuilder - Interface Definition for the Cardano transaction builder (Buildooor)
5
- * Defines the standard methods that any Cardano transaction builder must implement to be used interchangeably.
6
- */
3
+ /** Interface for the Cardano transaction builder (Buildooor). */
7
4
  export interface CardanoTxBuilder {
8
- /**
9
- * Builder name
10
- */
5
+ /** Builder name */
11
6
  name: string;
12
7
  /**
13
- * Initialize the builder
14
- * @param client - The CardanoClient instance
15
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
8
+ * Initialize the builder.
9
+ * @param protocolParams - optional; fetched from the backend when omitted
16
10
  */
17
11
  init(client: CardanoClient, protocolParams?: LedgerProtocolParameters): Promise<void>;
18
- /**
19
- * Build unsigned transfer transaction (ADA-only or with native assets)
20
- * @param req transaction build request
21
- * @param ctx transaction build context
22
- * @returns {Promise<TxBuildResult>} transaction build result
23
- */
12
+ /** Build an unsigned transfer transaction (ADA-only or with native assets). */
24
13
  buildUnsignedTransfer(req: TxBuildRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
25
- /**
26
- * Build unsigned transaction with metadata
27
- * @param req transaction build request
28
- * @param ctx transaction build context
29
- * @returns {Promise<TxBuildResult>} transaction build result
30
- */
14
+ /** Build an unsigned transaction with attached metadata. */
31
15
  buildUnsignedTransactionWithMetadata(req: TxBuildRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
32
- /**
33
- * Build unsigned Plutus SC transaction
34
- * @param req transaction build request
35
- * @param ctx transaction build context
36
- * @returns {Promise<TxBuildResult>} transaction build result
37
- */
16
+ /** Build an unsigned Plutus mint transaction. */
38
17
  buildUnsignedMintTransaction(req: TxBuildMintRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
39
- /**
40
- * Build unsigned Plutus spending transaction (consume UTxO at script address)
41
- * @param req transaction build request with plutusScriptExecution
42
- * @param ctx transaction build context
43
- * @returns {Promise<TxBuildResult>} transaction build result
44
- */
18
+ /** Build an unsigned Plutus spending transaction (consume a UTxO at a script address). */
45
19
  buildUnsignedPlutusSpendTransaction(req: TxBuildPlutusSpendRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
46
20
  }
47
21
  //# sourceMappingURL=cardano-tx.d.ts.map
@@ -2,25 +2,12 @@ import type { TxBuildRequest } from '../../utils/types';
2
2
  import type { Network } from '../cardano-client';
3
3
  import type { WalletJobKindValue } from './job-store';
4
4
  /**
5
- * Transform a stored wallet-job `requestJson` (the documented Build*-action
6
- * payload shape — assetsJson, mintActionsJson, metadataJson strings, …) into
7
- * the TxBuildRequest shape the CardanoIndexer build methods expect (assets,
8
- * mintActions with bigint quantities, parsed metadata, assembled
9
- * plutusScriptExecution, …).
10
- *
11
- * The synchronous CardanoTransactionService handlers do this transformation
12
- * inline per action; the worker executes the SAME payload asynchronously, so
13
- * this module mirrors that logic using the shared parsers
14
- * (srv/utils/tx-request-parsers.ts). Validation failures throw
15
- * BackendError 400 INVALID_INPUT — deterministic, so the job fails terminally
16
- * instead of burning retries.
5
+ * Transforms a stored wallet-job request (Build*-action payload shape) into the
6
+ * TxBuildRequest the CardanoIndexer build methods expect, mirroring the synchronous handlers.
7
+ * Validation failures throw BackendError 400 INVALID_INPUT so the job fails terminally, not via retries.
17
8
  */
18
9
  type RawRequest = Record<string, unknown>;
19
- /**
20
- * Transform the raw job request (documented Build*-action payload) into the
21
- * TxBuildRequest the matching CardanoIndexer build method expects. Throws
22
- * BackendError 400 INVALID_INPUT for malformed payloads (terminal job failure).
23
- */
10
+ /** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
24
11
  export declare function prepareWorkerBuildRequest(kind: WalletJobKindValue, raw: RawRequest, network: Network): TxBuildRequest;
25
12
  export {};
26
13
  //# sourceMappingURL=build-request.d.ts.map
@@ -12,12 +12,7 @@ const const_1 = require("../../utils/const");
12
12
  function fail(message) {
13
13
  throw new errors_1.BackendError(message, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
14
14
  }
15
- /**
16
- * Presence-only check for required payload fields. Format validation (bech32,
17
- * hex, amounts) deliberately stays with the builder/indexer, mirroring what a
18
- * missing field would produce on the synchronous path — the transform's job is
19
- * the SHAPE, not re-validating content.
20
- */
15
+ /** Presence-only check; format validation (bech32, hex, amounts) stays with the builder/indexer. */
21
16
  function requirePresent(raw, required) {
22
17
  const missing = required.filter((f) => raw[f] === undefined || raw[f] === null || raw[f] === '');
23
18
  if (missing.length > 0)
@@ -42,8 +37,7 @@ function parseScriptParams(raw) {
42
37
  fail('scriptParamsJson must be a JSON array');
43
38
  return parsed;
44
39
  }
45
- /** Mirrors the BuildMint/BuildPlutusSpend mint-action parsing (bigint quantities,
46
- * multi-policy per-action fields). */
40
+ /** Mint-action parsing as in BuildMint/BuildPlutusSpend (bigint quantities, per-action policy fields). */
47
41
  function parseMintActions(raw, allowBareNames) {
48
42
  const parsed = parseJsonField(raw, 'mintActionsJson');
49
43
  if (!Array.isArray(parsed))
@@ -58,7 +52,7 @@ function parseMintActions(raw, allowBareNames) {
58
52
  }
59
53
  if (typeof action.assetUnit !== 'string')
60
54
  fail('Each mint action must have an assetUnit string');
61
- // Multi-policy mint FR: optional per-action mintingPolicyScript + redeemerJson.
55
+ // Optional per-action mintingPolicyScript + redeemerJson (multi-policy mint).
62
56
  const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, i);
63
57
  if (policyFields.error)
64
58
  fail(policyFields.error);
@@ -100,13 +94,11 @@ function scriptHashOf(scriptHex, context) {
100
94
  }
101
95
  }
102
96
  /**
103
- * BUG 9 mirror: every (expanded) mint action must carry the effective policy id —
104
- * parseAssetUnit silently discards the first 56 hex chars, so a mismatched prefix
105
- * would mint a truncated asset name.
97
+ * Every mint action must carry the effective policy id: parseAssetUnit drops the first
98
+ * 56 hex chars, so a mismatched prefix would mint a truncated asset name.
106
99
  */
107
100
  function assertPolicyPrefix(actions, policyId) {
108
- // Actions with their own per-action script were already checked against THAT
109
- // script's policy id during parsing.
101
+ // Actions with their own script were already checked against that script's policy id.
110
102
  const mismatch = actions.find((a) => !a.mintingPolicyScript && !a.assetUnit.toLowerCase().startsWith(policyId));
111
103
  if (mismatch) {
112
104
  fail(`assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`);
@@ -207,8 +199,7 @@ function prepareMint(raw, network) {
207
199
  if (raw.referenceScriptHex)
208
200
  clean.referenceScript = raw.referenceScriptHex;
209
201
  delete clean.referenceScriptHex;
210
- // Apply script parameters (parameterized policies), expand bare asset names,
211
- // route lockOnScript output — mirrors BuildMintTransaction.
202
+ // Apply script parameters, expand bare asset names, route lockOnScript output.
212
203
  let finalMintingPolicyScript = raw.mintingPolicyScript;
213
204
  let effectivePolicyId;
214
205
  if (scriptParams && scriptParams.length > 0) {
@@ -266,7 +257,7 @@ function preparePlutusSpend(raw, network) {
266
257
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
267
258
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
268
259
  const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
269
- // Optional combined spend+mint (FR-1) — mirrors BuildPlutusSpendTransaction.
260
+ // Optional combined spend+mint.
270
261
  const validatorScript = raw.validatorScript;
271
262
  const mintingPolicyScript = raw.mintingPolicyScript;
272
263
  let mintActions;
@@ -351,11 +342,7 @@ function preparePlutusSpend(raw, network) {
351
342
  delete clean.lockOnScript;
352
343
  return clean;
353
344
  }
354
- /**
355
- * Transform the raw job request (documented Build*-action payload) into the
356
- * TxBuildRequest the matching CardanoIndexer build method expects. Throws
357
- * BackendError 400 INVALID_INPUT for malformed payloads (terminal job failure).
358
- */
345
+ /** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
359
346
  function prepareWorkerBuildRequest(kind, raw, network) {
360
347
  switch (kind) {
361
348
  case 'simpleAda': return prepareSimpleAda(raw, network);
@@ -1,21 +1,9 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  /**
3
- * Confirmation tracker (v2.0, design §7).
4
- *
5
- * Watches `submitted` jobs until their tx sits at depth ≥ `confirmationDepth`:
6
- * - Crawler hook (preferred, zero extra load): `blockIndexed` events match
7
- * submitted tx hashes and carry the advancing tip; `reorg` events invalidate
8
- * confirmation points behind the fork and optionally re-submit the SAME
9
- * signed CBOR (never a rebuild — the double-spend guard).
10
- * - Polling fallback (always on, hook path just accelerates): every
11
- * `pollIntervalMs` unfound txs are looked up via `client.getTransaction`
12
- * and the tip via `client.getLatestBlock`.
13
- *
14
- * A tx that stays unseen past `confirmationTimeoutMs` fails as TX_DROPPED —
15
- * safe to retry from the caller, because the guard is the on-chain lookup itself.
16
- *
17
- * Confirmations are counted as `tipHeight - foundHeight + 1`, so depth 1 means
18
- * "confirmed as soon as included in a block".
3
+ * Watches `submitted` jobs until their tx sits at depth >= `confirmationDepth`, via crawler
4
+ * `blockIndexed`/`reorg` hooks plus an always-on polling fallback. A reorg re-submits the SAME
5
+ * signed CBOR (never a rebuild); a tx unseen past `confirmationTimeoutMs` fails as TX_DROPPED.
6
+ * Depth = `tipHeight - foundHeight + 1`, so depth 1 means "included in a block".
19
7
  */
20
8
  export interface TrackedJob {
21
9
  jobId: string;
@@ -29,10 +17,8 @@ export interface TrackedJob {
29
17
  foundSlot: number | null;
30
18
  foundHeight: number | null;
31
19
  /**
32
- * Polling round in which the tx was last SEEN on-chain (found or
33
- * re-validated). A job found in the current round needs no second lookup
34
- * before it is confirmed; one found in an earlier round is re-checked, so a
35
- * rollback the crawler did not report (crawler off) cannot slip through.
20
+ * Polling round in which the tx was last seen on-chain. An inclusion from an earlier
21
+ * round is re-checked before confirming, so a rollback the crawler did not report cannot slip through.
36
22
  */
37
23
  seenRound?: number;
38
24
  }
@@ -87,29 +73,20 @@ export declare class ConfirmationTracker {
87
73
  private onBlockIndexed;
88
74
  private onReorg;
89
75
  /**
90
- * The recorded inclusion is gone (a reorg the crawler reported, or a polling
91
- * re-check that no longer finds the tx): back to watching, and optionally
92
- * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
93
- * guard. "Already known" means the tx survived into the new chain's mempool;
94
- * that is success, not an error.
76
+ * Inclusion rolled back: back to watching, optionally re-submitting the SAME signed CBOR
77
+ * (never a rebuild — the double-spend guard). "Already known" means the tx survived; success.
95
78
  */
96
79
  private forgetInclusion;
97
80
  /** One polling round. Public for tests; guarded against overlapping rounds. */
98
81
  pollOnce(): Promise<void>;
99
82
  /**
100
- * Confirm every found job whose depth requirement is met by the known tip.
101
- * `revalidate` (polling path): an inclusion not seen in THIS round is looked
102
- * up again first — the crawler's reorg events are the only rollback signal,
103
- * and with the crawler off there is none, so a tx that was found at height N
104
- * and then rolled back would otherwise be confirmed on the tip alone.
83
+ * Confirm every found job whose depth is met by the known tip. With `revalidate`
84
+ * (polling path) an inclusion not seen in this round is looked up again first.
105
85
  */
106
86
  private confirmMature;
107
87
  /**
108
- * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
109
- * moved to another block (re-included after a rollback) gets its new point
110
- * and is judged at the new height; one that is gone is forgotten (back to
111
- * watching, optional same-CBOR re-submit) and the tip is re-learned next
112
- * round, because the pre-rollback tip may overstate the depth.
88
+ * Is the tx still on-chain and deep enough? A tx that moved blocks is re-anchored at its
89
+ * new height; one that is gone goes back to watching and the tip is re-learned next round.
113
90
  */
114
91
  private stillIncluded;
115
92
  private finalize;
@@ -71,7 +71,7 @@ class ConfirmationTracker {
71
71
  }
72
72
  const txHashes = new Set(event.txHashes);
73
73
  const found = [...this.pending.values()].filter(j => j.foundHeight == null && txHashes.has(j.txHash));
74
- // Persist + depth-check detached: hook callers (the crawler) must not await us.
74
+ // Detached: hook callers (the crawler) must not await us.
75
75
  void (async () => {
76
76
  for (const job of found) {
77
77
  job.foundSlot = event.slot;
@@ -90,17 +90,15 @@ class ConfirmationTracker {
90
90
  async onReorg(event) {
91
91
  if (!this.running)
92
92
  return;
93
- // The pre-fork tip no longer exists — clamp (or drop) lastKnownTipHeight so
94
- // confirmations are never counted against it. Without this, a tx re-included
95
- // on the new chain would reach "depth" instantly via the stale tip height,
96
- // defeating the confirmation-depth guarantee exactly in the rollback case.
93
+ // Clamp (or drop) the stale pre-fork tip, otherwise a tx re-included on the new
94
+ // chain would reach depth instantly against it.
97
95
  if (event.forkHeight != null) {
98
96
  if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
99
97
  this.lastKnownTipHeight = event.forkHeight;
100
98
  }
101
99
  }
102
100
  else {
103
- this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
101
+ this.lastKnownTipHeight = null; // re-learn from the next block/poll
104
102
  }
105
103
  for (const job of this.pending.values()) {
106
104
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
@@ -110,11 +108,8 @@ class ConfirmationTracker {
110
108
  }
111
109
  }
112
110
  /**
113
- * The recorded inclusion is gone (a reorg the crawler reported, or a polling
114
- * re-check that no longer finds the tx): back to watching, and optionally
115
- * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
116
- * guard. "Already known" means the tx survived into the new chain's mempool;
117
- * that is success, not an error.
111
+ * Inclusion rolled back: back to watching, optionally re-submitting the SAME signed CBOR
112
+ * (never a rebuild — the double-spend guard). "Already known" means the tx survived; success.
118
113
  */
119
114
  async forgetInclusion(job) {
120
115
  job.foundSlot = null;
@@ -149,8 +144,7 @@ class ConfirmationTracker {
149
144
  this.polling = true;
150
145
  this.round++;
151
146
  try {
152
- // Tip first — also serves the depth check for hook-found entries when the
153
- // crawler is off.
147
+ // Tip first — also the depth check for hook-found entries when the crawler is off.
154
148
  try {
155
149
  const tip = await this.deps.client.getLatestBlock();
156
150
  if (tip.height != null) {
@@ -173,9 +167,8 @@ class ConfirmationTracker {
173
167
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
174
168
  }
175
169
  catch (err) {
176
- // The client's failover wraps per-backend 404s into AllBackendsFailedError,
177
- // so a plain `instanceof NotFoundError` check never fires — the helper also
178
- // accepts "every consulted backend said 404" as proof of absence.
170
+ // Failover wraps per-backend 404s into AllBackendsFailedError; the helper
171
+ // treats "every backend said 404" as proof of absence.
179
172
  if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
180
173
  // Not on-chain yet — check the mempool-TTL timeout.
181
174
  const age = Date.now() - Date.parse(job.submittedAt);
@@ -188,8 +181,7 @@ class ConfirmationTracker {
188
181
  }
189
182
  }
190
183
  }
191
- // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
- // round is re-checked before it counts (see stillIncluded).
184
+ // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
193
185
  await this.confirmMature(true);
194
186
  }
195
187
  finally {
@@ -198,11 +190,8 @@ class ConfirmationTracker {
198
190
  }
199
191
  // ---- Shared -----------------------------------------------------------------
200
192
  /**
201
- * Confirm every found job whose depth requirement is met by the known tip.
202
- * `revalidate` (polling path): an inclusion not seen in THIS round is looked
203
- * up again first — the crawler's reorg events are the only rollback signal,
204
- * and with the crawler off there is none, so a tx that was found at height N
205
- * and then rolled back would otherwise be confirmed on the tip alone.
193
+ * Confirm every found job whose depth is met by the known tip. With `revalidate`
194
+ * (polling path) an inclusion not seen in this round is looked up again first.
206
195
  */
207
196
  async confirmMature(revalidate = false) {
208
197
  const tip = this.lastKnownTipHeight;
@@ -219,11 +208,8 @@ class ConfirmationTracker {
219
208
  }
220
209
  }
221
210
  /**
222
- * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
223
- * moved to another block (re-included after a rollback) gets its new point
224
- * and is judged at the new height; one that is gone is forgotten (back to
225
- * watching, optional same-CBOR re-submit) and the tip is re-learned next
226
- * round, because the pre-rollback tip may overstate the depth.
211
+ * Is the tx still on-chain and deep enough? A tx that moved blocks is re-anchored at its
212
+ * new height; one that is gone goes back to watching and the tip is re-learned next round.
227
213
  */
228
214
  async stillIncluded(job, tip) {
229
215
  try {
@@ -264,13 +250,11 @@ class ConfirmationTracker {
264
250
  }
265
251
  catch (persistErr) {
266
252
  logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
267
- return; // keep tracking — the next poll round retries the transition
253
+ return; // keep tracking — the next round retries
268
254
  }
269
255
  this.pending.delete(job.jobId);
270
256
  if (!transitioned) {
271
- // Somebody else (another tracker instance, a reconciliation pass, a
272
- // cancel) reached the terminal state first. The job is done either way,
273
- // but the stats bump and the terminal event belong to the winner only.
257
+ // Another actor reached the terminal state first; stats bump and event belong to it.
274
258
  logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
275
259
  return;
276
260
  }
@@ -12,14 +12,8 @@ const node_crypto_1 = require("node:crypto");
12
12
  const wallet_worker_1 = require("./wallet-worker");
13
13
  const logger = cds_1.default.log('CardanoWalletWorker');
14
14
  /**
15
- * Module-level singleton lifecycle for the wallet worker. Mirrors the crawler's
16
- * srv/blockchain/crawler/index.ts: one active worker per process, started
17
- * fire-and-forget from the server's `served` hook and controlled (pause/resume/
18
- * status) via the worker control service.
19
- *
20
- * Unlike the crawler there is no standby machinery: every instance may run a
21
- * dispatch loop — the per-WALLET DB leases decide which instance executes a
22
- * given wallet's jobs, so failover is inherent.
15
+ * Process-wide wallet-worker singleton, started from the `served` hook and controlled via the
16
+ * worker service. No standby: every instance may dispatch, the per-wallet DB leases decide who executes.
23
17
  */
24
18
  let active = null;
25
19
  let lifecycleQueue = Promise.resolve();
@@ -1,38 +1,20 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  /**
3
- * Wallet-worker job store (v2.0).
3
+ * Persistence for `CardanoWalletJobs` + `CardanoWorkerWallets`. `insertJob` runs on the caller's
4
+ * ambient tx (a detached insert would deadlock on the SQLite write lock); transition helpers run in
5
+ * short fresh txs so the pooled connection is never held across a job execution.
4
6
  *
5
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
6
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
7
- *
8
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
9
- * handler in its own root tx which may already hold the SQLite write lock; a
10
- * detached insert would deadlock against it. The row simply commits together
11
- * with the handler, and the worker's dispatch loop only sees it once visible.
12
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
13
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
14
- * never held across the seconds-to-minutes job execution.
15
- *
16
- * State machine (see WALLET_WORKER_DESIGN.md §5):
7
+ * State machine:
17
8
  * pending → building → submitting → submitted → confirmed
18
9
  * │ │ │ └────→ failed
19
10
  * │ │ └→ submitted (reconciled) | failed (proven absent)
20
11
  * │ └→ pending (transient retry) | failed
21
12
  * └→ cancelled
22
13
  *
23
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
24
- * fee are committed BEFORE the transaction can reach the network, so a process
25
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
26
- * against the chain (or re-submitted verbatim) instead of a `building` row that
27
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
28
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
29
- *
30
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
31
- * a read-back verification — the wallet lease already fences concurrent workers,
32
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
33
- * all reads coerce via `num()` so callers get clean numbers.
14
+ * `submitting` commits the signed CBOR, hash and fee BEFORE the network call and keeps the idempotency
15
+ * key held; transitions are conditional UPDATEs on the expected source status.
34
16
  */
35
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
17
+ /** Per-wallet DB lease TTL. */
36
18
  export declare const WORKER_LEASE_TTL_MS = 15000;
37
19
  export declare const JOB_ERROR_CODES: {
38
20
  readonly PROCESS_RESTART: "PROCESS_RESTART";
@@ -103,42 +85,22 @@ export interface InsertJobResult {
103
85
  /** True when an idempotent retry matched an existing non-failed job. */
104
86
  deduplicated: boolean;
105
87
  }
106
- /** The job that currently owns an idempotency key, or null when it is free. */
107
88
  /**
108
- * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
109
- * submits. Two agents (two grants, two users) may both use `order-1` on the
110
- * same wallet: each must get its own job, never a "deduplicated" answer that
111
- * hands one the other's job id. A key from an owner-less caller (privileged
112
- * test context) stays as-is; an owned key becomes a hash of owner + key, which
113
- * fits the String(100) column whatever the owner id's length and never collides
114
- * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
89
+ * Stored dedup claim for an idempotency key, scoped to the submitting principal: an owned key
90
+ * becomes `o:` + hash(owner, key) (fits String(100), never collides with a plain key); an
91
+ * owner-less key stays as-is. The `idempotencyKey` column keeps the raw key.
115
92
  */
116
93
  export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
117
94
  /**
118
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
119
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
120
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
121
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
122
- * intended work never reached the chain, so re-using the key must be able to
123
- * actually execute it (a cancelled job would otherwise burn its key forever).
124
- *
125
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
126
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
127
- * app instances, or two HANA sessions — can both read "no such job" before either
128
- * commits, and would both insert. The read is only a fast path; the constraint is
129
- * what makes it correct, and the loser of the race returns the winner's job.
130
- *
131
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
132
- * otherwise, so keyless jobs never collide and terminated jobs free their key
133
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
134
- * inside a unique index.
95
+ * Insert a job row on the caller's transaction; an active-or-confirmed row with the same
96
+ * (walletId, kind, dedupKey) is returned instead, `failed`/`cancelled` rows never block a retry.
97
+ * The UNIQUE constraint decides concurrent inserts (the loser returns the winner's job).
135
98
  */
136
99
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
137
100
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
138
101
  /**
139
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
140
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
141
- * avoids adapter-specific NULL/OR predicate quirks.
102
+ * Pending jobs ordered by (priority, createdAt). `notBefore` is filtered in JS to avoid
103
+ * adapter-specific NULL/OR predicate quirks.
142
104
  */
143
105
  export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
144
106
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
@@ -146,31 +108,20 @@ export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJob
146
108
  /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
147
109
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
148
110
  /**
149
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
150
- * executor — its submit outcome is unknown (crash, or a submit call that failed
151
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
152
- * wallet lease is still held are being worked on right now and are left alone.
111
+ * Oldest `submitting` row of a wallet whose lease is expired/unowned: its submit outcome is
112
+ * unknown and needs chain reconciliation. Rows under a held lease are being worked on.
153
113
  */
154
114
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
155
115
  /**
156
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
157
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
158
- * which is what lets a caller re-use the key for a fresh attempt while the row
159
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
160
- *
161
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
162
- * request resolves to it instead of paying again.
116
+ * Free a job's idempotency key by pointing `dedupKey` at its own ID; `idempotencyKey` stays for
117
+ * the audit trail. Not called for `confirmed`: a completed job keeps its key.
163
118
  */
164
119
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
165
120
  /** pending → building. Increments the attempt counter. Returns false when lost. */
166
121
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
167
122
  /**
168
- * building → submitting. Commits the signed transaction, its hash, the unsigned
169
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
170
- * state: whatever happens to the process during `submitTransaction`, the exact
171
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
172
- * key so a caller retry can never turn into a second, differently-built payment.
173
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
123
+ * building → submitting. Commits the signed tx, hash, unsigned CBOR and fee BEFORE the network
124
+ * call, so the exact bytes survive a crash. `submittedAt` is the attempt time, not proof of acceptance.
174
125
  */
175
126
  export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
176
127
  txHash: string;
@@ -178,19 +129,11 @@ export declare function markSubmitting(db: CapTransaction, jobId: string, artifa
178
129
  signedTxCbor: string;
179
130
  fee: string | number | null;
180
131
  }): Promise<boolean>;
181
- /**
182
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
183
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
184
- * is re-asserted, in case the backend canonicalized it.
185
- */
132
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
186
133
  export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
187
134
  /**
188
- * building → pending (transient failure, attempts left). Keeps the error visible
189
- * and defers the next attempt via `notBefore` (exponential backoff).
190
- *
191
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
192
- * mempool, and re-queueing it would rebuild a different transaction from the same
193
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
135
+ * building → pending (transient failure), deferring via `notBefore`. Guarded on `building` only:
136
+ * a `submitting` tx may be in a mempool and a rebuild would double-pay; those rows are reconciled.
194
137
  */
195
138
  export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
196
139
  /** Record where the submitted tx was seen on-chain (not yet at depth). */
@@ -203,9 +146,8 @@ export declare function clearConfirmationPoint(db: CapTransaction, jobId: string
203
146
  /** submitted → confirmed (depth reached). */
204
147
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
205
148
  /**
206
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
207
- * only safe once the chain has been consulted — a failed row releases the
208
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
149
+ * Any active state → failed. Releases the idempotency key, so a `submitting`/`submitted` row
150
+ * may only be failed once the chain has been consulted.
209
151
  */
210
152
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
211
153
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
@@ -219,33 +161,14 @@ export interface RecoveryResult {
219
161
  submittingToReconcile: WalletJobRow[];
220
162
  }
221
163
  /**
222
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
223
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
224
- * lease is held belong to a running executor (possibly on another instance) and
225
- * must not be touched.
226
- *
227
- * Safe by construction: a `building` row is pre-submit by definition — the worker
228
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
229
- * backend, so nothing that is still `building` has ever been sent. Rows that made
230
- * it past that point are `submitting` and are reconciled, never failed here.
164
+ * Fail a wallet's orphaned `building` rows, only when its lease is expired/unowned. A `building`
165
+ * row is pre-submit by definition (the signed CBOR is committed as `submitting` first), so nothing sent is failed.
231
166
  */
232
167
  export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
233
168
  /**
234
- * Boot-time recovery (design §8), by state:
235
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
236
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
237
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
238
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
239
- * chain and re-submits those exact bytes if needed.
240
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
241
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
242
- *
243
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
244
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
245
- * job right now (rolling deploy) — failing it here while its submit succeeds
246
- * would leave a failed row for an on-chain tx, and since failed rows don't block
247
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
248
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
169
+ * Boot-time recovery: `building` → failed PROCESS_RESTART (never sent; only when the wallet lease
170
+ * is expired/unowned, a held lease means another live instance owns it); `submitting` → returned
171
+ * for chain reconciliation, never rebuilt; `submitted` → handed to the confirmation tracker.
249
172
  */
250
173
  export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
251
174
  /** Idempotently register/refresh a configured wallet row (no key material). */
@@ -258,9 +181,8 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
258
181
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
259
182
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
260
183
  /**
261
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
262
- * read-back verification, same shape as the crawler lease). At most one worker
263
- * instance may execute jobs for a wallet at any time.
184
+ * Acquire an expired/unowned per-wallet lease (compare-and-swap + read-back verification).
185
+ * At most one worker instance may execute jobs for a wallet at any time.
264
186
  */
265
187
  export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
266
188
  /** Renew/fence the caller's lease. Call before every job-advancing write. */