@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -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
@@ -0,0 +1,12 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ export interface TxKey {
3
+ hash: string;
4
+ txSeq: number | string | null;
5
+ }
6
+ /** `txSeq` as a stable map key: Int64 columns come back as number or string depending on the driver. */
7
+ export declare const seqKey: (txSeq: number | string) => string;
8
+ /** Hash and txSeq of the given transactions that are indexed. */
9
+ export declare function readTxKeys(tx: CapTransaction, hashes: string[]): Promise<TxKey[]>;
10
+ /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
11
+ export declare function deleteTransactionRows(tx: CapTransaction, keys: TxKey[]): Promise<void>;
12
+ //# sourceMappingURL=transaction-rows.d.ts.map
@@ -0,0 +1,42 @@
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.seqKey = void 0;
7
+ exports.readTxKeys = readTxKeys;
8
+ exports.deleteTransactionRows = deleteTransactionRows;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
+ const collections_1 = require("../utils/collections");
12
+ const { SELECT, DELETE } = cds_1.default.ql;
13
+ /** `txSeq` as a stable map key: Int64 columns come back as number or string depending on the driver. */
14
+ const seqKey = (txSeq) => String(Number(txSeq));
15
+ exports.seqKey = seqKey;
16
+ /** Hash and txSeq of the given transactions that are indexed. */
17
+ async function readTxKeys(tx, hashes) {
18
+ const keys = [];
19
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
20
+ const rows = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ hash: { in: hashChunk } }));
21
+ keys.push(...(rows ?? []));
22
+ }
23
+ return keys;
24
+ }
25
+ /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
26
+ async function deleteTransactionRows(tx, keys) {
27
+ for (const keyChunk of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
28
+ const hashes = keyChunk.map(k => k.hash);
29
+ const seqs = keyChunk.filter(k => k.txSeq != null).map(k => k.txSeq);
30
+ if (seqs.length) {
31
+ await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: { in: seqs } }));
32
+ await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: { in: seqs } }));
33
+ await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqs } }));
34
+ await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: { in: seqs } }));
35
+ }
36
+ await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: hashes } }));
37
+ await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: hashes } }));
38
+ await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: hashes } }));
39
+ await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: hashes } }));
40
+ }
41
+ }
42
+ //# sourceMappingURL=transaction-rows.js.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,12 +37,12 @@ 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). */
40
+ /** Mint-action parsing as in BuildMint/BuildPlutusSpend (bigint quantities, per-action policy fields). */
46
41
  function parseMintActions(raw, allowBareNames) {
47
42
  const parsed = parseJsonField(raw, 'mintActionsJson');
48
43
  if (!Array.isArray(parsed))
49
44
  fail('mintActionsJson must be a JSON array');
50
- return parsed.map((rawAction) => {
45
+ return parsed.map((rawAction, i) => {
51
46
  if (!rawAction || typeof rawAction !== 'object') {
52
47
  fail('Each mint action must be an object with assetUnit and quantity');
53
48
  }
@@ -57,14 +52,37 @@ function parseMintActions(raw, allowBareNames) {
57
52
  }
58
53
  if (typeof action.assetUnit !== 'string')
59
54
  fail('Each mint action must have an assetUnit string');
60
- const bareAssetNameForExpansion = allowBareNames &&
55
+ // Optional per-action mintingPolicyScript + redeemerJson (multi-policy mint).
56
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, i);
57
+ if (policyFields.error)
58
+ fail(policyFields.error);
59
+ let actionPolicyId;
60
+ if (policyFields.script) {
61
+ actionPolicyId = scriptHashOf(policyFields.script, `mintActions[${i}].mintingPolicyScript is not a valid Plutus script`);
62
+ }
63
+ const bareAssetNameForExpansion = (allowBareNames || !!actionPolicyId) &&
61
64
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
62
65
  action.assetUnit.length % 2 === 0 &&
63
66
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
64
67
  if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
65
- fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson is set)`);
68
+ fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson or a per-action mintingPolicyScript is set)`);
69
+ }
70
+ let assetUnit = action.assetUnit;
71
+ if (actionPolicyId) {
72
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
73
+ assetUnit = actionPolicyId + assetUnit;
74
+ }
75
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
76
+ fail(`mintActions[${i}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`);
77
+ }
66
78
  }
