@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,24 +1,13 @@
1
1
  import type { UTxO as OdatanoUtxo, JSONValue } from '../utils/types';
2
2
  import { type Data } from '@harmoniclabs/plutus-data';
3
3
  import { UPLCConst } from '@harmoniclabs/uplc';
4
- /**
5
- * Extract lovelace amount from UTxO
6
- * @param u UTxO to extract from
7
- * @returns {bigint} lovelace amount
8
- */
4
+ /** Lovelace amount of a UTxO. */
9
5
  export declare function getLovelace(u: OdatanoUtxo): bigint;
10
- /**
11
- * Assert that UTxO contains only ADA (lovelace)
12
- * @param u UTxO to check
13
- * @throws {MixedAssetsError} if UTxO contains non-ADA assets
14
- */
6
+ /** Throws MixedAssetsError when the UTxO carries non-ADA assets. */
15
7
  export declare function assertAdaOnly(u: OdatanoUtxo): void;
16
8
  /**
17
- * Extract transaction hash from a transaction CBOR (signed or unsigned).
18
- * Hash is computed over the body, so witness presence does not affect it.
19
- * @param txCbor transaction in CBOR hex format
20
- * @returns {string} transaction hash (64 character hex string)
21
- * @throws {Error} if CBOR is invalid or transaction hash cannot be extracted
9
+ * Transaction hash of a signed or unsigned tx CBOR: blake2b-256 over the body bytes, so witnesses do not affect it.
10
+ * @returns 64-char hex string
22
11
  */
23
12
  export declare function getTxHashFromCbor(txCbor: string): string;
24
13
  /** Cache-invalidation targets of a submitted transaction (see extractTxCacheTargets). */
@@ -32,102 +21,39 @@ export interface TxCacheTargets {
32
21
  outputAddresses: string[];
33
22
  }
34
23
  /**
35
- * Extract the consumed input refs and the output addresses from a transaction
36
- * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
37
- * UTxO cache. Works at the raw-CBOR level for the same reason as
38
- * getTxHashFromCbor (byte-exact, no high-level Tx round-trip).
39
- *
40
- * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
41
- * addresses) are skipped — invalidation is best-effort per address.
42
- *
43
- * @param txCbor transaction in CBOR hex format
44
- * @throws {TransactionValidationError} if the CBOR is not a transaction
24
+ * Consumed input refs and output addresses of a tx CBOR: the UTxO-cache rows a submit makes stale.
25
+ * Outputs whose address bytes cannot be decoded (Byron) are skipped.
45
26
  */
46
27
  export declare function extractTxCacheTargets(txCbor: string): TxCacheTargets;
47
28
  /**
48
- * Maps builder errors to typed BackendErrors
49
- * Used by the Buildooor transaction builder.
50
- * When no assetUnit is provided, extracts it from the error message if possible
51
- * (e.g. "not enough <policyId.assetName>"), falling back to 'lovelace'.
52
- * @param err Error from builder
53
- * @param assetUnit Optional asset unit override (auto-extracted from error message if omitted)
54
- * @param context Optional build-flow context (e.g. the collateral/funding partition)
55
- * appended to the consumer-facing message — the builder's own message
56
- * has no way of knowing it
57
- * @throws {InsufficientFundsError} if error is related to insufficient funds
58
- * @throws {Error} original error if not mappable
29
+ * Maps Buildooor errors to typed BackendErrors. Asset unit is parsed from "not enough <unit>" when not given;
30
+ * `context` (e.g. the collateral partition) is appended to the consumer-facing message.
59
31
  */
60
32
  export declare function mapBuilderError(err: unknown, assetUnit?: string, context?: string): never;
