@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) 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/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getLovelace = getLovelace;
4
+ exports.isCollateralCandidate = isCollateralCandidate;
4
5
  exports.assertAdaOnly = assertAdaOnly;
5
6
  exports.getTxHashFromCbor = getTxHashFromCbor;
6
7
  exports.extractTxCacheTargets = extractTxCacheTargets;
@@ -10,6 +11,7 @@ exports.jsonToPlutusData = jsonToPlutusData;
10
11
  exports.inlineDatumToHex = inlineDatumToHex;
11
12
  exports.encodeScriptParam = encodeScriptParam;
12
13
  exports.applyScriptParameters = applyScriptParameters;
14
+ exports.plutusScriptHash = plutusScriptHash;
13
15
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
14
16
  const crypto_1 = require("@harmoniclabs/crypto");
15
17
  const errors_1 = require("./errors");
@@ -18,20 +20,16 @@ const plutus_data_1 = require("@harmoniclabs/plutus-data");
18
20
  const uplc_1 = require("@harmoniclabs/uplc");
19
21
  const cbor_1 = require("@harmoniclabs/cbor");
20
22
  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
- */
23
+ /** Lovelace amount of a UTxO. */
26
24
  function getLovelace(u) {
27
25
  const entry = u.amount.find(a => (a.unit).toLowerCase() === "lovelace");
28
26
  return BigInt(entry?.quantity ?? "0");
29
27
  }
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
- */
28
+ /** A UTxO the builders may take as collateral: lovelace only and no reference script. */
29
+ function isCollateralCandidate(u) {
30
+ return u.amount.every(a => a.unit.toLowerCase() === 'lovelace' || BigInt(a.quantity) === 0n) && !u.scriptRef && !u.scriptRefCbor;
31
+ }
32
+ /** Throws MixedAssetsError when the UTxO carries non-ADA assets. */
35
33
  function assertAdaOnly(u) {
36
34
  const nonAda = u.amount.filter(a => (a.unit).toLowerCase() !== "lovelace" && BigInt(a.quantity) !== 0n);
37
35
  if (nonAda.length > 0) {
@@ -39,27 +37,18 @@ function assertAdaOnly(u) {
39
37
  }
40
38
  }
41
39
  /**
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
40
+ * Transaction hash of a signed or unsigned tx CBOR: blake2b-256 over the body bytes, so witnesses do not affect it.
41
+ * @returns 64-char hex string
47
42
  */
48
43
  function getTxHashFromCbor(txCbor) {
49
44
  if (!txCbor || typeof txCbor !== 'string') {
50
45
  throw new Error('Invalid input: txCbor must be a non-empty string');
51
46
  }
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.
47
+ // Even length: an odd hex string would otherwise fail later as a confusing parse error
56
48
  if (!/^[a-fA-F0-9]+$/.test(txCbor) || txCbor.length % 2 !== 0) {
57
49
  throw new Error('Invalid input: txCbor must be a valid hex string');
58
50
  }
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.
51
+ // Hash the ORIGINAL body bytes via subCborRef (no re-serialization), so it matches what was signed
63
52
  try {
64
53
  const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
65
54
  if (!(tx instanceof cbor_1.CborArray) || tx.array.length < 1 || !tx.array[0].subCborRef) {
@@ -69,21 +58,12 @@ function getTxHashFromCbor(txCbor) {
69
58
  return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(bodyBytes));
70
59
  }
71
60
  catch (err) {
72
- // typed 400 — a plain Error here surfaced as a 500 to the consumer
73
61
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
74
62
  }
75
63
  }
76
64
  /**
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
65
+ * Consumed input refs and output addresses of a tx CBOR: the UTxO-cache rows a submit makes stale.
66
+ * Outputs whose address bytes cannot be decoded (Byron) are skipped.
87
67
  */
88
68
  function extractTxCacheTargets(txCbor) {
89
69
  let body;
@@ -98,7 +78,7 @@ function extractTxCacheTargets(txCbor) {
98
78
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
99
79
  }
100
80
  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)
81
+ // key 0: inputs, plain array or CBOR tag-258 set (Conway)
102
82
  const inputs = [];
103
83
  let inputsObj = bodyValue(0);
104
84
  if (inputsObj instanceof cbor_1.CborTag)
@@ -112,7 +92,7 @@ function extractTxCacheTargets(txCbor) {
112
92
  }
113
93
  }
114
94
  }
