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

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 +1193 -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 +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +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 +130 -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
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.blockRowToData = blockRowToData;
7
+ exports.readBlock = readBlock;
8
+ exports.readBlockByHeight = readBlockByHeight;
9
+ exports.readNextBlocks = readNextBlocks;
10
+ exports.lacksOutpoints = lacksOutpoints;
11
+ exports.readTransactionsByHash = readTransactionsByHash;
12
+ exports.readBlockTransactions = readBlockTransactions;
13
+ exports.readTransactionMetadata = readTransactionMetadata;
14
+ const cds_1 = __importDefault(require("@sap/cds"));
15
+ const client_1 = require("@cardano-ogmios/client");
16
+ const cardano_1 = require("#cds-models/odatano/cardano");
17
+ const collections_1 = require("../utils/collections");
18
+ const { SELECT } = cds_1.default.ql;
19
+ const num = (v) => Number(v ?? 0);
20
+ const numOrNull = (v) => (v == null ? null : Number(v));
21
+ const str = (v) => (v == null ? '' : String(v));
22
+ /** `Blocks` row -> BlockData. */
23
+ function blockRowToData(row) {
24
+ return {
25
+ time: Math.floor(Date.parse(str(row.time)) / 1000),
26
+ height: numOrNull(row.height),
27
+ hash: str(row.hash),
28
+ slot: numOrNull(row.slot),
29
+ slotLeader: str(row.slotLeader),
30
+ epoch: numOrNull(row.epochNumber),
31
+ epochSlot: numOrNull(row.epochSlot),
32
+ size: num(row.size),
33
+ txCount: num(row.txCount),
34
+ fees: row.fees == null ? null : String(row.fees),
35
+ };
36
+ }
37
+ /** A stored block by hash; null when not indexed. */
38
+ async function readBlock(db, hash) {
39
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ hash }));
40
+ return row ? blockRowToData(row) : null;
41
+ }
42
+ /** A stored block by height; null when not indexed. */
43
+ async function readBlockByHeight(db, height) {
44
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
45
+ return row ? blockRowToData(row) : null;
46
+ }
47
+ /**
48
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
49
+ * the first missing height, so a caller never walks over a gap.
50
+ */
51
+ async function readNextBlocks(db, afterHeight, count) {
52
+ const rows = await db.run(
53
+ // one operator per column object: `{ '>': a, '<=': b }` renders as `height > a <= b`
54
+ SELECT.from(cardano_1.Blocks).where({ height: { between: afterHeight + 1, and: afterHeight + count } }).orderBy('height asc'));
55
+ const out = [];
56
+ let expected = afterHeight + 1;
57
+ for (const row of rows ?? []) {
58
+ if (num(row.height) !== expected)
59
+ break;
60
+ out.push(blockRowToData(row));
61
+ expected++;
62
+ }
63
+ return out;
64
+ }
65
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
66
+ function lacksOutpoints(t) {
67
+ return (t.inputs ?? []).some(i => i.txHash == null);
68
+ }
69
+ /** Stored transactions by hash (missing hashes are absent from the map). */
70
+ async function readTransactionsByHash(db, hashes) {
71
+ const rows = [];
72
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
73
+ rows.push(...((await db.run(SELECT.from(cardano_1.Transactions).where({ hash: { in: hashChunk } }))) ?? []));
74
+ }
75
+ const txs = await assembleTransactions(db, rows);
76
+ return new Map(txs.map(t => [t.hash, t]));
77
+ }
78
+ /**
79
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
80
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
81
+ */
82
+ async function readBlockTransactions(db, blockHash) {
83
+ const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
84
+ if (!block)
85
+ return null;
86
+ const rows = await db.run(SELECT.from(cardano_1.Transactions).where({ blockHash }).orderBy('txIndex asc'));
87
+ if ((rows ?? []).length !== num(block.txCount))
88
+ return null;
89
+ return assembleTransactions(db, rows ?? []);
90
+ }
91
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
92
+ async function readTransactionMetadata(db, txHash) {
93
+ const known = await db.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ hash: txHash }));
94
+ if (!known)
95
+ return null;
96
+ const rows = await db.run(SELECT.from(cardano_1.TransactionMetadata_).where({ tx_hash: txHash }));
97
+ return (rows ?? []).map(metadataRow);
98
+ }
99
+ function metadataRow(r) {
100
+ return {
101
+ txHash: str(r.tx_hash),
102
+ label: str(r.label),
103
+ json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
104
+ };
105
+ }
106
+ /** Amount list with lovelace first, as the providers deliver it. */
107
+ function amounts(assets) {
108
+ const list = assets.map(a => ({ unit: str(a.unit), quantity: str(a.asset_quantity) }));
109
+ return [...list.filter(a => a.unit === 'lovelace'), ...list.filter(a => a.unit !== 'lovelace')];
110
+ }
111
+ function groupBy(rows, key) {
112
+ const out = new Map();
113
+ for (const r of rows) {
114
+ const k = key(r);
115
+ const list = out.get(k);
116
+ if (list)
117
+ list.push(r);
118
+ else
119
+ out.set(k, [r]);
120
+ }
121
+ return out;
122
+ }
123
+ /** Transactions rows + their child tables -> provider transactions, in the order of `rows`. */
124
+ async function assembleTransactions(db, rows) {
125
+ if (rows.length === 0)
126
+ return [];
127
+ const seqs = rows.map(r => r.txSeq);
128
+ const hashes = rows.map(r => str(r.hash));
129
+ const fetchIn = async (entity, column, keys) => {
130
+ const out = [];
131
+ for (const c of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
132
+ out.push(...((await db.run(SELECT.from(entity).where({ [column]: { in: c } }))) ?? []));
133
+ }
134
+ return out;
135
+ };
136
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers] = await Promise.all([
137
+ fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
138
+ fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
139
+ fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
140
+ fetchIn(cardano_1.TransactionOutputAssets, 'output_txSeq', seqs),
141
+ fetchIn(cardano_1.TransactionMetadata_, 'tx_hash', hashes),
142
+ fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
143
+ fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
144
+ fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
145
+ fetchIn(cardano_1.TransactionRedeemers, 'tx_hash', hashes),
146
+ ]);
147
+ const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
148
+ const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
149
+ const outputsBySeq = groupBy(outputs, r => str(r.txSeq));
150
+ const outputAssetsByKey = groupBy(outputAssets, r => `${r.output_txSeq}#${r.output_outputIndex}`);
151
+ const metadataByHash = groupBy(metadata, r => str(r.tx_hash));
152
+ const certsByHash = groupBy(certificates, r => str(r.tx_hash));
153
+ const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
154
+ const mintsByHash = groupBy(mints, r => str(r.txHash));
155
+ const redeemersByHash = groupBy(redeemers, r => str(r.tx_hash));
156
+ return rows.map((t) => {
157
+ const seq = str(t.txSeq);
158
+ const hash = str(t.hash);
159
+ const txInputs = (inputsBySeq.get(seq) ?? [])
160
+ .sort((a, b) => num(a.inputIndex) - num(b.inputIndex))
161
+ .map(i => ({
162
+ address: str(i.address_address),
163
+ amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
164
+ // null on rows indexed before the outpoint was recorded, never a made-up reference
165
+ txHash: (i.spentTxHash ?? null),
166
+ outputIndex: numOrNull(i.spentOutputIndex),
167
+ dataHash: i.utxoData_dataHash ?? null,
168
+ inlineDatum: i.utxoData_inlineDatum ?? null,
169
+ referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
170
+ isCollateral: Boolean(i.isCollateral),
171
+ isReference: Boolean(i.isReference),
172
+ }));
173
+ // a phase-2 failure keeps only collateral and reference inputs, and its collateral return
174
+ const spendsCollaterals = txInputs.some(i => i.isCollateral) && !txInputs.some(i => !i.isCollateral && !i.isReference);
175
+ const txOutputs = (outputsBySeq.get(seq) ?? [])
176
+ .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
177
+ .map(o => ({
178
+ address: str(o.address_address),
179
+ amount: amounts(outputAssetsByKey.get(`${seq}#${o.outputIndex}`) ?? []),
180
+ txHash: hash,
181
+ outputIndex: num(o.outputIndex),
182
+ dataHash: o.utxo_dataHash ?? null,
183
+ inlineDatum: o.utxo_inlineDatum ?? null,
184
+ isCollateral: spendsCollaterals,
185
+ referenceScriptHash: o.utxo_referenceScriptHash ?? null,
186
+ }));
187
+ const certs = certsByHash.get(hash);
188
+ const withdrawn = withdrawalsByHash.get(hash);
189
+ const minted = mintsByHash.get(hash);
190
+ const redeemed = redeemersByHash.get(hash);
191
+ return {
192
+ hash,
193
+ blockHash: str(t.blockHash),
194
+ blockHeight: num(t.blockHeight),
195
+ slot: num(t.slot),
196
+ index: num(t.txIndex),
197
+ fee: str(t.fee ?? '0'),
198
+ deposit: str(t.deposit ?? '0'),
199
+ size: numOrNull(t.size),
200
+ blockTime: num(t.blockTime),
201
+ spendsCollaterals,
202
+ mint: minted?.map(m => ({
203
+ unit: str(m.unit),
204
+ quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
205
+ })),
206
+ inputs: txInputs,
207
+ outputs: txOutputs,
208
+ metadata: (metadataByHash.get(hash) ?? []).map(metadataRow),
209
+ certificates: certs?.map((c) => ({
210
+ certIndex: num(c.certIndex),
211
+ kind: str(c.kind),
212
+ stakeAddress: c.stakeAddress ?? null,
213
+ poolId: c.poolId ?? null,
214
+ drepId: c.drepId ?? null,
215
+ deposit: c.deposit == null ? null : String(c.deposit),
216
+ epoch: numOrNull(c.epoch),
217
+ })),
218
+ withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
219
+ redeemers: redeemed
220
+ ?.sort((a, b) => str(a.purpose).localeCompare(str(b.purpose)) || num(a.redeemerIndex) - num(b.redeemerIndex))
221
+ .map((r) => ({
222
+ purpose: str(r.purpose),
223
+ index: num(r.redeemerIndex),
224
+ data: str(r.data),
225
+ mem: str(r.mem),
226
+ steps: str(r.steps),
227
+ txHash: r.spentTxHash ?? null,
228
+ outputIndex: numOrNull(r.spentOutputIndex),
229
+ policyId: r.policyId ?? null,
230
+ })),
231
+ };
232
+ });
233
+ }
234
+ //# sourceMappingURL=stored-chain.js.map
@@ -1,9 +1,7 @@
1
1
  import type { CardanoTxBuilder } from "./cardano-tx";