61
- /**
62
- * Parse asset unit string into policyId and assetName
63
- * Format: policyId (56 hex chars) + assetName (remaining hex)
64
- * Used by the Buildooor transaction builder
65
- */
33
+ /** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
66
34
  export declare function parseAssetUnit(assetUnit: string): {
67
35
  policyId: string;
68
36
  assetName: string;
69
37
  };
70
- /**
71
- * Convert JSON value to Buildooor PlutusData (Data type).
72
- * Accepts both cardano-cli format ("constructor") and Buildooor format ("constr").
73
- * - { "int": 42 } → DataI(42)
74
- * - { "bytes": "deadbeef" } → DataB("deadbeef")
75
- * - { "list": [...] } → DataList([...])
76
- * - { "map": [{ "k": ..., "v": ... }] } → DataMap([...])
77
- * - { "constructor": 0, "fields": [...] } or { "constr": 0, "fields": [...] } → DataConstr(0, [...])
78
- * @param json JSON value representing PlutusData
79
- * @returns Buildooor Data object
80
- */
38
+ /** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
81
39
  export declare function jsonToPlutusData(json: JSONValue): Data;
82
40
  /**
83
- * Normalize a backend-provided inline datum to canonical CBOR hex.
84
- *
85
- * Backends report inline datums in different shapes:
86
- * - Blockfrost: hex CBOR string (e.g. "19a6aa")
87
- * - Koios (_extended): wrapper { bytes: "<hex>", value: { ...PlutusData JSON... } }
88
- * - Koios (sometimes empty): { bytes: null, value: null }
89
- * - Some endpoints: raw PlutusData JSON ({ "int": 42 } / { "constructor": 0, "fields": [] })
90
- *
91
- * Returns hex CBOR (lowercase) or null. Defensive: returns null on unknown
92
- * shapes rather than throwing — backend mappers must not crash on malformed data.
41
+ * Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
42
+ * or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
93
43
  */
94
44
  export declare function inlineDatumToHex(datum: unknown): string | null;
95
45
  /** UPLC type tag for a typed script parameter (see {@link encodeScriptParam}). */
96
46
  export type ScriptParamUplcType = 'data' | 'bytes' | 'int' | 'bool' | 'unit';
97
47
  /**
98
- * Encode a single script parameter into the UPLC constant the parameterized
99
- * script expects.
100
- *
101
- * A script parameter is applied as a UPLC constant whose TYPE must match what
102
- * the compiled validator expects for that parameter. Two input shapes are
103
- * accepted:
104
- *
105
- * 1. Typed — `{ "uplc": "<type>", "value": <...> }`:
106
- * - `"data"` → `UPLCConst.data(...)` value: PlutusData JSON ("constr"/cardano-cli form)
107
- * - `"bytes"` → `UPLCConst.byteString(...)` value: even-length hex string
108
- * - `"int"` → `UPLCConst.int(...)` value: number | numeric string
109
- * - `"bool"` → `UPLCConst.bool(...)` value: boolean
110
- * - `"unit"` → `UPLCConst.unit` value: omitted
111
- * Required for compilers whose scalar params are NATIVE-typed rather than
112
- * Data-wrapped (e.g. Pebble: `param x: PubKeyHash` expects a native
113
- * `bytestring`, not a `Data` bytestring).
114
- *
115
- * 2. Bare PlutusData object (e.g. `{ "bytes": "ab.." }`, `{ "constructor": 0, ... }`)
116
- * — shorthand for `{ "uplc": "data", "value": <object> }`. This is the
117
- * Aiken / CIP-57 blueprint convention, where every parameter is Data.
48
+ * Encode a script parameter as the UPLC constant of the type the validator expects: typed
49
+ * `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
50
+ * (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
118
51
  */
119
52
  export declare function encodeScriptParam(param: JSONValue): UPLCConst;
120
53
  /**
121
- * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC).
122
- * Each parameter becomes a successive UPLC Application wrapping the program body.
123
- *
124
- * Parameters are applied in their declared UPLC type via {@link encodeScriptParam}:
125
- * pass `{ uplc, value }` entries for native-typed params (e.g. Pebble scalars),
126
- * or bare PlutusData objects for the Data convention (Aiken / CIP-57 blueprints).
127
- *
128
- * @param scriptHex CBOR hex of the unapplied Plutus script (as output by Aiken/Pebble/Plutus compilers)
129
- * @param params Array of script parameters (typed `{uplc,value}` and/or bare PlutusData JSON) to apply in order
130
- * @returns CBOR hex of the applied script (ready for transaction building)
54
+ * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
55
+ * UPLC Application around the program body, encoded via {@link encodeScriptParam}.
56
+ * @returns CBOR hex of the applied script
131
57
  */
132
58
  export declare function applyScriptParameters(scriptHex: string, params: JSONValue[]): string;
133
59
  //# sourceMappingURL=tx-build-helper.d.ts.map
@@ -18,20 +18,12 @@ const plutus_data_1 = require("@harmoniclabs/plutus-data");
18
18
  const uplc_1 = require("@harmoniclabs/uplc");