115
- // key 1: outputs — post-alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
95
+ // key 1: outputs, post-Alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
116
96
  const outputAddresses = new Set();
117
97
  const outputsObj = bodyValue(1);
118
98
  if (outputsObj instanceof cbor_1.CborArray) {
@@ -126,35 +106,37 @@ function extractTxCacheTargets(txCbor) {
126
106
  outputAddresses.add(cardano_ledger_ts_1.Address.fromBuffer(addrObj.bytes).toString());
127
107
  }
128
108
  catch {
129
- // non-Shelley address bytes — nothing cached under a bech32 key for it
109
+ // non-Shelley address bytes: nothing cached under a bech32 key
130
110
  }
131
111
  }
132
112
  }
133
113
  return { inputs, outputAddresses: [...outputAddresses] };
134
114
  }
135
115
  /**
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
116
+ * Maps Buildooor errors to typed BackendErrors. Asset unit is parsed from "not enough <unit>" when not given;
117
+ * `context` (e.g. the collateral partition) is appended to the consumer-facing message.
118
+ * `requestedOutputs` is the number of outputs the caller asked for; Buildooor appends the change after them.
147
119
  */
148
- 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.
120
+ function mapBuilderError(err, assetUnit, context, requestedOutputs) {
121
+ // Typed errors keep their own status and payload
152
122
  if (err instanceof errors_1.BackendError) {
153
123
  throw err;
154
124
  }
155
125
  const errObj = err;
156
126
  const rawMsg = errObj?.message || errObj?.toString?.() || String(err);
157
127
  const msg = rawMsg.toLowerCase();
128
+ // An output below the protocol's min-ADA: a request error, not missing funds
129
+ const minAda = rawMsg.match(/tx output at index (\d+) did not have enough lovelaces[\s\S]*?minimum lovelaces required:\s*(\d+)[\s\S]*?output lovelaces\s*:\s*(\d+)/);
130
+ if (minAda) {
131
+ const [, index, minimum, actual] = minAda;
132
+ if (requestedOutputs !== undefined && Number(index) >= requestedOutputs) {
133
+ // the change output: the caller cannot raise it. The shortfall is unknown here, so no amounts
134
+ throw new errors_1.InsufficientFundsError('lovelace', 0n, 0n, err, `the change output needs at least ${minimum} lovelace (has ${actual}); the funding UTxOs cannot pay the fee and the change` +
135
+ (context ? ` (${context})` : ''));
136
+ }
137
+ const withAssets = /tx output:[\s\S]*"[0-9a-f]{56}"\s*:/i.test(rawMsg) ? ', it carries native assets' : '';
138
+ throw new errors_1.TransactionValidationError(`output ${index} needs at least ${minimum} lovelace (has ${actual}${withAssets}); raise its lovelace amount`, err);
139
+ }
158
140
  if (msg.includes('not enough') ||
159
141
  msg.includes('insufficient') ||
160
142
  msg.includes('balance')) {
@@ -162,24 +144,19 @@ function mapBuilderError(err, assetUnit, context) {
162
144
  const match = msg.match(/not enough\s+([a-f0-9.]+)/i);
163
145
  return match?.[1] || 'lovelace';
164
146
  })();
165
- // The builder knows no amounts here — surface its own message (plus the build
166
- // context) instead of a meaningless "required 0, available 0".
147
+ // No amounts known here: surface the builder's own message instead of "required 0, available 0"
167
148
  throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err, context ? `${rawMsg} (${context})` : rawMsg);
168
149
  }
169
150
  throw err;
170
151
  }
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
- */
152
+ /** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
176
153
  function parseAssetUnit(assetUnit) {
177
154
  return {
178
155
  policyId: assetUnit.substring(0, 56),
179
156
  assetName: assetUnit.substring(56)
180
157
  };
181
158
  }
182
- /** Allowed keys in PlutusData JSON — strip anything else for defense-in-depth */
159
+ /** Allowed keys in PlutusData JSON; anything else is stripped */
183
160
  const PLUTUS_DATA_ALLOWED_KEYS = new Set([
184
161
  'constructor', 'constr', 'fields', 'int', 'bytes', 'list', 'map', 'k', 'v'
185
162
  ]);
@@ -193,11 +170,7 @@ function sanitizePlutusKeys(obj) {
193
170
  }
194
171
  return clean;