67
- return { assetUnit: action.assetUnit, quantity: BigInt(action.quantity) };
79
+ return {
80
+ assetUnit,
81
+ quantity: BigInt(action.quantity),
82
+ ...(typeof action.redeemer === 'number' ? { redeemer: action.redeemer } : {}),
83
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
84
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
85
+ };
68
86
  });
69
87
  }
70
88
  function scriptHashOf(scriptHex, context) {
@@ -76,12 +94,12 @@ function scriptHashOf(scriptHex, context) {
76
94
  }
77
95
  }
78
96
  /**
79
- * BUG 9 mirror: every (expanded) mint action must carry the effective policy id —
80
- * parseAssetUnit silently discards the first 56 hex chars, so a mismatched prefix
81
- * 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.
82
99
  */
83
100
  function assertPolicyPrefix(actions, policyId) {
84
- const mismatch = actions.find((a) => !a.assetUnit.toLowerCase().startsWith(policyId));
101
+ // Actions with their own script were already checked against that script's policy id.
102
+ const mismatch = actions.find((a) => !a.mintingPolicyScript && !a.assetUnit.toLowerCase().startsWith(policyId));
85
103
  if (mismatch) {
86
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)`);
87
105
  }
@@ -153,6 +171,7 @@ function prepareMint(raw, network) {
153
171
  const mintRedeemer = parseJsonField(raw, 'mintRedeemerJson');
154
172
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
155
173
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
174
+ const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
156
175
  if (raw.lockOnScript && (!scriptParams || scriptParams.length === 0)) {
157
176
  fail('lockOnScript requires scriptParamsJson to derive script address');
158
177
  }
@@ -172,6 +191,7 @@ function prepareMint(raw, network) {
172
191
  delete clean.lockOnScript;
173
192
  delete clean.forceInputsJson;
174
193
  delete clean.referenceInputsJson;
194
+ delete clean.extraOutputsJson;
175
195
  if (parsedMetadata)
176
196
  clean.metadataJson = parsedMetadata;
177
197
  else
@@ -179,8 +199,7 @@ function prepareMint(raw, network) {
179
199
  if (raw.referenceScriptHex)
180
200
  clean.referenceScript = raw.referenceScriptHex;
181
201
  delete clean.referenceScriptHex;
182
- // Apply script parameters (parameterized policies), expand bare asset names,
183
- // route lockOnScript output — mirrors BuildMintTransaction.
202
+ // Apply script parameters, expand bare asset names, route lockOnScript output.
184
203
  let finalMintingPolicyScript = raw.mintingPolicyScript;
185
204
  let effectivePolicyId;
186
205
  if (scriptParams && scriptParams.length > 0) {
@@ -219,6 +238,7 @@ function prepareMint(raw, network) {
219
238
  mintRedeemer,
220
239
  forceInputs,
221
240
  referenceInputs,
241
+ extraOutputs,
222
242
  };
223
243
  }
224
244
  function preparePlutusSpend(raw, network) {
@@ -237,7 +257,7 @@ function preparePlutusSpend(raw, network) {
237
257
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
238
258
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
239
259
  const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
240
- // Optional combined spend+mint (FR-1) — mirrors BuildPlutusSpendTransaction.
260
+ // Optional combined spend+mint.
241
261
  const validatorScript = raw.validatorScript;
242
262
  const mintingPolicyScript = raw.mintingPolicyScript;
243
263
  let mintActions;
@@ -322,11 +342,7 @@ function preparePlutusSpend(raw, network) {
322
342
  delete clean.lockOnScript;
323
343
  return clean;
324
344
  }
325
- /**
326
- * Transform the raw job request (documented Build*-action payload) into the
327
- * TxBuildRequest the matching CardanoIndexer build method expects. Throws
328
- * BackendError 400 INVALID_INPUT for malformed payloads (terminal job failure).
329
- */
345
+ /** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
330
346
  function prepareWorkerBuildRequest(kind, raw, network) {
331
347
  switch (kind) {
332
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;
@@ -28,6 +16,11 @@ export interface TrackedJob {
28
16
  submittedAt: string;
29
17
  foundSlot: number | null;
30
18
  foundHeight: number | null;
19
+ /**
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.
22
+ */
23
+ seenRound?: number;
31
24
  }
32
25
  export interface ConfirmationTrackerOptions {
33
26
  confirmationDepth: number;
@@ -59,6 +52,8 @@ export declare class ConfirmationTracker {
59
52
  private running;
60
53
  private polling;
61
54
  private lastKnownTipHeight;
55
+ /** Polling round counter; see TrackedJob.seenRound. */
56
+ private round;
62
57
  constructor(deps: ConfirmationTrackerDeps);
63
58
  start(): void;
64
59
  stop(): void;
@@ -77,10 +72,23 @@ export declare class ConfirmationTracker {
77
72
  }): void;
78
73
  private onBlockIndexed;
79
74
  private onReorg;
75
+ /**
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.
78
+ */
79
+ private forgetInclusion;
80
80
  /** One polling round. Public for tests; guarded against overlapping rounds. */
81
81
  pollOnce(): Promise<void>;
82
- /** Confirm every found job whose depth requirement is met by the known tip. */
82
+ /**
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.
85
+ */
83
86
  private confirmMature;
87
+ /**
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.
90
+ */
91
+ private stillIncluded;
84
92
  private finalize;
85
93
  }
86
94
  //# sourceMappingURL=confirmation-tracker.d.ts.map
@@ -18,6 +18,8 @@ class ConfirmationTracker {
18
18
  running = false;
19
19
  polling = false;
20
20
  lastKnownTipHeight = null;
21
+ /** Polling round counter; see TrackedJob.seenRound. */
22
+ round = 0;
21
23
  constructor(deps) {
22
24
  this.deps = deps;
23
25
  }
@@ -69,7 +71,7 @@ class ConfirmationTracker {
69
71
  }
70
72
  const txHashes = new Set(event.txHashes);
71
73
  const found = [...this.pending.values()].filter(j => j.foundHeight == null && txHashes.has(j.txHash));
72
- // Persist + depth-check detached: hook callers (the crawler) must not await us.
74
+ // Detached: hook callers (the crawler) must not await us.
73
75
  void (async () => {
74
76
  for (const job of found) {
75
77
  job.foundSlot = event.slot;
@@ -88,44 +90,48 @@ class ConfirmationTracker {
88
90
  async onReorg(event) {
89
91
  if (!this.running)
90
92
  return;
91
- // The pre-fork tip no longer exists — clamp (or drop) lastKnownTipHeight so
92
- // confirmations are never counted against it. Without this, a tx re-included
93
- // on the new chain would reach "depth" instantly via the stale tip height,
94
- // 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.
95
95
  if (event.forkHeight != null) {
96
96
  if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
97
97
  this.lastKnownTipHeight = event.forkHeight;
98
98
  }
99
99
  }
100
100
  else {
101
- this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
101
+ this.lastKnownTipHeight = null; // re-learn from the next block/poll
102
102
  }
103
103
  for (const job of this.pending.values()) {
104
104
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
105
105
  logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
106
- job.foundSlot = null;
107
- job.foundHeight = null;
108
- try {
109
- await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
110
- }
111
- catch (err) {
112
- logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
106
+ await this.forgetInclusion(job);
107
+ }
108
+ }
109
+ }
110
+ /**
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.
113
+ */
114
+ async forgetInclusion(job) {
115
+ job.foundSlot = null;
116
+ job.foundHeight = null;
117
+ job.seenRound = undefined;
118
+ try {
119
+ await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
120
+ }
121
+ catch (err) {
122
+ logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
123
+ }
124
+ if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
125
+ try {
126
+ await this.deps.client.submitTransaction(job.signedTxCbor);
127
+ logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
128
+ }
129
+ catch (err) {
130
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
131
+ logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
113
132
  }
114
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
115
- // SAME signed CBOR only — never a rebuild. "Already known" means the tx
116
- // survived into the new chain's mempool; that is success, not an error.
117
- try {
118
- await this.deps.client.submitTransaction(job.signedTxCbor);
119
- logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
120
- }
121
- catch (err) {
122
- if (err instanceof errors_1.TransactionAlreadySubmittedError) {
123
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
124
- }
125
- else {
126
- logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
127
- }
128
- }
133
+ else {
134
+ logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
129
135
  }
130
136
  }
131
137
  }
@@ -136,9 +142,9 @@ class ConfirmationTracker {
136
142
  if (!this.running || this.polling || this.pending.size === 0)
137
143
  return;
138
144
  this.polling = true;
145
+ this.round++;
139
146
  try {
140
- // Tip first — also serves the depth check for hook-found entries when the
141
- // crawler is off.
147
+ // Tip first — also the depth check for hook-found entries when the crawler is off.
142
148
  try {
143
149
  const tip = await this.deps.client.getLatestBlock();
144
150
  if (tip.height != null) {
@@ -156,13 +162,13 @@ class ConfirmationTracker {
156
162
  const tx = await this.deps.client.getTransaction(job.txHash);
157
163
  job.foundSlot = tx.slot ?? null;
158
164
  job.foundHeight = tx.blockHeight ?? null;
165
+ job.seenRound = this.round;
159
166
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
160
167
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
161
168
  }
162
169
  catch (err) {
163
- // The client's failover wraps per-backend 404s into AllBackendsFailedError,
164
- // so a plain `instanceof NotFoundError` check never fires — the helper also
165
- // 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.
166
172
  if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
167
173
  // Not on-chain yet — check the mempool-TTL timeout.
168
174
  const age = Date.now() - Date.parse(job.submittedAt);
@@ -175,31 +181,66 @@ class ConfirmationTracker {
175
181
  }
176
182
  }
177
183
  }
178
- await this.confirmMature();
184
+ // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
185
+ await this.confirmMature(true);
179
186
  }
180
187
  finally {
181
188
  this.polling = false;
182
189
  }
183
190
  }
184
191
  // ---- Shared -----------------------------------------------------------------
185
- /** Confirm every found job whose depth requirement is met by the known tip. */
186
- async confirmMature() {
192
+ /**
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.
195
+ */
196
+ async confirmMature(revalidate = false) {
187
197
  const tip = this.lastKnownTipHeight;
188
198
  if (tip == null)
189
199
  return;
190
200
  for (const job of [...this.pending.values()]) {
191
201
  if (job.foundHeight == null)
192
202
  continue;
193
- const confirmations = tip - job.foundHeight + 1;
194
- if (confirmations >= this.deps.options.confirmationDepth) {
195
- await this.finalize(job, 'confirmed');
203
+ if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
204
+ continue;
205
+ if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
206
+ continue;
207
+ await this.finalize(job, 'confirmed');
208
+ }
209
+ }
210
+ /**
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.
213
+ */
214
+ async stillIncluded(job, tip) {
215
+ try {
216
+ const tx = await this.deps.client.getTransaction(job.txHash);
217
+ const height = tx.blockHeight ?? null;
218
+ job.seenRound = this.round;
219
+ if (height != null && height !== job.foundHeight) {
220
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
221
+ job.foundHeight = height;
222
+ job.foundSlot = tx.slot ?? null;
223
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
224
+ return tip - height + 1 >= this.deps.options.confirmationDepth;
225
+ }
226
+ return true;
227
+ }
228
+ catch (err) {
229
+ if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
230
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
231
+ this.lastKnownTipHeight = null;
232
+ await this.forgetInclusion(job);
233
+ return false;
196
234
  }
235
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
236
+ return false;
197
237
  }
198
238
  }
199
239
  async finalize(job, outcome, errorCode, err) {
240
+ let transitioned = false;
200
241
  try {
201
242
  await cds_1.default.tx(async (tx) => {
202
- const transitioned = outcome === 'confirmed'
243
+ transitioned = outcome === 'confirmed'
203
244
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
204
245
  : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
205
246
  if (transitioned) {
@@ -209,9 +250,14 @@ class ConfirmationTracker {
209
250
  }
210
251
  catch (persistErr) {
211
252
  logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
212
- return; // keep tracking — the next poll round retries the transition
253
+ return; // keep tracking — the next round retries
213
254
  }
214
255
  this.pending.delete(job.jobId);
256
+ if (!transitioned) {
257
+ // Another actor reached the terminal state first; stats bump and event belong to it.
258
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
259
+ return;
260
+ }
215
261
  logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
216
262
  this.deps.onFinal?.({
217
263
  jobId: job.jobId,
@@ -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();