19
19
  const cbor_1 = require("@harmoniclabs/cbor");
20
20
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
21
- /**
22
- * Extract lovelace amount from UTxO
23
- * @param u UTxO to extract from
24
- * @returns {bigint} lovelace amount
25
- */
21
+ /** Lovelace amount of a UTxO. */
26
22
  function getLovelace(u) {
27
23
  const entry = u.amount.find(a => (a.unit).toLowerCase() === "lovelace");
28
24
  return BigInt(entry?.quantity ?? "0");
29
25
  }
30
- /**
31
- * Assert that UTxO contains only ADA (lovelace)
32
- * @param u UTxO to check
33
- * @throws {MixedAssetsError} if UTxO contains non-ADA assets
34
- */
26
+ /** Throws MixedAssetsError when the UTxO carries non-ADA assets. */
35
27
  function assertAdaOnly(u) {
36
28
  const nonAda = u.amount.filter(a => (a.unit).toLowerCase() !== "lovelace" && BigInt(a.quantity) !== 0n);
37
29
  if (nonAda.length > 0) {
@@ -39,27 +31,18 @@ function assertAdaOnly(u) {
39
31
  }
40
32
  }
41
33
  /**
42
- * Extract transaction hash from a transaction CBOR (signed or unsigned).
43
- * Hash is computed over the body, so witness presence does not affect it.
44
- * @param txCbor transaction in CBOR hex format
45
- * @returns {string} transaction hash (64 character hex string)
46
- * @throws {Error} if CBOR is invalid or transaction hash cannot be extracted
34
+ * Transaction hash of a signed or unsigned tx CBOR: blake2b-256 over the body bytes, so witnesses do not affect it.
35
+ * @returns 64-char hex string
47
36
  */
48
37
  function getTxHashFromCbor(txCbor) {
49
38
  if (!txCbor || typeof txCbor !== 'string') {
50
39
  throw new Error('Invalid input: txCbor must be a non-empty string');
51
40
  }
52
- // Validate hex format. Require even length — a hex byte string encodes whole bytes,
53
- // so an odd-length string is malformed and would otherwise surface as a confusing
54
- // "Failed to parse transaction CBOR" from fromHex/Cbor.parse rather than a clear
55
- // input-validation error.
41
+ // Even length: an odd hex string would otherwise fail later as a confusing parse error
56
42
  if (!/^[a-fA-F0-9]+$/.test(txCbor) || txCbor.length % 2 !== 0) {
57
43
  throw new Error('Invalid input: txCbor must be a valid hex string');
58
44
  }
59
- // Compute blake2b-256 over the ORIGINAL transaction-body bytes (CBOR array index 0).
60
- // subCborRef.toBuffer() returns the exact bytes as received — no re-serialization, so
61
- // the hash matches what was signed. We stay at the raw-CBOR level (never instantiate
62
- // the high-level Tx type) for that byte-exactness.
45
+ // Hash the ORIGINAL body bytes via subCborRef (no re-serialization), so it matches what was signed
63
46
  try {
64
47
  const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
65
48
  if (!(tx instanceof cbor_1.CborArray) || tx.array.length < 1 || !tx.array[0].subCborRef) {
@@ -69,21 +52,12 @@ function getTxHashFromCbor(txCbor) {
69
52
  return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(bodyBytes));
70
53
  }
71
54
  catch (err) {
72
- // typed 400 — a plain Error here surfaced as a 500 to the consumer
73
55
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
74
56
  }
75
57
  }
76
58
  /**
77
- * Extract the consumed input refs and the output addresses from a transaction
78
- * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
79
- * UTxO cache. Works at the raw-CBOR level for the same reason as
80
- * getTxHashFromCbor (byte-exact, no high-level Tx round-trip).
81
- *
82
- * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
83
- * addresses) are skipped — invalidation is best-effort per address.
84
- *
85
- * @param txCbor transaction in CBOR hex format
86
- * @throws {TransactionValidationError} if the CBOR is not a transaction
59
+ * Consumed input refs and output addresses of a tx CBOR: the UTxO-cache rows a submit makes stale.
60
+ * Outputs whose address bytes cannot be decoded (Byron) are skipped.
87
61
  */
88
62
  function extractTxCacheTargets(txCbor) {
89
63
  let body;
@@ -98,7 +72,7 @@ function extractTxCacheTargets(txCbor) {
98
72
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
99
73
  }
100
74
  const bodyValue = (key) => body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v;
101
- // key 0: inputs — plain array or a CBOR tag-258 set (Conway)
75
+ // key 0: inputs, plain array or CBOR tag-258 set (Conway)
102
76
  const inputs = [];
103
77
  let inputsObj = bodyValue(0);
104
78
  if (inputsObj instanceof cbor_1.CborTag)
@@ -112,7 +86,7 @@ function extractTxCacheTargets(txCbor) {
112
86
  }
113
87
  }
114
88
  }
115
- // key 1: outputs — post-alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
89
+ // key 1: outputs, post-Alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
116
90
  const outputAddresses = new Set();
117
91
  const outputsObj = bodyValue(1);
118
92
  if (outputsObj instanceof cbor_1.CborArray) {
@@ -126,29 +100,18 @@ function extractTxCacheTargets(txCbor) {
126
100
  outputAddresses.add(cardano_ledger_ts_1.Address.fromBuffer(addrObj.bytes).toString());
127
101
  }
128
102
  catch {
129
- // non-Shelley address bytes — nothing cached under a bech32 key for it
103
+ // non-Shelley address bytes: nothing cached under a bech32 key
130
104
  }
131
105
  }
132
106
  }
