@odatano/core 2.0.0-rc.3 → 2.0.0-rc.30

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 (162) 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 +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -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 +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -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 +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  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 +356 -217
  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 +548 -197
  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 +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1191 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -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 +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  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 +108 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +50 -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 +48 -24
  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 +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +127 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -11,19 +11,12 @@ const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
11
11
  const errors_1 = require("./errors");
12
12
  const logger = cds_1.default.log('SigningHelper');
13
13
  /**
14
- * Combine an unsigned transaction with a witness set from CIP-30 wallet signing
15
- *
16
- * CIP-30 signTx() returns only the witness set, not a complete signed transaction.
17
- * This function combines the original unsigned transaction with the witness set
18
- * to create a complete signed transaction that can be submitted to the network.
19
- *
20
- * @param unsignedTxCbor - The unsigned transaction CBOR (hex)
21
- * @param witnessSetCbor - The witness set CBOR from CIP-30 signTx() (hex)
22
- * @returns Complete signed transaction CBOR (hex)
14
+ * Combine an unsigned tx with the witness set a CIP-30 `signTx()` returns into a submittable signed tx.
15
+ * @returns complete signed transaction CBOR (hex)
23
16
  */
24
17
  function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
25
18
  try {
26
- // Parse at raw CBOR level — no Cardano type validation, preserves all encoding metadata
19
+ // Raw CBOR level: no Cardano type validation, preserves all encoding metadata
27
20
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
28
21
  if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
29
22
  throw new errors_1.TransactionValidationError('Invalid transaction CBOR structure');
@@ -33,19 +26,18 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
33
26
  const origWs = txObj.array[1];
34
27
  let witnessCount = 0;
35
28
  if (origWs instanceof cbor_1.CborMap && walletWsObj instanceof cbor_1.CborMap) {
36
- // Find wallet's VKey witnesses (map key 0)
29
+ // Wallet's VKey witnesses (map key 0)
37
30
  const walletVkeyEntry = walletWsObj.map.find(e => e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0);
38
31
  if (walletVkeyEntry) {
39
- // Merge: keep all original entries (redeemers, datums, scripts at keys 3-7),
40
- // remove any existing key 0, then add wallet's key 0 (VKey witnesses)
32
+ // Keep original entries (redeemers, datums, scripts at keys 3-7), replace key 0 with the wallet's
41
33
  const mergedEntries = origWs.map
42
34
  .filter(e => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0))
43
35
  .concat([walletVkeyEntry]);
44
- // Construct new witness set CborMap preserving the original's encoding style
36
+ // New witness set map preserving the original's encoding style
45
37
  txObj.array[1] = new cbor_1.CborMap(mergedEntries, {
46
38
  indefinite: origWs.indefinite,
47
39
  });
48
- // Count VKey witnesses — value may be CborArray or CborTag(258, CborArray) in Conway era
40
+ // VKey witnesses: CborArray, or CborTag(258, CborArray) in Conway
49
41
  const vkeyValue = walletVkeyEntry.v;
50
42
  if (vkeyValue instanceof cbor_1.CborArray) {
51
43
  witnessCount = vkeyValue.array.length;
@@ -61,11 +53,8 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
61
53
  else {
62
54
  throw new errors_1.TransactionValidationError('Witness set must be CBOR map per Cardano spec');
63
55
  }
64
- // Re-encode the tx as a NEW outer CborArray so the encoder cannot short-circuit
65
- // to the original full-tx bytes via the outer value's subCborRef (which no longer
66
- // matches now that the witness set changed). The INNER element subCborRefs are
67
- // deliberately kept: that byte-preserves the body (array[0]), so the tx body hash
68
- // the witnesses signed stays identical.
56
+ // New outer CborArray so the encoder cannot reuse the stale outer subCborRef; the inner
57
+ // subCborRefs are kept so the body bytes (and thus the signed body hash) stay identical.
69
58
  const signedTxCbor = (0, uint8array_utils_1.toHex)(cbor_1.Cbor.encode(new cbor_1.CborArray(txObj.array, { indefinite: txObj.indefinite })));
70
59
  logger.info({
71
60
  unsignedTxLength: unsignedTxCbor.length,
@@ -81,26 +70,15 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
81
70
  throw new errors_1.TransactionValidationError(`Failed to combine transaction with witnesses: ${msg}`);
82
71
  }
83
72
  }
84
- /**
85
- * Check if a CBOR string is a witness set (vs a full transaction)
86
- *
87
- * CIP-30 returns witness sets, not full transactions.
88
- * This helps detect when we need to call combineTransactionWithWitnesses.
89
- *
90
- * @param cborHex - CBOR hex string
91
- * @returns true if it's a witness set, false if it's a full transaction
92
- */
73
+ /** True when the CBOR is a CIP-30 witness set (map) rather than a full transaction (array). */
93
74
  function isWitnessSetCbor(cborHex) {
94
75
  try {
95
76
  const obj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(cborHex));
96
- // A full transaction is a CBOR array ([body, witness_set, is_valid, aux_data]);
97
- // a CIP-30 witness set is a CBOR map. The two shapes are unambiguous.
98
77
  if (obj instanceof cbor_1.CborArray)
99
78
  return false;
100
79
  return obj instanceof cbor_1.CborMap;
101
80
  }
102
81
  catch {
103
- // Invalid / unparseable CBOR
104
82
  return false;
105
83
  }
106
84
  }
@@ -1,24 +1,15 @@
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
+ /** A UTxO the builders may take as collateral: lovelace only and no reference script. */
7
+ export declare function isCollateralCandidate(u: OdatanoUtxo): boolean;
8
+ /** Throws MixedAssetsError when the UTxO carries non-ADA assets. */
15
9
  export declare function assertAdaOnly(u: OdatanoUtxo): void;
16
10
  /**
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
11
+ * Transaction hash of a signed or unsigned tx CBOR: blake2b-256 over the body bytes, so witnesses do not affect it.
12
+ * @returns 64-char hex string
22
13
  */
23
14
  export declare function getTxHashFromCbor(txCbor: string): string;
24
15
  /** Cache-invalidation targets of a submitted transaction (see extractTxCacheTargets). */
@@ -32,102 +23,45 @@ export interface TxCacheTargets {
32
23
  outputAddresses: string[];
33
24
  }
34
25
  /**
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
26
+ * Consumed input refs and output addresses of a tx CBOR: the UTxO-cache rows a submit makes stale.
27
+ * Outputs whose address bytes cannot be decoded (Byron) are skipped.
45
28
  */
46
29
  export declare function extractTxCacheTargets(txCbor: string): TxCacheTargets;
47
30
  /**
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
31
+ * Maps Buildooor errors to typed BackendErrors. Asset unit is parsed from "not enough <unit>" when not given;
32
+ * `context` (e.g. the collateral partition) is appended to the consumer-facing message.
59
33
  */
60
34
  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
- */
35
+ /** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
66
36
  export declare function parseAssetUnit(assetUnit: string): {
67
37
  policyId: string;
68
38
  assetName: string;
69
39
  };
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
- */
40
+ /** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
81
41
  export declare function jsonToPlutusData(json: JSONValue): Data;
82
42
  /**
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.
43
+ * Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
44
+ * or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
93
45
  */
94
46
  export declare function inlineDatumToHex(datum: unknown): string | null;
95
47
  /** UPLC type tag for a typed script parameter (see {@link encodeScriptParam}). */
96
48
  export type ScriptParamUplcType = 'data' | 'bytes' | 'int' | 'bool' | 'unit';
97
49
  /**
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.
50
+ * Encode a script parameter as the UPLC constant of the type the validator expects: typed
51
+ * `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
52
+ * (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
118
53
  */
119
54
  export declare function encodeScriptParam(param: JSONValue): UPLCConst;
120
55
  /**
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)
56
+ * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
57
+ * UPLC Application around the program body, encoded via {@link encodeScriptParam}.
58
+ * @returns CBOR hex of the applied script
131
59
  */
132
60
  export declare function applyScriptParameters(scriptHex: string, params: JSONValue[]): string;
61
+ /**
62
+ * Script hash of a Plutus script, CBOR-wrapped once or twice as cardano-cli writes it:
63
+ * blake2b-224 over the language byte and the once-wrapped CBOR. The version cannot be read
64
+ * from the script, so the caller names it.
65
+ */
66
+ export declare function plutusScriptHash(scriptHex: string, version: 'plutusV2' | 'plutusV3'): string;
133
67
  //# sourceMappingURL=tx-build-helper.d.ts.map
@@ -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,31 @@ 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.
147
118
  */
148
119
  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
+ // Typed errors keep their own status and payload
152
121
  if (err instanceof errors_1.BackendError) {
153
122
  throw err;
154
123
  }
155
124
  const errObj = err;
156
125
  const rawMsg = errObj?.message || errObj?.toString?.() || String(err);
157
126
  const msg = rawMsg.toLowerCase();
127
+ // An output below the protocol's min-ADA: a request error, not missing funds
128
+ 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+)/);
129
+ if (minAda) {
130
+ const [, index, minimum, actual] = minAda;
131
+ const withAssets = /tx output:[\s\S]*"[0-9a-f]{56}"\s*:/i.test(rawMsg) ? ', it carries native assets' : '';
132
+ throw new errors_1.TransactionValidationError(`output ${index} needs at least ${minimum} lovelace (has ${actual}${withAssets}); raise its lovelace amount`, err);
133
+ }
158
134
  if (msg.includes('not enough') ||
159
135
  msg.includes('insufficient') ||
160
136
  msg.includes('balance')) {
@@ -162,24 +138,19 @@ function mapBuilderError(err, assetUnit, context) {
162
138
  const match = msg.match(/not enough\s+([a-f0-9.]+)/i);
163
139
  return match?.[1] || 'lovelace';
164
140
  })();