2
- import type { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
2
+ import type { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildPlutusRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
3
3
  import { CardanoClient } from "../cardano-client";
4
- /**
5
- * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
6
- */
4
+ /** CardanoTxBuilder implementation on top of Buildooor. */
7
5
  export declare class BuildooorTxBuilder implements CardanoTxBuilder {
8
6
  readonly name = "BuildooorTxBuilder";
9
7
  private txBuilder;
@@ -11,90 +9,74 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
11
9
  private genesisInfos;
12
10
  private paramsFingerprint;
13
11
  /**
14
- * Chain cost-model arrays kept verbatim for language-view hashing. Maintained by
15
- * _mapCostModels (in lockstep with the named-key models the TxBuilder is built
16
- * with); consumed by _languageViewCostModels. Empty when the current parameters
17
- * carry no usable cost models (library defaults in effect).
12
+ * Chain cost-model arrays kept verbatim for language-view hashing; set by _mapCostModels,
13
+ * empty when the current parameters carry no usable cost models.
18
14
  */
19
15
  private rawCostModelArrays;
20
16
  /**
21
- * Initialize the builder
22
- * @param client - The CardanoClient instance
23
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
17
+ * Initialize the builder.
18
+ * @param protocolParams - optional; fetched from the backend when omitted
24
19
  */
25
20
  init(client: CardanoClient, protocolParams?: LedgerProtocolParameters): Promise<void>;
26
21
  /**
27
- * Rebuild the TxBuilder when the per-request protocol parameters differ from
28
- * the ones the current TxBuilder was constructed with. Buildooor's TxBuilder
29
- * has no setter for protocol params, but its constructor is cheap, so we
30
- * rebuild on change (effectively once per epoch) instead of staying frozen
31
- * at init-time parameters for the process lifetime.
22
+ * Rebuild the TxBuilder when the per-request protocol parameters differ from the current
23
+ * ones; the TxBuilder has no setter but its constructor is cheap (effectively once per epoch).
32
24
  */
33
25
  private _ensureCurrentProtocolParameters;
34
26
  private _applyProtocolParameters;
35
- /**
36
- * Build unsigned transfer transaction (ADA-only or with native assets).
37
- */
27
+ /** Build an unsigned transfer transaction (ADA-only or with native assets). */
38
28
  buildUnsignedTransfer(req: TxBuildRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
39
- /**
40
- * Build unsigned transfer transaction with attached metadata.
41
- */
29
+ /** Build an unsigned transfer transaction with attached metadata. */
42
30
  buildUnsignedTransactionWithMetadata(req: TxBuildRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
43
31
  /**
44
- * Shared non-script transfer build. The two public entry points only differ in
45
- * the optional pieces of the request they carry (assets/outputDatum on the
46
- * plain-transfer path, metadataJson on the metadata path) — all handled here
47
- * conditionally on the field being present, so behaviour matches both.
32
+ * Shared non-script transfer build; assets, outputDatum and metadataJson are each
33
+ * handled only when present in the request.
48
34
  */
49
35
  private _buildSimpleTransfer;
50
36
  buildUnsignedMintTransaction(req: TxBuildMintRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
51
37
  buildUnsignedPlutusSpendTransaction(req: TxBuildPlutusSpendRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
38
+ /**
39
+ * Several script inputs in one transaction, each with its own redeemer (inline validator or a
40
+ * reference-script UTxO), the outputs exactly in the given order and change after them.
41
+ */
42
+ buildUnsignedPlutusTransaction(req: TxBuildPlutusRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
43
+ /**
44
+ * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
45
+ * Returns the inline datums given as CBOR, keyed by output index.
46
+ */
47
+ private _appendPlutusOutputs;
48
+ /**
49
+ * Min-ADA of an output, counting the caller's datum bytes where they are longer than
50
+ * Buildooor's encoding. `forAnyAmount` sizes the coin field for the largest amount, so the
51
+ * result stays valid once written into the output.
52
+ */
53
+ private _minOutputLovelace;
54
+ /** Build, then write the caller's datum bytes; when they are longer, a second build raises the fee. */
55
+ private _buildWithCallerDatums;
52
56
  /** Extract CBOR, hash, fee, size, inputs and outputs from a built Buildooor Tx */
53
57
  private _extractTxDetails;
54
58
  /** Build the standard TxBuildResult object */
55
59
  private _buildResult;
56
60
  /**
57
- * Build a script-bearing transaction whose redeemers carry *real* execution units and
58
- * whose fee covers them.
59
- *
60
- * Background (verified against the vendored Buildooor source): `initTxBuild` constructs
61
- * every redeemer with a dummy budget — caller-supplied execution units in the build args
62
- * are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
63
- * the budget the local CEK run consumed, even when the script failed (partial budget).
64
- * So the declared units are whatever the *local* evaluation produced, and any cushion
65
- * passed into the args silently evaporates. This method makes the declared units real:
66
- *
67
- * 1. First pass: build once; redeemers now carry the local CEK budgets.
68
- * 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
69
- * budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
70
- * 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
71
- * without an Ogmios result aborts — see makeScriptBuildOpts).
72
- * 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
73
- * from its own local budgets, so the floor adds the price + encoding-size delta).
74
- * 5. Stamp the target units into the redeemers and recompute scriptDataHash.
61
+ * Build a script-bearing transaction with real execution units: Buildooor stamps local CEK
62
+ * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
63
+ * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
75
64
  */
76
65
  private _buildScriptTx;
77
66
  /**
78
- * Evaluate a transaction via Ogmios and return cushioned budgets keyed per redeemer
79
- * (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
80
- * failure, empty result) so callers fall back to buffered local units. A
81
- * TransactionValidationError or ScriptValidationError from the evaluator is
82
- * authoritative (the script really failed on the ledger) and is rethrown.
67
+ * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
68
+ * evaluation is unusable (transient failure, empty result). Validation errors are rethrown.
83
69
  */
84
70
  private _evaluateExUnitsByRedeemer;
85
71
  /**
86
- * Combined cushion: relative multiplier catches proportional drift on large
87
- * validators, absolute floor catches sub-percent drift on small ones (observed
88
- * when metadata affects the real tx body vs the evaluator's ScriptContext).
72
+ * Cushion: relative multiplier for proportional drift on large validators, absolute floor
73
+ * for sub-percent drift on small ones.
89
74
  */
90
75
  private _applyExUnitBuffer;
91
76
  /**
92
- * Decide the execution units each redeemer must declare.
93
- * - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
94
- * - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
95
- * - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
96
- * - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
97
- * collateral of whoever signs and submits the returned CBOR.
77
+ * Execution units each redeemer must declare: max(local, Ogmios) when both exist, buffered
78
+ * local without Ogmios, Ogmios alone after a local failure; a local failure without Ogmios
79
+ * aborts because unreliable units would forfeit the signer's collateral.
98
80
  */
99
81
  private _resolveTargetExUnits;
100
82
  /** Fee delta of the target vs local units, priced like Buildooor's own fee loop. */
@@ -103,17 +85,18 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
103
85
  private _exUnitsSizeDelta;
104
86
  private _txFeePerByte;
105
87
  /**
106
- * Replace the redeemers' execution units and recompute scriptDataHash.
107
- *
108
- * Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
109
- * 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
110
- * builder's named-key cost models, which clamp the chain array to the parameter
111
- * count the library release knows — wrong whenever the on-chain cost model has
112
- * grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
113
- * _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
114
- * is recomputed here even when the target units already match.
88
+ * Replace the redeemers' execution units and recompute scriptDataHash with the raw chain
89
+ * cost-model arrays (TxBuilder.overrideTxRedeemers hashes with clamped named-key models,
90
+ * which mismatches once the on-chain cost model grows). Recomputed even when units match.
115
91
  */
116
92
  private _stampExecUnits;
93
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
94
+ private _languageViews;
95
+ /**
96
+ * Check a witness datum against the datum hash its script UTxO is locked with: the ledger
97
+ * finds the datum by the hash of its bytes. Inline-datum UTxOs need no witness datum.
98
+ */
99
+ private _checkWitnessDatum;
117
100
  /**
118
101
  * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
119
102
  * (which flags the languages of *executed* scripts). This builder only attaches
@@ -121,49 +104,62 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
121
104
  */
122
105
  private _usedLanguageViewOpts;
123
106
  /**
124
- * Cost models for language-view hashing. The named-key objects the TxBuilder was
125
- * constructed with clamp the chain array to the parameter count this costmodels-ts
126
- * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
127
- * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
128
- * array form through unclamped, so substitute the raw chain arrays where we have
129
- * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
107
+ * Cost models for language-view hashing: named-key objects clamp the chain array to the
108
+ * parameter count this library release knows, but the ledger hashes every entry served,
109
+ * so raw chain arrays (passed through unclamped) are substituted where available.
130
110
  */
131
111
  private _languageViewCostModels;
132
112
  /**
133
- * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
134
- * coin selection / collateral). Refs in forceInputs that are not present in utxos are
135
- * silently ignored — the resolver upstream has already validated existence.
113
+ * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
114
+ * refs absent from utxos are ignored (existence is validated upstream).
136
115
  */
137
116
  private _partitionForcedInputs;
138
117
  /**
139
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
140
- * Returns empty array when no reference inputs are provided.
118
+ * Script of a withdrawal, certificate or mint: inline (swapped for a reference input that already
119
+ * carries the same hash), by reference, or none (key witness).
120
+ */
121
+ private _resolveScriptWitness;
122
+ /**
123
+ * Withdrawal credential hashes in ledger order, which `__WDRL_IDX__` resolves against. Buildooor
124
+ * numbers withdrawal redeemers by hash alone, so a scripted withdrawal whose position differs
125
+ * between the two orders would get the wrong redeemer; such a build is refused.
141
126
  */
127
+ private _ledgerWithdrawalOrder;
128
+ /**
129
+ * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
130
+ * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
131
+ * Script addresses are refused; those UTxOs are script inputs.
132
+ */
133
+ private _checkForeignForcedInputs;
134
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
135
+ private _referencedKeys;
136
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
142
137
  private _mapReferenceInputs;
143
138
  /**
144
- * Build the Buildooor mint-entry array shared by the mint-only flow and the
145
- * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
146
- * they are stamped into the redeemers post-build by _buildScriptTx).
139
+ * Funding contributed by extra outputs on a mint build: their summed lovelace plus, per asset
140
+ * unit, the demand the transaction's own positive mints do not cover.
141
+ */
142
+ private _extraOutputsFundingAfterMint;
143
+ /**
144
+ * Script a mint action executes under: its per-action policy when set, else the request's
145
+ * top-level policy script.
146
+ */
147
+ private _mintActionScript;
148
+ /**
149
+ * Buildooor mint entries shared by all mint flows. `scriptFor` gives each action's policy, inline
150
+ * or as a reference-script UTxO. Each action may carry its own redeemer (falling back to the
151
+ * request-level one); the ledger holds ONE redeemer per policy, so actions on the same policy must agree.
147
152
  */
148
153
  private _buildMintEntries;
149
154
  /**
150
- * Consumer-facing context for insufficient-funds rejections after the
151
- * collateral partition: the builder's own "not enough …" message counts only
152
- * the funding pool, and without this the reservation is invisible ("but the
153
- * address HAS enough ADA").
155
+ * Context for insufficient-funds rejections after the collateral partition: the builder's
156
+ * message counts only the funding pool, so the reservation would otherwise be invisible.
154
157
  */
155
158
  private _collateralPartitionContext;
156
159
  /**
157
- * Pick a collateral UTxO and return remaining funding UTxOs.
158
- * Throws if no ADA-only UTxO is available.
159
- *
160
- * Selection: the SMALLEST ADA-only UTxO that still covers the static
161
- * COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
162
- * The previous "first ADA-only" pick failed both ways: a dust UTxO below
163
- * collateralPercentage × fee is rejected at submit, and a large UTxO is
164
- * fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
165
- * for ADA-only collateral). Everything above the floor is therefore handed
166
- * back via an explicit collateralReturn when the excess satisfies min-ADA.
160
+ * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
161
+ * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
162
+ * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
167
163
  */
168
164
  private _setupCollateral;
169
165
  /** Build a Ledger Value from lovelace + optional multi-asset array */
@@ -171,100 +167,59 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
171
167
  /** Build a TxOut with optional inline datum and optional reference script (CIP-33) */
172
168
  private _buildTxOut;
173
169
  /**
174
- * Parse a consumer-provided, CBOR-wrapped Plutus script and reject UPLC 1.0.0
175
- * code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
176
- * would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
177
- * wrong policy IDs and unspendable script addresses with no error anywhere
178
- * down the line. The UPLC version is the first three flat-encoded naturals
179
- * of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
170
+ * Parse a CBOR-wrapped Plutus script and reject UPLC 1.0.0 code (V1/V2): Script.fromCbor
171
+ * defaults to V3 and would hash with the 0x03 prefix, giving a silently wrong script hash.
172
+ * The UPLC version is the first three flat naturals of the unwrapped script: [1,0,0] vs [1,1,0].
180
173
  */
181
174
  private _parsePlutusV3Script;
182
175
  /** Parse a Plutus V3 CBOR hex into a Buildooor Script for refScript attachment. */
183
176
  private _parseReferenceScript;
184
177
  /**
185
- * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
186
- * UTxO.scriptRef is overloaded across backends: Blockfrost/Ogmios set it to a 28-byte
187
- * hash (56 hex chars), Koios sets it to the full CBOR script bytes. Only full bytes
188
- * are usable here — hash-only entries are preserved only on-chain, not in local eval.
178
+ * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
179
+ * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
189
180
  */
190
181
  private _buildInputRefScript;
191
182
  /**
192
- * Compute the post-sort input order so __INPUT_IDX__ placeholders (FR-3) resolve to the
193
- * same indices Buildooor will assign during build(). Order: script-input first by convention,
194
- * then forced + funding sorted lexicographically on (txHash, outputIndex).
195
- * Buildooor sorts ALL inputs together; we mirror that exact behaviour via sortInputsLikeBuildooor.
183
+ * Post-sort input order so __INPUT_IDX__ placeholders resolve to the indices Buildooor assigns
184
+ * in build(): all inputs (script, forced, funding) sorted lexicographically on (txHash, outputIndex).
196
185
  */
197
186
  private _computeSortedInputs;
198
187
  /** Extract InputRef list from the Buildooor-shaped funding inputs returned by keepRelevant. */
199
188
  private _extractFundingRefs;
200
- /**
201
- * Resolve __INPUT_IDX__ placeholders (FR-3) inside each extraOutput.inlineDatum.
202
- * Returns a new array with resolved datums; non-datum fields pass through unchanged.
203
- */
189
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
204
190
  private _resolveExtraOutputPlaceholders;
205
191
  /**
206
- * Append parsed extraOutputs (FR-2) to the outputs array, enforcing min-ADA per entry.
207
- * Throws TransactionValidationError with the required min-ADA in the message so consumers
208
- * can adjust without having to inspect Buildooor internals.
192
+ * Append parsed extra outputs, enforcing min-ADA per entry; the rejection names the
193
+ * required min-ADA so consumers can adjust without inspecting Buildooor internals.
209
194
  */
210
195
  private _appendExtraOutputs;
211
196
  /**
212
- * Resolve the transaction's validity window (slots) from the request.
213
- * Falls back to `now - 2 min` / `now + 1 h` when the request omits bounds.
214
- * Script-validated builds must call this; plain transfers pass their own
215
- * explicit bounds through (no defaulting) so replay behavior is opt-in.
197
+ * Validity window (slots) from the request. Script builds default to `now - 2 min` / `now + 1 h`;
198
+ * plain transfers pass explicit bounds through without defaulting.
216
199
  */
217
200
  private _resolveValiditySlots;
218
201
  /**
219
- * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape.
220
- *
221
- * Every field is null-guarded: a missing/null source value keeps the library
222
- * default instead of degrading to 0 (`Number(null) === 0` previously set
223
- * utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
224
- * execution-unit prices are mapped because they feed the scriptDataHash
225
- * (language views) and the fee/ExUnits math — stale defaults there cause
226
- * PPViewHashesDontMatch or fee underestimation on-chain.
202
+ * Map LedgerProtocolParameter to Buildooor's ProtocolParameters. Every field is null-guarded so a
203
+ * missing value keeps the library default instead of degrading to 0 (e.g. utxoCostPerByte = 0
204
+ * disables min-ADA); cost models and ExUnit prices feed scriptDataHash and the fee math.
227
205
  */
228
206
  private _mapLedgerParametersToBuildooorParams;
229
207
  /**
230
- * Parse the cost-models JSON blob (backend-normalized number arrays, keys
231
- * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
232
- * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
233
- * usable is found, so the caller can keep defaults and warn.
234
- *
235
- * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
236
- * for the versions mapped here — the named-key conversion drops every entry past
237
- * the parameter count this costmodels-ts release knows, and the scriptDataHash
238
- * must cover all of them (see _languageViewCostModels).
208
+ * Parse the cost-models JSON (keys 'PlutusVN', 'plutus:vN' or 'PlutusScriptVN') into Buildooor's
209
+ * CostModels; undefined when nothing usable is found. Also (re)sets this.rawCostModelArrays with
210
+ * the unclamped chain arrays, which the scriptDataHash must cover (see _languageViewCostModels).
239
211
  */
240
212
  private _mapCostModels;
241
- /**
242
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
243
- */
213
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
244
214
  private _mapOdatanoUtxoToLedgerUtxo;
245
- /**
246
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
247
- */
215
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
248
216
  private _mapMultiAssetUtxoToLedgerUtxo;
249
- /**
250
- * Map ODATANO metadata JSON to Ledger TxMetadata
251
- */
217
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
252
218
  private _mapOdatanoMetadataToLedgerMetadata;
253
219
  /**
254
- * Recursively convert JSON value to TxMetadatum.
255
- *
256
- * Ledger rules enforced here (instead of a node-side rejection or a raw 500):
257
- * - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
258
- * - text and byte values are limited to 64 BYTES per metadatum — longer values
259
- * are chunked into a list of ≤64-byte pieces (the established convention,
260
- * e.g. CIP-25 long strings)
261
- * - strings prefixed with "0x" (even hex length) become byte metadata
262
- * - map keys are not auto-chunked (readers match on the literal key) — over-long
263
- * keys are rejected with a clear 400
264
- *
265
- * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
266
- * "1155.result" or "721.files[0].src") — named in every rejection
267
- * so the consumer can locate the offending value.
220
+ * Recursively convert a JSON value to TxMetadatum, enforcing ledger rules: integers only, text/bytes
221
+ * over 64 BYTES chunked into a list, "0x..." strings become bytes, over-long map keys rejected.
222
+ * @param path label-rooted position of `value` (e.g. "721.files[0].src"), named in every rejection
268
223
  */
269
224
  private _jsonToTxMetadatum;
270
225
  }