133
107
  return { inputs, outputAddresses: [...outputAddresses] };
134
108
  }
135
109
  /**
136
- * Maps builder errors to typed BackendErrors
137
- * Used by the Buildooor transaction builder.
138
- * When no assetUnit is provided, extracts it from the error message if possible
139
- * (e.g. "not enough <policyId.assetName>"), falling back to 'lovelace'.
140
- * @param err Error from builder
141
- * @param assetUnit Optional asset unit override (auto-extracted from error message if omitted)
142
- * @param context Optional build-flow context (e.g. the collateral/funding partition)
143
- * appended to the consumer-facing message — the builder's own message
144
- * has no way of knowing it
145
- * @throws {InsufficientFundsError} if error is related to insufficient funds
146
- * @throws {Error} original error if not mappable
110
+ * Maps Buildooor errors to typed BackendErrors. Asset unit is parsed from "not enough <unit>" when not given;
111
+ * `context` (e.g. the collateral partition) is appended to the consumer-facing message.
147
112
  */
148
113
  function mapBuilderError(err, assetUnit, context) {
149
- // Already-typed errors carry their own status + payload (amounts, asset units,
150
- // validation details) — re-wrapping them into a generic InsufficientFundsError
151
- // because their MESSAGE happens to contain "balance"/"insufficient" destroys that.
114
+ // Typed errors keep their own status and payload
152
115
  if (err instanceof errors_1.BackendError) {
153
116
  throw err;
154
117
  }
@@ -162,24 +125,19 @@ function mapBuilderError(err, assetUnit, context) {
162
125
  const match = msg.match(/not enough\s+([a-f0-9.]+)/i);
163
126
  return match?.[1] || 'lovelace';
164
127
  })();
165
- // The builder knows no amounts here — surface its own message (plus the build
166
- // context) instead of a meaningless "required 0, available 0".
128
+ // No amounts known here: surface the builder's own message instead of "required 0, available 0"
167
129
  throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err, context ? `${rawMsg} (${context})` : rawMsg);
168
130
  }
169
131
  throw err;
170
132
  }
171
- /**
172
- * Parse asset unit string into policyId and assetName
173
- * Format: policyId (56 hex chars) + assetName (remaining hex)
174
- * Used by the Buildooor transaction builder
175
- */
133
+ /** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
176
134
  function parseAssetUnit(assetUnit) {
177
135
  return {
178
136
  policyId: assetUnit.substring(0, 56),
179
137
  assetName: assetUnit.substring(56)
180
138
  };
181
139
  }
182
- /** Allowed keys in PlutusData JSON — strip anything else for defense-in-depth */
140
+ /** Allowed keys in PlutusData JSON; anything else is stripped */
183
141
  const PLUTUS_DATA_ALLOWED_KEYS = new Set([
184
142
  'constructor', 'constr', 'fields', 'int', 'bytes', 'list', 'map', 'k', 'v'
185
143
  ]);
@@ -193,11 +151,7 @@ function sanitizePlutusKeys(obj) {
193
151
  }
194
152
  return clean;
195
153
  }