165
- // The builder knows no amounts here — surface its own message (plus the build
166
- // context) instead of a meaningless "required 0, available 0".
141
+ // No amounts known here: surface the builder's own message instead of "required 0, available 0"
167
142
  throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err, context ? `${rawMsg} (${context})` : rawMsg);
168
143
  }
169
144
  throw err;
170
145
  }
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
- */
146
+ /** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
176
147
  function parseAssetUnit(assetUnit) {
177
148
  return {
178
149
  policyId: assetUnit.substring(0, 56),
179
150
  assetName: assetUnit.substring(56)
180
151
  };
181
152
  }
182
- /** Allowed keys in PlutusData JSON — strip anything else for defense-in-depth */
153
+ /** Allowed keys in PlutusData JSON; anything else is stripped */
183
154
  const PLUTUS_DATA_ALLOWED_KEYS = new Set([
184
155
  'constructor', 'constr', 'fields', 'int', 'bytes', 'list', 'map', 'k', 'v'
185
156
  ]);
@@ -193,11 +164,7 @@ function sanitizePlutusKeys(obj) {
193
164
  }
194
165
  return clean;
195
166
  }
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
- */
167
+ /** Normalize cardano-cli "constructor" to Buildooor "constr" recursively; strips unknown keys. */
201
168
  function normalizeConstructorKey(obj) {
202
169
  const safe = sanitizePlutusKeys(obj);
203
170
  const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -222,17 +189,7 @@ function normalizeConstructorKey(obj) {
222
189
  }
223
190
  return safe;
224
191
  }
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
- */
192
+ /** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
236
193
  function jsonToPlutusData(json) {
237
194
  if (json === null || json === undefined) {
238
195
  throw new Error('PlutusData JSON cannot be null or undefined');
@@ -244,21 +201,13 @@ function jsonToPlutusData(json) {
244
201
  throw new Error(`Unsupported PlutusData JSON format: expected an object with "int", "bytes", "list", "map", or "constructor" key`);
245
202
  }
246
203
  /**
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.
204
+ * Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
205
+ * or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
257
206
  */
