@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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