196
- /**
197
- * Normalize PlutusData JSON from cardano-cli format ("constructor") to
198
- * Buildooor format ("constr"), recursively through fields/list/map.
199
- * Also strips unrecognized keys for safety.
200
- */
154
+ /** Normalize cardano-cli "constructor" to Buildooor "constr" recursively; strips unknown keys. */
201
155
  function normalizeConstructorKey(obj) {
202
156
  const safe = sanitizePlutusKeys(obj);
203
157
  const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -222,17 +176,7 @@ function normalizeConstructorKey(obj) {
222
176
  }
223
177
  return safe;
224
178
  }
225
- /**
226
- * Convert JSON value to Buildooor PlutusData (Data type).
227
- * Accepts both cardano-cli format ("constructor") and Buildooor format ("constr").
228
- * - { "int": 42 } → DataI(42)
229
- * - { "bytes": "deadbeef" } → DataB("deadbeef")
230
- * - { "list": [...] } → DataList([...])
231
- * - { "map": [{ "k": ..., "v": ... }] } → DataMap([...])
232
- * - { "constructor": 0, "fields": [...] } or { "constr": 0, "fields": [...] } → DataConstr(0, [...])
233
- * @param json JSON value representing PlutusData
234
- * @returns Buildooor Data object
235
- */
179
+ /** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
236
180
  function jsonToPlutusData(json) {
237
181
  if (json === null || json === undefined) {
238
182
  throw new Error('PlutusData JSON cannot be null or undefined');
@@ -244,21 +188,13 @@ function jsonToPlutusData(json) {
244
188
  throw new Error(`Unsupported PlutusData JSON format: expected an object with "int", "bytes", "list", "map", or "constructor" key`);
245
189
  }
246
190
  /**
247
- * Normalize a backend-provided inline datum to canonical CBOR hex.
248
- *
249
- * Backends report inline datums in different shapes:
250
- * - Blockfrost: hex CBOR string (e.g. "19a6aa")
251
- * - Koios (_extended): wrapper { bytes: "<hex>", value: { ...PlutusData JSON... } }
252
- * - Koios (sometimes empty): { bytes: null, value: null }
253
- * - Some endpoints: raw PlutusData JSON ({ "int": 42 } / { "constructor": 0, "fields": [] })
254
- *
255
- * Returns hex CBOR (lowercase) or null. Defensive: returns null on unknown
256
- * shapes rather than throwing — backend mappers must not crash on malformed data.
191
+ * Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
192
+ * or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
257
193
  */