258
207
  function inlineDatumToHex(datum) {
259
208
  if (datum === null || datum === undefined)
260
209
  return null;
261
- // Already hex CBOR (Blockfrost path, or pre-normalized)
210
+ // Already hex CBOR
262
211
  if (typeof datum === 'string') {
263
212
  const s = datum.trim();
264
213
  if (!s)
@@ -268,8 +217,7 @@ function inlineDatumToHex(datum) {
268
217
  if (typeof datum !== 'object' || Array.isArray(datum))
269
218
  return null;
270
219
  const obj = datum;
271
- // Koios wrapper: { bytes: "<hex>", value: <PlutusData JSON> }.
272
- // Distinguished from raw PlutusData {bytes:"deadbeef"} by the presence of `value`.
220
+ // Koios wrapper { bytes, value }; `value` distinguishes it from raw PlutusData { bytes }
273
221
  if ('value' in obj && typeof obj.bytes === 'string' && obj.bytes.length > 0) {
274
222
  const hex = obj.bytes.trim();
275
223
  return /^[0-9a-fA-F]+$/.test(hex) && hex.length % 2 === 0 ? hex.toLowerCase() : null;
@@ -290,26 +238,9 @@ function inlineDatumToHex(datum) {
290
238
  }
291
239
  }
292
240
  /**
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.
241
+ * Encode a script parameter as the UPLC constant of the type the validator expects: typed
242
+ * `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
243
+ * (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
313
244
  */
314
245
  function encodeScriptParam(param) {
315
246
  if (param !== null &&
@@ -351,39 +282,53 @@ function encodeScriptParam(param) {
351
282
  throw new Error(`Unknown script param uplc type "${String(uplc)}"; expected one of: data, bytes, int, bool, unit`);
352
283
  }
353
284
  }
354
- // Bare PlutusData → apply as Data (Aiken / blueprint convention)
285
+ // Bare PlutusData: apply as Data
355
286
  return uplc_1.UPLCConst.data(jsonToPlutusData(param));
356
287
  }
357
288
  /**
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)
289
+ * Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
290
+ * UPLC Application around the program body, encoded via {@link encodeScriptParam}.
291
+ * @returns CBOR hex of the applied script
368
292
  */
369
293
  function applyScriptParameters(scriptHex, params) {
370
294
  if (!Array.isArray(params) || params.length === 0) {
371
295
  throw new Error('Script parameters must be a non-empty array');
372
296
  }
373
- // 1. CBOR-decode script hex → get inner flat UPLC bytes
297
+ // CBOR-unwrap to the flat UPLC bytes
374
298
  const cborObj = cbor_1.Cbor.parse(scriptHex);
375
299
  const flatBytes = cborObj.bytes;
376
- // 2. Flat-decode → UPLCProgram
377
300
  const program = uplc_1.UPLCDecoder.parse(flatBytes, 'flat');
378
- // 3. Apply each parameter as Application(body, <typed UPLC constant>)
379
301
  let body = program.body;
380
302
  for (const param of params) {
381
303
  body = new uplc_1.Application(body, encodeScriptParam(param));
382
304
  }
383
- // 4. Create new program with applied body, flat-encode, CBOR-wrap
305
+ // Flat-encode the applied program and CBOR-wrap it again
384
306
  const applied = new uplc_1.UPLCProgram(program.version, body);
385
307
  const appliedFlatBytes = (0, uplc_1.compileUPLC)(applied);
386
308
  const cborEncoded = cbor_1.Cbor.encode(new cbor_1.CborBytes(appliedFlatBytes));
387
309
  return (0, uint8array_utils_1.toHex)(cborEncoded);
388
310
  }
311
+ /**
312
+ * Script hash of a Plutus script, CBOR-wrapped once or twice as cardano-cli writes it:
313
+ * blake2b-224 over the language byte and the once-wrapped CBOR. The version cannot be read
314
+ * from the script, so the caller names it.
315
+ */
316
+ function plutusScriptHash(scriptHex, version) {
317
+ if (version !== 'plutusV2' && version !== 'plutusV3') {
318
+ throw new errors_1.TransactionValidationError(`version must be plutusV2 or plutusV3, got ${String(version)}`);
319
+ }
320
+ let script;
321
+ try {
322
+ 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));
323
+ }
324
+ catch (err) {
325
+ throw new errors_1.TransactionValidationError(`scriptHex is not a CBOR-wrapped Plutus script: ${err instanceof Error ? err.message : String(err)}`);
326
+ }
327
+ // Plutus V2 runs UPLC 1.0.0 only; the first three flat bytes hold the UPLC version
328
+ const b = script.bytes;
329
+ if (version === 'plutusV2' && !(b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0)) {
330
+ throw new errors_1.TransactionValidationError('scriptHex is not UPLC 1.0.0 code, so it cannot be a Plutus V2 script');
331
+ }
332
+ return script.hash.toString();
333
+ }
389
334
  //# sourceMappingURL=tx-build-helper.js.map