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

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 (239) 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 +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -1,113 +1,49 @@
1
1
  import type { CardanoClient } from './cardano-client';
2
- import type { TxBuildRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
2
+ import type { UTxO } from '../utils/types';
3
+ import type { TxBuildRequest, TxBuildPlutusRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
3
4
  import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
4
5
  import { LedgerProtocolParameter } from '#cds-models/CardanoODataService';
5
- /**
6
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
7
- * to build various types of Cardano transactions.
8
- */
6
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
9
7
  export declare class CardanoTransactionBuilder {
10
8
  private client;
11
9
  private txBuilder;
12
10
  private initialized;
13
- /**
14
- * Create a new CardanoTransactionBuilder instance
15
- * @param client - The CardanoClient instance for UTxO fetching
16
- */
11
+ /** @param client UTxO source for coin selection */
17
12
  constructor(client: CardanoClient);
18
- /**
19
- * Initialize the transaction builder
20
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
21
- */
13
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
14
+ private addressUtxoSource;
15
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
16
+ setAddressUtxoSource(source: (address: string) => Promise<UTxO[] | null>): void;
17
+ /** @param protocolParams optional; fetched from the backend when omitted */
22
18
  init(protocolParams?: LedgerProtocolParameters): Promise<void>;
23
- /**
24
- * Ensure the builder is initialized and return it (lazy init)
25
- * @returns {Promise<CardanoTxBuilder>} initialized builder
26
- * @throws {Error} if builder cannot be initialized
27
- */
19
+ /** Lazily initialize and return the builder. */
28
20
  private ensureInitialized;
29
- /**
30
- * Reset the transaction builder (useful for testing)
31
- */
21
+ /** Reset the builder (testing). */
32
22
  reset(): void;
33
- /**
34
- * Set the transaction builder directly (for testing)
35
- * @param builder - The builder to set
36
- */
23
+ /** Set the builder directly (testing). */
37
24
  setBuilder(builder: CardanoTxBuilder): void;
38
- /**
39
- * Build a simple ADA transfer transaction
40
- * @param req transaction build request
41
- * @param protocolParameters current protocol parameters
42
- * @returns {Promise<TxBuildResult>} transaction build result
43
- */
25
+ /** Build a simple ADA transfer transaction. */
44
26
  buildSimpleAdaTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
45
- /**
46
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
47
- * @param req transaction build request
48
- * @param protocolParameters current protocol parameters
49
- * @returns {Promise<TxBuildResult>} transaction build result
50
- */
27
+ /** Build a transaction with metadata (simple or multi-asset). */
51
28
  buildTransactionWithMetadata(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
52
- /**
53
- * Build a multi-asset transaction
54
- * @param req transaction build request
55
- * @param protocolParameters current protocol parameters
56
- * @returns {Promise<TxBuildResult>} transaction build result
57
- */
29
+ /** Build a multi-asset transaction. */
58
30
  buildMultiAssetTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
59
- /**
60
- * Build a minting transaction
61
- * @param req transaction build request
62
- * @param protocolParameters current protocol parameters
63
- * @returns {Promise<TxBuildResult>} transaction build result
64
- */
31
+ /** Build a minting transaction. */
65
32
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
66
- /**
67
- * Build a Plutus spending transaction (consume UTxO at script address)
68
- * @param req transaction build request
69
- * @param protocolParameters current protocol parameters
70
- * @returns {Promise<TxBuildResult>} transaction build result
71
- */
33
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
72
34
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
73
- /**
74
- * Verify that a transaction output resolved via getTransaction is still unspent,
75
- * by checking the live UTxO set of its address. getTransaction only proves the
76
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
77
- * rejection at submit instead of a clear 400 here.
78
- *
79
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
80
- * build on a flaky backend would be a new failure mode).
81
- */
35
+ /** Several script inputs in one transaction. */
36
+ buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
37
+ private _assertRewardAccountsRegistered;
38
+ private _resolveScriptUtxo;
39
+ private _lookupUnspent;
82
40
  private _assertUnspent;
83
- /**
84
- * Resolve forced-input refs (consumed) to full UTxO records.
85
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
86
- */
41
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
87
42
  private _resolveForceInputs;
88
- /**
89
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
90
- * coin-selection set) to full UTxO records.
91
- */
43
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
92
44
  private _resolveReferenceInputs;
93
- /**
94
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
95
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
96
- * otherwise fetches the producing transaction and verifies the output is
97
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
98
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
99
- *
100
- * @param refs input refs from the request
101
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
102
- * @param kind label used in error messages / the spent-check
103
- * @returns resolved UTxOs, in the same order as the deduped refs
104
- */
105
45
  private _resolveInputRefs;
106
- /**
107
- * Fetch UTxOs for a given address
108
- * @param address bech32 address
109
- * @returns {Promise<UTxO[]>} list of UTxOs
110
- */
46
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
111
47
  private _fetchUtxosForAddress;
112
48
  }
113
49
  //# sourceMappingURL=cardano-tx-builder.d.ts.map
@@ -8,26 +8,23 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const buildooor_tx_1 = require("./transaction-building/buildooor-tx");
9
9
  const errors_1 = require("../utils/errors");
10
10
  const logger = cds_1.default.log('CardanoTransactionBuilder');
11
- /**
12
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
13
- * to build various types of Cardano transactions.
14
- */
11
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
15
12
  class CardanoTransactionBuilder {
16
13
  client;
17
14
  txBuilder;
18
15
  initialized = false;
19
- /**
20
- * Create a new CardanoTransactionBuilder instance
21
- * @param client - The CardanoClient instance for UTxO fetching
22
- */
16
+ /** @param client UTxO source for coin selection */
23
17
  constructor(client) {
24
18
  this.client = client;
25
19
  logger.debug('CardanoTransactionBuilder instance created');
26
20
  }
27
- /**
28
- * Initialize the transaction builder
29
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
30
- */
21
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
22
+ addressUtxoSource = null;
23
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
24
+ setAddressUtxoSource(source) {
25
+ this.addressUtxoSource = source;
26
+ }
27
+ /** @param protocolParams optional; fetched from the backend when omitted */
31
28
  async init(protocolParams) {
32
29
  if (this.initialized && this.txBuilder)
33
30
  return;
@@ -37,42 +34,27 @@ class CardanoTransactionBuilder {
37
34
  this.initialized = true;
38
35
  logger.debug(`Initialized with builder: ${this.txBuilder.name}`);
39
36
  }
40
- /**
41
- * Ensure the builder is initialized and return it (lazy init)
42
- * @returns {Promise<CardanoTxBuilder>} initialized builder
43
- * @throws {Error} if builder cannot be initialized
44
- */
37
+ /** Lazily initialize and return the builder. */
45
38
  async ensureInitialized() {
46
39
  if (!this.initialized || !this.txBuilder) {
47
40
  await this.init();
48
41
  }
49
42
  return this.txBuilder;
50
43
  }
51
- /**
52
- * Reset the transaction builder (useful for testing)
53
- */
44
+ /** Reset the builder (testing). */
54
45
  reset() {
55
46
  this.txBuilder = undefined;
56
47
  this.initialized = false;
57
48
  logger.debug(`Builder reset`);
58
49
  }
59
- /**
60
- * Set the transaction builder directly (for testing)
61
- * @param builder - The builder to set
62
- */
50
+ /** Set the builder directly (testing). */
63
51
  setBuilder(builder) {
64
52
  this.txBuilder = builder;
65
53
  this.initialized = true;
66
54
  }
67
- /**
68
- * Build a simple ADA transfer transaction
69
- * @param req transaction build request
70
- * @param protocolParameters current protocol parameters
71
- * @returns {Promise<TxBuildResult>} transaction build result
72
- */
55
+ /** Build a simple ADA transfer transaction. */
73
56
  async buildSimpleAdaTransaction(req, protocolParameters) {
74
57
  const builder = await this.ensureInitialized();
75
- // prepare the transaction build context
76
58
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
77
59
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
78
60
  const txContext = {
@@ -80,21 +62,13 @@ class CardanoTransactionBuilder {
80
62
  protocolParameters: protocolParameters
81
63
  };
82
64
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
83
- // Build the unsigned transfer transaction
84
65
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
85
66
  logger.debug(`Built simple ADA transaction successfully.`);
86
- // Return the transaction build result
87
67
  return txBuildResult;
88
68
  }
89
- /**
90
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
91
- * @param req transaction build request
92
- * @param protocolParameters current protocol parameters
93
- * @returns {Promise<TxBuildResult>} transaction build result
94
- */
69
+ /** Build a transaction with metadata (simple or multi-asset). */
95
70
  async buildTransactionWithMetadata(req, protocolParameters) {
96
71
  const builder = await this.ensureInitialized();
97
- // Prepare the transaction build context
98
72
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
99
73
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
100
74
  const txContext = {
@@ -102,24 +76,16 @@ class CardanoTransactionBuilder {
102
76
  protocolParameters: protocolParameters
103
77
  };
104
78
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
105
- // Build the unsigned transaction with metadata
106
79
  const txBuildResult = await builder.buildUnsignedTransactionWithMetadata(req, txContext);
107
80
  logger.debug(`Built transaction with metadata successfully.`);
108
- // Return the transaction build result
109
81
  return txBuildResult;
110
82
  }
111
- /**
112
- * Build a multi-asset transaction
113
- * @param req transaction build request
114
- * @param protocolParameters current protocol parameters
115
- * @returns {Promise<TxBuildResult>} transaction build result
116
- */
83
+ /** Build a multi-asset transaction. */
117
84
  async buildMultiAssetTransaction(req, protocolParameters) {
118
85
  if (!req.assets || req.assets.length === 0) {
119
86
  throw new Error('[CardanoTransactionBuilder] buildMultiAssetTransaction requires assets to be specified');
120
87
  }
121
88
  const builder = await this.ensureInitialized();
122
- // Prepare the transaction build context
123
89
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
124
90
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
125
91
  const txContext = {
@@ -127,39 +93,30 @@ class CardanoTransactionBuilder {
127
93
  protocolParameters: protocolParameters
128
94
  };
129
95
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
130
- // Build the unsigned transfer transaction (unified with simple ADA transfer)
131
96
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
132
97
  logger.debug(`Built multi-asset transaction successfully.`);
133
98
  return txBuildResult;
134
99
  }
135
- /**
136
- * Build a minting transaction
137
- * @param req transaction build request
138
- * @param protocolParameters current protocol parameters
139
- * @returns {Promise<TxBuildResult>} transaction build result
140
- */
100
+ /** Build a minting transaction. */
141
101
  async buildMintTransaction(req, protocolParameters) {
142
- // Validate mint-specific required fields
143
102
  if (!req.mintActions || req.mintActions.length === 0) {
144
103
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintActions to be specified');
145
104
  }
146
105
  if (!req.mintingPolicyScript) {
147
106
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintingPolicyScript to be specified');
148
107
  }
149
- // Type is now narrowed to TxBuildMintRequest
150
108
  const mintReq = req;
151
109
  const builder = await this.ensureInitialized();
152
110
  const cardanoClient = this.client;
153
- // Prepare the transaction build context
154
111
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
155
112
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
156
- // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
113
+ // CIP-31 reference inputs are not consumed, so they stay out of coin selection.
157
114
  const referenceInputUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], senderUtxos);
158
115
  const txContext = {
159
116
  utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
160
117
  protocolParameters: protocolParameters,
161
118
  // Pass evaluator if Ogmios is available for dynamic execution unit calculation
162
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
119
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
163
120
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
164
121
  : undefined,
165
122
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -171,18 +128,11 @@ class CardanoTransactionBuilder {
171
128
  else {
172
129
  logger.debug(`Ogmios not available - using default execution units`);
173
130
  }
174
- // Build the unsigned minting transaction
175
131
  const txBuildResult = await builder.buildUnsignedMintTransaction(mintReq, txContext);
176
132
  logger.debug(`Built minting transaction successfully.`);
177
- // Return the transaction build result
178
133
  return txBuildResult;
179
134
  }
180
- /**
181
- * Build a Plutus spending transaction (consume UTxO at script address)
182
- * @param req transaction build request
183
- * @param protocolParameters current protocol parameters
184
- * @returns {Promise<TxBuildResult>} transaction build result
185
- */
135
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
186
136
  async buildPlutusSpendTransaction(req, protocolParameters) {
187
137
  if (!req.plutusScriptExecution) {
188
138
  throw new Error('[CardanoTransactionBuilder] buildPlutusSpendTransaction requires plutusScriptExecution to be specified');
@@ -192,45 +142,23 @@ class CardanoTransactionBuilder {
192
142
  const cardanoClient = this.client;
193
143
  // Fetch sender UTxOs for fee payment
194
144
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
195
- // Fetch the script UTxO separately (it's at the script address, not sender address)
196
- // We include it in the UTxO set so the builder can find it
145
+ // The script UTxO sits at the script address; add it so the builder can find it
197
146
  const scriptRef = spendReq.plutusScriptExecution.scriptUtxo;
198
147
  const allUtxos = [...senderUtxos];
199
- // Check if the script UTxO is already in sender UTxOs (unlikely but possible)
200
148
  const alreadyIncluded = senderUtxos.some(u => u.txHash === scriptRef.txHash && u.outputIndex === scriptRef.outputIndex);
201
149
  if (!alreadyIncluded) {
202
- // Fetch script UTxO via transaction lookup - the backend needs to provide it
203
- // For now, we create a minimal UTxO entry from what we know
204
- // The actual UTxO data will be resolved by the backend during tx building
205
- logger.debug(`Script UTxO ${scriptRef.txHash}#${scriptRef.outputIndex} not in sender UTxOs - fetching from backend`);
206
- const tx = await cardanoClient.getTransaction(scriptRef.txHash);
207
- const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
208
- if (!scriptOutput) {
209
- throw new errors_1.TransactionValidationError(`Script UTxO output ${scriptRef.txHash}#${scriptRef.outputIndex} not found in transaction`);
210
- }
211
- // spending an already-consumed script UTxO is the most common replay mistake —
212
- // catch it here with a clear 400 instead of a node-side rejection at submit
213
- await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
214
- allUtxos.push({
215
- txHash: scriptRef.txHash,
216
- outputIndex: scriptRef.outputIndex,
217
- address: scriptOutput.address,
218
- amount: scriptOutput.amount,
219
- inlineDatum: scriptOutput.inlineDatum,
220
- datumHash: scriptOutput.dataHash ?? undefined,
221
- scriptRef: scriptOutput.referenceScriptHash ?? undefined,
222
- });
150
+ allUtxos.push(await this._resolveScriptUtxo(scriptRef));
223
151
  }
224
- // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
225
- // The builder itself will skip any forced ref that matches scriptRef.
152
+ // Forced inputs may overlap with sender UTxOs, dedup below.
153
+ // The builder skips a forced ref that matches scriptRef.
226
154
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
227
155
  const mergedUtxos = mergeUtxosUnique(allUtxos, forcedUtxos);
228
- // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
156
+ // CIP-31 reference inputs are not consumed, so they stay out of coin selection.
229
157
  const referenceInputUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
230
158
  const txContext = {
231
159
  utxos: mergedUtxos,
232
160
  protocolParameters: protocolParameters,
233
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
161
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
234
162
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
235
163
  : undefined,
236
164
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -246,15 +174,99 @@ class CardanoTransactionBuilder {
246
174
  logger.debug(`Built Plutus spending transaction successfully.`);
247
175
  return txBuildResult;
248
176
  }
249
- /**
250
- * Verify that a transaction output resolved via getTransaction is still unspent,
251
- * by checking the live UTxO set of its address. getTransaction only proves the
252
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
253
- * rejection at submit instead of a clear 400 here.
254
- *
255
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
256
- * build on a flaky backend would be a new failure mode).
257
- */
177
+ /** Several script inputs in one transaction. */
178
+ async buildPlutusTransaction(req, protocolParameters) {
179
+ const builder = await this.ensureInitialized();
180
+ const cardanoClient = this.client;
181
+ const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
182
+ const scriptUtxos = await this._resolveInputRefs(req.scriptInputs.map(s => ({ txHash: s.txHash, outputIndex: s.outputIndex })), senderUtxos, 'scriptInput');
183
+ const allUtxos = mergeUtxosUnique(senderUtxos, scriptUtxos);
184
+ const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
185
+ // Reference-script UTxOs always from the ledger: a known sender UTxO may carry only the script hash
186
+ const refScriptUtxos = await this._resolveInputRefs([
187
+ ...req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])),
188
+ ...(req.withdrawals ?? []).flatMap(w => (w.referenceScript ? [w.referenceScript] : [])),
189
+ ...(req.certificates ?? []).flatMap(c => (c.referenceScript ? [c.referenceScript] : [])),
190
+ ...(req.mintActions ?? []).flatMap(m => (m.referenceScript ? [m.referenceScript] : [])),
191
+ ], [], 'referenceScript');
192
+ const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
193
+ const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
194
+ // A credential this transaction registers is withdrawable in the same transaction
195
+ const registeredHere = new Set((req.certificates ?? []).filter(c => c.type === 'registerStake').map(c => c.stakeAddress.toLowerCase()));
196
+ await this._assertRewardAccountsRegistered(req.withdrawals ?? [], registeredHere);
197
+ const txContext = {
198
+ utxos: mergeUtxosUnique(allUtxos, forcedUtxos),
199
+ protocolParameters,
200
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
201
+ ? (cbor) => cardanoClient.evaluateTransaction(cbor)
202
+ : undefined,
203
+ referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined,
204
+ };
205
+ logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
206
+ return builder.buildUnsignedPlutusTransaction(req, txContext);
207
+ }
208
+ // The ledger rejects a withdrawal from an unregistered reward account, even a zero one.
209
+ // When no backend can tell, the build goes on and the node decides at submit.
210
+ async _assertRewardAccountsRegistered(withdrawals, registeredHere = new Set()) {
211
+ for (const [i, w] of withdrawals.entries()) {
212
+ if (registeredHere.has(w.rewardAddress.toLowerCase()))
213
+ continue;
214
+ const registered = await this.client.isRewardAccountRegistered(w.rewardAddress);
215
+ if (registered === false) {
216
+ throw new errors_1.TransactionValidationError(`withdrawals[${i}] reward account ${w.rewardAddress} is not registered on chain; register the stake credential first`);
217
+ }
218
+ if (registered === null) {
219
+ logger.warn(`withdrawals[${i}] reward account ${w.rewardAddress}: registration not verifiable (the node lists delegated accounts only, no provider answered); the node checks it at submit`);
220
+ }
221
+ }
222
+ }
223
+ // Spending an already-consumed script UTxO is a common replay mistake.
224
+ // Both lookup paths reject it with a clear 400 instead of a node rejection at submit.
225
+ async _resolveScriptUtxo(scriptRef) {
226
+ const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
227
+ if (by)
228
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} is spent by transaction ${by}, submitted and not yet on chain`);
229
+ const ledger = await this._lookupUnspent([scriptRef]);
230
+ if (ledger) {
231
+ const live = ledger.get(outRefKey(scriptRef));
232
+ if (!live) {
233
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} not found on-chain or already spent`);
234
+ }
235
+ return live;
236
+ }
237
+ logger.debug(`Script UTxO ${outRefKey(scriptRef)} not in sender UTxOs - fetching its transaction`);
238
+ const tx = await this.client.getTransaction(scriptRef.txHash);
239
+ const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
240
+ if (!scriptOutput) {
241
+ throw new errors_1.TransactionValidationError(`Script UTxO output ${outRefKey(scriptRef)} not found in transaction`);
242
+ }
243
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
244
+ return {
245
+ txHash: scriptRef.txHash,
246
+ outputIndex: scriptRef.outputIndex,
247
+ address: scriptOutput.address,
248
+ amount: scriptOutput.amount,
249
+ inlineDatum: scriptOutput.inlineDatum,
250
+ datumHash: scriptOutput.dataHash ?? undefined,
251
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
252
+ };
253
+ }
254
+ // Null when no ledger-state backend is usable or the query fails.
255
+ // Callers then fall back to getTransaction.
256
+ async _lookupUnspent(refs) {
257
+ if (refs.length === 0)
258
+ return new Map();
259
+ try {
260
+ const utxos = await this.client.getUnspentOutputs(refs);
261
+ return utxos ? new Map(utxos.map(u => [outRefKey(u), u])) : null;
262
+ }
263
+ catch (err) {
264
+ logger.warn(`Ledger lookup of ${refs.length} output reference(s) failed, falling back to the producing transactions: ${err instanceof Error ? err.message : String(err)}`);
265
+ return null;
266
+ }
267
+ }
268
+ // getTransaction only proves an output existed, so check the address's live UTxO set.
269
+ // Lookup failures are tolerated.
258
270
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
271
  let live;
260
272
  try {
@@ -276,35 +288,24 @@ class CardanoTransactionBuilder {
276
288
  throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
289
  }
278
290
  }
279
- /**
280
- * Resolve forced-input refs (consumed) to full UTxO records.
281
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
- */
291
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
283
292
  _resolveForceInputs(refs, senderUtxos) {
284
293
  return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
294
  }
286
- /**
287
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
- * coin-selection set) to full UTxO records.
289
- */
295
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
290
296
  _resolveReferenceInputs(refs, knownUtxos) {
291
297
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
292
298
  }
293
- /**
294
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
295
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
296
- * otherwise fetches the producing transaction and verifies the output is
297
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
298
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
299
- *
300
- * @param refs input refs from the request
301
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
302
- * @param kind label used in error messages / the spent-check
303
- * @returns resolved UTxOs, in the same order as the deduped refs
304
- */
299
+ // Known UTxOs first, then the node's ledger, else the producing transaction plus an unspent check.
300
+ // Throws for a missing or spent ref. Refs are deduplicated in order.
305
301
  async _resolveInputRefs(refs, knownUtxos, kind) {
306
302
  if (!refs || refs.length === 0)
307
303
  return [];
304
+ for (const r of refs) {
305
+ const by = this.client.pendingSpends?.spentBy(r.txHash, r.outputIndex);
306
+ if (by)
307
+ throw new errors_1.TransactionValidationError(`${kind} ${r.txHash}#${r.outputIndex} is spent by transaction ${by}, submitted and not yet on chain`);
308
+ }
308
309
  // Dedup by "txHash#index" key
309
310
  const seen = new Set();
310
311
  const dedupedRefs = refs.filter(r => {
@@ -314,6 +315,8 @@ class CardanoTransactionBuilder {
314
315
  seen.add(key);
315
316
  return true;
316
317
  });
318
+ const isKnown = (r) => knownUtxos.some(u => u.txHash === r.txHash && u.outputIndex === r.outputIndex);
319
+ const ledger = await this._lookupUnspent(dedupedRefs.filter(r => !isKnown(r)));
317
320
  const liveUtxoCache = new Map();
318
321
  const resolved = [];
319
322
  for (const ref of dedupedRefs) {
@@ -323,7 +326,16 @@ class CardanoTransactionBuilder {
323
326
  resolved.push(local);
324
327
  continue;
325
328
  }
326
- // 2) Fallback: fetch the producing transaction and look up the output.
329
+ // 2) The node's ledger answers existence and spendability in one lookup
330
+ if (ledger) {
331
+ const live = ledger.get(outRefKey(ref));
332
+ if (!live) {
333
+ throw new errors_1.TransactionValidationError(`${kind} ${outRefKey(ref)} not found on-chain or already spent`);
334
+ }
335
+ resolved.push(live);
336
+ continue;
337
+ }
338
+ // 3) Fallback: fetch the producing transaction and look up the output.
327
339
  let tx;
328
340
  try {
329
341
  tx = await this.client.getTransaction(ref.txHash);
@@ -349,33 +361,45 @@ class CardanoTransactionBuilder {
349
361
  }
350
362
  return resolved;
351
363
  }
352
- /**
353
- * Fetch UTxOs for a given address
354
- * @param address bech32 address
355
- * @returns {Promise<UTxO[]>} list of UTxOs
356
- */
364
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
357
365
  async _fetchUtxosForAddress(address) {
358
366
  logger.debug(`Fetching UTxOs for address: ${address}`);
359
- const utxos = await this.client.getAddressUtxos(address);
367
+ // The crawled set answers with an index lookup; the node's address query scans its whole
368
+ // UTxO set. An empty answer from the set is re-checked there (funded in the last block).
369
+ const local = await this.addressUtxoSource?.(address).catch((err) => {
370
+ logger.warn(`Local UTxO lookup for ${address} failed, asking the node: ${err instanceof Error ? err.message : String(err)}`);
371
+ return null;
372
+ });
373
+ const ledger = local && local.length > 0 ? local : await this.client.getAddressUtxos(address);
374
+ // the ledger view still lists what our own submitted transactions spend while they wait in the mempool
375
+ const all = this.client.pendingSpends?.apply(address, ledger) ?? ledger;
376
+ // A UTxO carrying a reference script is deployed on purpose, not change to spend; only a
377
+ // forced input consumes it (the fee of a spent reference script is also not counted by the builder).
378
+ const utxos = all.filter(u => !u.scriptRef && !u.scriptRefCbor);
379
+ if (utxos.length < all.length)
380
+ logger.debug(`${all.length - utxos.length} UTxO(s) with a reference script left out of coin selection`);
360
381
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
361
382
  if (utxos.length === 0) {
362
- throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
383
+ throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
384
+ ? `address ${address} holds only UTxOs with a reference script; they are not spent as funding, pass one in forceInputsJson to consume it`
385
+ : `address ${address} has no UTxOs; verify this is the correct sender address and that it has been funded`);
363
386
  }
364
387
  return utxos;
365
388
  }
366
389
  }
367
390
  exports.CardanoTransactionBuilder = CardanoTransactionBuilder;
368
- /**
369
- * Merge two UTxO lists, skipping refs already present in the first.
370
- * Used to add forced UTxOs to a context without duplicating existing entries.
371
- */
391
+ /** "txHash#outputIndex" key of an output reference. */
392
+ function outRefKey(ref) {
393
+ return `${ref.txHash}#${ref.outputIndex}`;
394
+ }
395
+ /** Merge two UTxO lists, skipping refs already present in the first. */
372
396
  function mergeUtxosUnique(base, extra) {
373
397
  if (extra.length === 0)
374
398
  return base;
375
- const seen = new Set(base.map(u => `${u.txHash}#${u.outputIndex}`));
399
+ const seen = new Set(base.map(outRefKey));
376
400
  const result = [...base];
377
401
  for (const u of extra) {
378
- const key = `${u.txHash}#${u.outputIndex}`;
402
+ const key = outRefKey(u);
379
403
  if (!seen.has(key)) {
380
404
  seen.add(key);
381
405
  result.push(u);
@@ -7,26 +7,15 @@ export interface CircuitBreakerConfig {
7
7
  /** Time in ms before transitioning from open to half-open (default: 30000) */
8
8
  resetTimeoutMs: number;
9
9
  }
10
- /**
11
- * Circuit Breaker for backend failover.
12
- * Tracks per-backend failure counts and prevents hammering unhealthy backends.
13
- *
14
- * States:
15
- * closed → normal operation, requests pass through
16
- * open → backend is unhealthy, requests are skipped
17
- * half-open → probe period, limited requests allowed to test recovery
18
- */
19
10
  export declare class CircuitBreakerManager {
20
11
  private circuits;
21
12
  private config;
22
13
  constructor(config?: Partial<CircuitBreakerConfig>);
23
- /**
24
- * Check if a backend should be attempted.
25
- * Transitions open → half-open if reset timeout has elapsed.
26
- */
14
+ /** Moves an open circuit to half-open once the reset timeout has elapsed. */
27
15
  shouldAttempt(backendName: string): boolean;
28
16
  /** Record a successful call to a backend. */
29
17
  recordSuccess(backendName: string): void;
18
+ recordVerdict(backendName: string): void;
30
19
  /** Record a failed call to a backend. */
31
20
  recordFailure(backendName: string): void;
32
21
  /** Get the current state of a backend's circuit. */