258
194
  function inlineDatumToHex(datum) {
259
195
  if (datum === null || datum === undefined)
260
196
  return null;
261
- // Already hex CBOR (Blockfrost path, or pre-normalized)
197
+ // Already hex CBOR
262
198
  if (typeof datum === 'string') {
263
199
  const s = datum.trim();
264
200
  if (!s)
@@ -268,8 +204,7 @@ function inlineDatumToHex(datum) {
268
204
  if (typeof datum !== 'object' || Array.isArray(datum))
269
205
  return null;
270
206
  const obj = datum;
271
- // Koios wrapper: { bytes: "<hex>", value: <PlutusData JSON> }.
272
- // Distinguished from raw PlutusData {bytes:"deadbeef"} by the presence of `value`.
207
+ // Koios wrapper { bytes, value }; `value` distinguishes it from raw PlutusData { bytes }
273
208
  if ('value' in obj && typeof obj.bytes === 'string' && obj.bytes.length > 0) {
274
209
  const hex = obj.bytes.trim();
275
210
  return /^[0-9a-fA-F]+$/.test(hex) && hex.length % 2 === 0 ? hex.toLowerCase() : null;
@@ -290,26 +225,9 @@ function inlineDatumToHex(datum) {
290
225
  }
291
226
  }
292
227
  /**
293
- * Encode a single script parameter into the UPLC constant the parameterized
294
- * script expects.
295
- *
296
- * A script parameter is applied as a UPLC constant whose TYPE must match what
297
- * the compiled validator expects for that parameter. Two input shapes are
298
- * accepted:
299
- *
300
- * 1. Typed — `{ "uplc": "<type>", "value": <...> }`:
301
- * - `"data"` → `UPLCConst.data(...)` value: PlutusData JSON ("constr"/cardano-cli form)
302
- * - `"bytes"` → `UPLCConst.byteString(...)` value: even-length hex string
303
- * - `"int"` → `UPLCConst.int(...)` value: number | numeric string
304
- * - `"bool"` → `UPLCConst.bool(...)` value: boolean
305
- * - `"unit"` → `UPLCConst.unit` value: omitted
306
- * Required for compilers whose scalar params are NATIVE-typed rather than
307
- * Data-wrapped (e.g. Pebble: `param x: PubKeyHash` expects a native
308
- * `bytestring`, not a `Data` bytestring).
309
- *
310
- * 2. Bare PlutusData object (e.g. `{ "bytes": "ab.." }`, `{ "constructor": 0, ... }`)
311
- * — shorthand for `{ "uplc": "data", "value": <object> }`. This is the
312
- * Aiken / CIP-57 blueprint convention, where every parameter is Data.
228
+ * Encode a script parameter as the UPLC constant of the type the validator expects: typed
229
+ * `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
230
+ * (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
313
231
  */
314
232
  function encodeScriptParam(param) {
315
233
  if (param !== null &&
@@ -351,36 +269,27 @@ function encodeScriptParam(param) {
351
269
  throw new Error(`Unknown script param uplc type "${String(uplc)}"; expected one of: data, bytes, int, bool, unit`);
352
270
  }
353
271
  }
354
- // Bare PlutusData → apply as Data (Aiken / blueprint convention)
272
+ // Bare PlutusData: apply as Data
355
273
  return uplc_1.UPLCConst.data(jsonToPlutusData(param));
356
274
  }
357
275
  /**
358
- * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC).
359
- * Each parameter becomes a successive UPLC Application wrapping the program body.
360
- *
361
- * Parameters are applied in their declared UPLC type via {@link encodeScriptParam}:
362
- * pass `{ uplc, value }` entries for native-typed params (e.g. Pebble scalars),
363
- * or bare PlutusData objects for the Data convention (Aiken / CIP-57 blueprints).
364
- *
365
- * @param scriptHex CBOR hex of the unapplied Plutus script (as output by Aiken/Pebble/Plutus compilers)
366
- * @param params Array of script parameters (typed `{uplc,value}` and/or bare PlutusData JSON) to apply in order
367
- * @returns CBOR hex of the applied script (ready for transaction building)
276
+ * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
277
+ * UPLC Application around the program body, encoded via {@link encodeScriptParam}.
278
+ * @returns CBOR hex of the applied script
368
279
  */
369
280
  function applyScriptParameters(scriptHex, params) {
370
281
  if (!Array.isArray(params) || params.length === 0) {
371
282
  throw new Error('Script parameters must be a non-empty array');
372
283
  }
373
- // 1. CBOR-decode script hex → get inner flat UPLC bytes
284
+ // CBOR-unwrap to the flat UPLC bytes
374
285
  const cborObj = cbor_1.Cbor.parse(scriptHex);
375
286
  const flatBytes = cborObj.bytes;
376
- // 2. Flat-decode → UPLCProgram
377
287
  const program = uplc_1.UPLCDecoder.parse(flatBytes, 'flat');
378
- // 3. Apply each parameter as Application(body, <typed UPLC constant>)
379
288
  let body = program.body;
380
289
  for (const param of params) {
381
290
  body = new uplc_1.Application(body, encodeScriptParam(param));
382
291
  }
383
- // 4. Create new program with applied body, flat-encode, CBOR-wrap
292
+ // Flat-encode the applied program and CBOR-wrap it again
384
293
  const applied = new uplc_1.UPLCProgram(program.version, body);
385
294
  const appliedFlatBytes = (0, uplc_1.compileUPLC)(applied);
386
295
  const cborEncoded = cbor_1.Cbor.encode(new cbor_1.CborBytes(appliedFlatBytes));
@@ -1,12 +1,7 @@
1
1
  import type { JSONValue } from './types';
2
2
  /**
3
- * Shared parsers for the Build*-action JSON payload fields. Used by the
4
- * synchronous CardanoTransactionService handlers AND the wallet-worker's
5
- * request transformation (srv/blockchain/wallet-worker/build-request.ts) so
6
- * both paths accept exactly the same payload shape.
7
- *
8
- * Result contract: { parsed } on success (undefined for absent/empty input →
9
- * no-op) or { error } with a caller-presentable message.
3
+ * Shared parsers for the Build*-action JSON payload fields (transaction service and wallet worker).
4
+ * Result contract: `{ parsed }` on success (undefined for absent/empty input) or `{ error }` with a client message.
10
5
  */
11
6
  export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson'): {
12
7
  parsed?: Array<{
@@ -15,19 +10,12 @@ export declare function parseUtxoRefArray(json: string | undefined, fieldName: '
15
10
  }>;
16
11
  error?: string;
17
12
  };
18
- /**
19
- * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
20
- * Same result contract as the other parse* helpers.
21
- */
13
+ /** Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes). */
22
14
  export declare function parseRequiredSigners(requiredSignersJson: string | undefined): {
23
15
  parsed?: string[];
24
16
  error?: string;
25
17
  };
26
- /**
27
- * Parse and validate an assetsJson array ({unit, quantity} entries) with the same
28
- * per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
29
- * into the builder and surfaced as 500s.
30
- */
18
+ /** Parse and validate an assetsJson array of `{unit, quantity}` entries. */
31
19
  export declare function parseAssetsArray(assetsJson: string | undefined, fieldName: string): {
32
20
  parsed?: Array<{
33
21
  unit: string;
@@ -47,12 +35,18 @@ export interface ParsedExtraOutput {
47
35
  inlineDatum?: JSONValue;
48
36
  referenceScript?: string;
49
37
  }
50
- /**
51
- * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
52
- * for empty array → no-op) or { error } on validation failure.
53
- */
38
+ /** Parse and validate extraOutputsJson (undefined for an empty array). */
54
39
  export declare function parseExtraOutputs(extraOutputsJson: string | undefined): {
55
40
  parsed?: ParsedExtraOutput[];
56
41
  error?: string;
57
42
  };
43
+ /**
44
+ * Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
45
+ * applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
46
+ */
47
+ export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number): {
48
+ script?: string;
49
+ redeemer?: JSONValue;
50
+ error?: string;
51
+ };
58
52
  //# sourceMappingURL=tx-request-parsers.d.ts.map
@@ -5,15 +5,11 @@ exports.parseUtxoRefArray = parseUtxoRefArray;
5
5
  exports.parseRequiredSigners = parseRequiredSigners;
6
6
  exports.parseAssetsArray = parseAssetsArray;
7
7
  exports.parseExtraOutputs = parseExtraOutputs;
8
+ exports.parseMintActionPolicyFields = parseMintActionPolicyFields;
8
9
  const validators_1 = require("./validators");
9
10
  /**
10
- * Shared parsers for the Build*-action JSON payload fields. Used by the
11
- * synchronous CardanoTransactionService handlers AND the wallet-worker's
12
- * request transformation (srv/blockchain/wallet-worker/build-request.ts) so
13
- * both paths accept exactly the same payload shape.
14
- *
15
- * Result contract: { parsed } on success (undefined for absent/empty input →
16
- * no-op) or { error } with a caller-presentable message.
11
+ * Shared parsers for the Build*-action JSON payload fields (transaction service and wallet worker).
12
+ * Result contract: `{ parsed }` on success (undefined for absent/empty input) or `{ error }` with a client message.
17
13
  */
18
14
  function parseUtxoRefArray(json, fieldName) {
19
15
  if (!json)
@@ -43,10 +39,7 @@ function parseUtxoRefArray(json, fieldName) {
43
39
  }
44
40
  return { parsed: refs };
45
41
  }
46
- /**
47
- * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
48
- * Same result contract as the other parse* helpers.
49
- */
42
+ /** Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes). */
50
43
  function parseRequiredSigners(requiredSignersJson) {
51
44
  if (!requiredSignersJson)
52
45
  return { parsed: undefined };
@@ -60,11 +53,7 @@ function parseRequiredSigners(requiredSignersJson) {
60
53
  return { error: err instanceof Error ? err.message : String(err) };
61
54
  }
62
55
  }
63
- /**
64
- * Parse and validate an assetsJson array ({unit, quantity} entries) with the same
65
- * per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
66
- * into the builder and surfaced as 500s.
67
- */
56
+ /** Parse and validate an assetsJson array of `{unit, quantity}` entries. */
68
57
  function parseAssetsArray(assetsJson, fieldName) {
69
58
  if (!assetsJson)
70
59
  return { parsed: undefined };
@@ -91,10 +80,7 @@ function parseAssetsArray(assetsJson, fieldName) {
91
80
  }
92
81
  /** Upper bound on extra outputs per transaction (defence against tx-size blow-up). */
93
82
  exports.MAX_EXTRA_OUTPUTS = 32;
94
- /**
95
- * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
96
- * for empty array → no-op) or { error } on validation failure.
97
- */
83
+ /** Parse and validate extraOutputsJson (undefined for an empty array). */
98
84
  function parseExtraOutputs(extraOutputsJson) {
99
85
  if (!extraOutputsJson)
100
86
  return { parsed: undefined };
@@ -167,4 +153,31 @@ function parseExtraOutputs(extraOutputsJson) {
167
153
  }
168
154
  return { parsed: out };
169
155
  }
156
+ /**
157
+ * Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
158
+ * applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
159
+ */
160
+ function parseMintActionPolicyFields(entry, i) {
161
+ let script;
162
+ if (entry.mintingPolicyScript !== undefined && entry.mintingPolicyScript !== null) {
163
+ if (typeof entry.mintingPolicyScript !== 'string' || !(0, validators_1.isValidCbor)(entry.mintingPolicyScript)) {
164
+ return { error: `mintActions[${i}].mintingPolicyScript must be even-length CBOR hex` };
165
+ }
166
+ script = entry.mintingPolicyScript;
167
+ }
168
+ let redeemer;
169
+ if (entry.redeemerJson !== undefined && entry.redeemerJson !== null) {
170
+ if (typeof entry.redeemerJson !== 'string') {
171
+ return { error: `mintActions[${i}].redeemerJson must be a JSON string` };
172
+ }
173
+ const jsonResult = (0, validators_1.validateJsonWithLimits)(entry.redeemerJson, `mintActions[${i}].redeemerJson`);
174
+ if (!jsonResult.valid)
175
+ return { error: jsonResult.error };
176
+ redeemer = jsonResult.parsed;
177
+ }
178
+ if (redeemer !== undefined && script === undefined) {
179
+ return { error: `mintActions[${i}].redeemerJson requires mintActions[${i}].mintingPolicyScript` };
180
+ }
181
+ return { script, redeemer };
182
+ }
170
183
  //# sourceMappingURL=tx-request-parsers.js.map
@@ -2,32 +2,13 @@ import cds from '@sap/cds';
2
2
  /** Default acquire budget for detached bookkeeping transactions. */
3
3
  export declare const DETACHED_TX_TIMEOUT_MS = 10000;
4
4
  /**
5
- * Run `fn` with `cds.context` cleared, so any `db.run(...)` inside it gets a
6
- * fresh short-lived transaction instead of joining a long-lived ambient one.
7
- * Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
8
- * connection free during long awaits (NIGHTGATE lesson 2; used by the
9
- * wallet-worker job loops).
5
+ * Run `fn` with `cds.context` cleared so inner `db.run` calls get short-lived transactions instead of
6
+ * joining a long-lived ambient one; keeps the single sqlite connection free during long awaits.
10
7
  */
11
8
  export declare function runWithoutAmbientTx<T>(fn: () => Promise<T>): Promise<T>;
12
9
  /**
13
- * `cds.tx(fn)` with a deadlock guard: a NEW ROOT transaction that fails fast
14
- * instead of hanging forever when no pooled connection becomes available.
15
- *
16
- * Why: the sign-service must commit its submit bookkeeping (claim, finalize,
17
- * failure marker) independently of the caller's request transaction. When an
18
- * in-process consumer awaits the action while its own request transaction
19
- * holds the single pooled sqlite connection, the acquire can never succeed —
20
- * without this guard that is a silent, zero-CPU, infinite hang.
21
- *
22
- * Guarantees:
23
- * - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
24
- * diagnosis pointing at KNOWN_ISSUES #11.
25
- * - A late connection grant (after the timeout already fired) performs NO
26
- * work: the callback forces the acquire via an explicit `begin()` and
27
- * checks the abort flag right after it, so it rolls back immediately and
28
- * the caller never observes an error for work that then silently happened
29
- * anyway. (A flag check at callback ENTRY would run long before the lazy
30
- * acquire and miss the timeout.)
10
+ * `cds.tx(fn)` as a new root transaction with a deadlock guard: throws BackendError 503
11
+ * `ODATANO_NESTED_TX_TIMEOUT` when no pooled connection arrives in time, and a late grant does no work.
31
12
  */
32
13
  export declare function detachedTx<T>(label: string, fn: (db: cds.Transaction) => Promise<T>, timeoutMs?: number): Promise<T>;
33
14
  //# sourceMappingURL=tx-utils.d.ts.map