195
172
  }
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
- */
173
+ /** Normalize cardano-cli "constructor" to Buildooor "constr" recursively; strips unknown keys. */
201
174
  function normalizeConstructorKey(obj) {
202
175
  const safe = sanitizePlutusKeys(obj);
203
176
  const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -222,17 +195,7 @@ function normalizeConstructorKey(obj) {
222
195
  }
223
196
  return safe;
224
197
  }
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
- */
198
+ /** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
236
199
  function jsonToPlutusData(json) {
237
200
  if (json === null || json === undefined) {
238
201
  throw new Error('PlutusData JSON cannot be null or undefined');
@@ -244,21 +207,13 @@ function jsonToPlutusData(json) {
244
207
  throw new Error(`Unsupported PlutusData JSON format: expected an object with "int", "bytes", "list", "map", or "constructor" key`);
245
208
  }
246
209
  /**
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.
210
+ * Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
211
+ * or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
257
212
  */
258
213
  function inlineDatumToHex(datum) {
259
214
  if (datum === null || datum === undefined)
260
215
  return null;
261
- // Already hex CBOR (Blockfrost path, or pre-normalized)
216
+ // Already hex CBOR
262
217
  if (typeof datum === 'string') {
263
218
  const s = datum.trim();
264
219
  if (!s)
@@ -268,8 +223,7 @@ function inlineDatumToHex(datum) {
268
223
  if (typeof datum !== 'object' || Array.isArray(datum))
269
224
  return null;
270
225
  const obj = datum;
271
- // Koios wrapper: { bytes: "<hex>", value: <PlutusData JSON> }.
272
- // Distinguished from raw PlutusData {bytes:"deadbeef"} by the presence of `value`.
226
+ // Koios wrapper { bytes, value }; `value` distinguishes it from raw PlutusData { bytes }
273
227
  if ('value' in obj && typeof obj.bytes === 'string' && obj.bytes.length > 0) {
274
228
  const hex = obj.bytes.trim();
275
229
  return /^[0-9a-fA-F]+$/.test(hex) && hex.length % 2 === 0 ? hex.toLowerCase() : null;
@@ -290,26 +244,9 @@ function inlineDatumToHex(datum) {
290
244
  }
291
245
  }
292
246
  /**
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.
247
+ * Encode a script parameter as the UPLC constant of the type the validator expects: typed
248
+ * `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
249
+ * (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
313
250
  */
314
251
  function encodeScriptParam(param) {
315
252
  if (param !== null &&
@@ -351,39 +288,53 @@ function encodeScriptParam(param) {
351
288
  throw new Error(`Unknown script param uplc type "${String(uplc)}"; expected one of: data, bytes, int, bool, unit`);
352
289
  }
353
290
  }
354
- // Bare PlutusData → apply as Data (Aiken / blueprint convention)
291
+ // Bare PlutusData: apply as Data
355
292
  return uplc_1.UPLCConst.data(jsonToPlutusData(param));
356
293
  }
357
294
  /**
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)
295
+ * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
296
+ * UPLC Application around the program body, encoded via {@link encodeScriptParam}.
297
+ * @returns CBOR hex of the applied script
368
298
  */
369
299
  function applyScriptParameters(scriptHex, params) {
370
300
  if (!Array.isArray(params) || params.length === 0) {
371
301
  throw new Error('Script parameters must be a non-empty array');
372
302
  }
373
- // 1. CBOR-decode script hex → get inner flat UPLC bytes
303
+ // CBOR-unwrap to the flat UPLC bytes
374
304
  const cborObj = cbor_1.Cbor.parse(scriptHex);
375
305
  const flatBytes = cborObj.bytes;
376
- // 2. Flat-decode → UPLCProgram
377
306
  const program = uplc_1.UPLCDecoder.parse(flatBytes, 'flat');
378
- // 3. Apply each parameter as Application(body, <typed UPLC constant>)
379
307
  let body = program.body;
380
308
  for (const param of params) {
381
309
  body = new uplc_1.Application(body, encodeScriptParam(param));
382
310
  }
383
- // 4. Create new program with applied body, flat-encode, CBOR-wrap
311
+ // Flat-encode the applied program and CBOR-wrap it again
384
312
  const applied = new uplc_1.UPLCProgram(program.version, body);
385
313
  const appliedFlatBytes = (0, uplc_1.compileUPLC)(applied);
386
314
  const cborEncoded = cbor_1.Cbor.encode(new cbor_1.CborBytes(appliedFlatBytes));
387
315
  return (0, uint8array_utils_1.toHex)(cborEncoded);
388
316
  }
317
+ /**
318
+ * Script hash of a Plutus script, CBOR-wrapped once or twice as cardano-cli writes it:
319
+ * blake2b-224 over the language byte and the once-wrapped CBOR. The version cannot be read
320
+ * from the script, so the caller names it.
321
+ */
322
+ function plutusScriptHash(scriptHex, version) {
323
+ if (version !== 'plutusV2' && version !== 'plutusV3') {
324
+ throw new errors_1.TransactionValidationError(`version must be plutusV2 or plutusV3, got ${String(version)}`);
325
+ }
326
+ let script;
327
+ try {
328
+ script = new cardano_ledger_ts_1.Script(version === 'plutusV2' ? cardano_ledger_ts_1.ScriptType.PlutusV2 : cardano_ledger_ts_1.ScriptType.PlutusV3, (0, uint8array_utils_1.fromHex)(scriptHex));
329
+ }
330
+ catch (err) {
331
+ throw new errors_1.TransactionValidationError(`scriptHex is not a CBOR-wrapped Plutus script: ${err instanceof Error ? err.message : String(err)}`);
332
+ }
333
+ // Plutus V2 runs UPLC 1.0.0 only; the first three flat bytes hold the UPLC version
334
+ const b = script.bytes;
335
+ if (version === 'plutusV2' && !(b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0)) {
336
+ throw new errors_1.TransactionValidationError('scriptHex is not UPLC 1.0.0 code, so it cannot be a Plutus V2 script');
337
+ }
338
+ return script.hash.toString();
339
+ }
389
340
  //# sourceMappingURL=tx-build-helper.js.map
@@ -1,33 +1,26 @@
1
- import type { JSONValue } from './types';
1
+ import type { JSONValue, MintAction } 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
- export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson'): {
6
+ /** PlutusData as CBOR hex, checked to decode; `field` names it in the error. */
7
+ export declare function parsePlutusCbor(value: unknown, field: string): {
8
+ hex?: string;
9
+ error?: string;
10
+ };
11
+ export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson' | 'protectInputsJson'): {
12
12
  parsed?: Array<{
13
13
  txHash: string;
14
14
  outputIndex: number;
15
15
  }>;
16
16
  error?: string;
17
17
  };
18
- /**
19
- * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
20
- * Same result contract as the other parse* helpers.
21
- */
18
+ /** Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes). */
22
19
  export declare function parseRequiredSigners(requiredSignersJson: string | undefined): {
23
20
  parsed?: string[];
24
21
  error?: string;
25
22
  };
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
- */
23
+ /** Parse and validate an assetsJson array of `{unit, quantity}` entries. */
31
24
  export declare function parseAssetsArray(assetsJson: string | undefined, fieldName: string): {
32
25
  parsed?: Array<{
33
26
  unit: string;
@@ -45,27 +38,107 @@ export interface ParsedExtraOutput {
45
38
  quantity: string;
46
39
  }>;
47
40
  inlineDatum?: JSONValue;
41
+ /** Hash of a datum the output is locked with (hex, 32 bytes); `outputsJson` only. */
42
+ datumHash?: string;
43
+ /** Inline datum as PlutusData CBOR hex, taken byte for byte; `outputsJson` only. */
44
+ inlineDatumCbor?: string;
48
45
  referenceScript?: string;
49
46
  }
47
+ /** Parse and validate extraOutputsJson (undefined for an empty array). */
48
+ export declare function parseExtraOutputs(extraOutputsJson: string | undefined): {
49
+ parsed?: ParsedExtraOutput[];
50
+ error?: string;
51
+ };
50
52
  /**
51
- * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
52
- * for empty array → no-op) or { error } on validation failure.
53
+ * Parse an output list. `outputsJson` (BuildPlutusTransaction) additionally accepts `datumHash`;
54
+ * the entries keep their order, each is min-ADA checked by the builder.
53
55
  */
54
- export declare function parseExtraOutputs(extraOutputsJson: string | undefined): {
56
+ export declare function parseOutputList(json: string | undefined, fieldName: 'extraOutputsJson' | 'outputsJson'): {
55
57
  parsed?: ParsedExtraOutput[];
56
58
  error?: string;
57
59
  };
58
60
  /**
59
- * Parse the optional PER-ACTION policy fields of a mintActionsJson entry
60
- * (multi-policy mint FR): `mintingPolicyScript` (CBOR hex, applied as-is; a
61
- * parameterized per-action script must be pre-applied by the caller) and
62
- * `redeemerJson` (a JSON-encoded string, same convention as extraOutputs'
63
- * inlineDatumJson). Absent fields fall back to the action's top-level
64
- * script/redeemer at build time.
61
+ * Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
62
+ * applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
65
63
  */
66
- export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number): {
64
+ export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number, byReference?: boolean): {
67
65
  script?: string;
68
66
  redeemer?: JSONValue;
69
67
  error?: string;
70
68
  };
69
+ /** Upper bound on script inputs per BuildPlutusTransaction. */
70
+ export declare const MAX_SCRIPT_INPUTS = 16;
71
+ /** One script UTxO of a BuildPlutusTransaction, validated; `validatorScript` still without params applied. */
72
+ export interface ParsedScriptInput {
73
+ txHash: string;
74
+ outputIndex: number;
75
+ validatorScript?: string;
76
+ scriptParams?: JSONValue[];
77
+ referenceScript?: {
78
+ txHash: string;
79
+ outputIndex: number;
80
+ };
81
+ redeemer: JSONValue;
82
+ /** Redeemer as PlutusData CBOR hex (instead of redeemerJson), taken byte for byte. */
83
+ redeemerCbor?: string;
84
+ datum?: JSONValue;
85
+ /** Datum preimage as PlutusData CBOR hex (instead of datumJson). */
86
+ datumCbor?: string;
87
+ }
88
+ /** Parse and validate scriptInputsJson: 0..MAX_SCRIPT_INPUTS distinct script UTxOs, each with its own redeemer. */
89
+ export declare function parseScriptInputs(json: string | undefined): {
90
+ parsed?: ParsedScriptInput[];
91
+ error?: string;
92
+ };
93
+ /** Upper bound on withdrawals per BuildPlutusTransaction. */
94
+ export declare const MAX_WITHDRAWALS = 16;
95
+ /** One withdrawal of a BuildPlutusTransaction, validated; `stakingScript` still without params applied. */
96
+ export interface ParsedWithdrawal {
97
+ rewardAddress: string;
98
+ lovelace: string;
99
+ stakingScript?: string;
100
+ scriptParams?: JSONValue[];
101
+ referenceScript?: {
102
+ txHash: string;
103
+ outputIndex: number;
104
+ };
105
+ redeemer?: JSONValue;
106
+ redeemerCbor?: string;
107
+ }
108
+ /**
109
+ * Parse and validate withdrawalsJson: distinct reward accounts, lovelace >= 0, optionally a staking
110
+ * script (inline or by reference) with exactly one redeemer form; without a script no redeemer.
111
+ */
112
+ export declare function parseWithdrawals(json: string | undefined): {
113
+ parsed?: ParsedWithdrawal[];
114
+ error?: string;
115
+ };
116
+ /** Optional staking script (inline with params, or by reference) plus its redeemer, shared by withdrawals and certificates. */
117
+ type ParsedStakingScriptWitness = Pick<ParsedWithdrawal, 'stakingScript' | 'scriptParams' | 'referenceScript' | 'redeemer' | 'redeemerCbor'>;
118
+ /** Upper bound on certificates per BuildPlutusTransaction. */
119
+ export declare const MAX_CERTIFICATES = 16;
120
+ /** One certificate of a BuildPlutusTransaction, validated; `stakingScript` still without params applied. */
121
+ export interface ParsedCertificate extends ParsedStakingScriptWitness {
122
+ type: 'registerStake' | 'deregisterStake';
123
+ stakeAddress: string;
124
+ deposit?: string;
125
+ }
126
+ /**
127
+ * Parse and validate certificatesJson: stake registrations and deregistrations, each with an
128
+ * optional staking script (inline or by reference) and exactly one redeemer form when scripted.
129
+ */
130
+ export declare function parseCertificates(json: string | undefined): {
131
+ parsed?: ParsedCertificate[];
132
+ error?: string;
133
+ };
134
+ /**
135
+ * Parse mintActionsJson for BuildPlutusTransaction: every action carries its own `mintingPolicyScript`
136
+ * or `referenceScript` (no request-level default) and optional `redeemerJson`; `assetUnit` is
137
+ * policyId+assetName, or with an inline script a bare assetName prefixed with the script's policy id.
138
+ */
139
+ export declare function parsePolicyMintActions(json: string | undefined): {
140
+ parsed?: MintAction[];
141
+ error?: string;
142
+ };
143
+ export {};
71
144
  //# sourceMappingURL=tx-request-parsers.d.ts.map