@odatano/core 2.0.0-rc.41 → 2.0.0-rc.43

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 (47) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +47 -0
  2. package/@cds-models/CardanoIndexerService/index.js +7 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +44 -0
  4. package/@cds-models/CardanoODataService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +3 -0
  6. package/@cds-models/CardanoTransactionService/index.d.ts +3 -0
  7. package/@cds-models/index.d.ts +3 -0
  8. package/@cds-models/odatano/cardano/index.d.ts +33 -0
  9. package/@cds-models/odatano/cardano/index.js +3 -0
  10. package/README.md +195 -195
  11. package/db/schema.cds +27 -0
  12. package/db/types.cds +421 -409
  13. package/package.json +1 -1
  14. package/srv/blockchain/backends/blockfrost-backend.js +1 -0
  15. package/srv/blockchain/backends/koios-backend.js +19 -0
  16. package/srv/blockchain/backends/ogmios-backend.js +16 -12
  17. package/srv/blockchain/cardano-indexer.js +26 -9
  18. package/srv/blockchain/crawler/credential-backfill.d.ts +37 -0
  19. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  20. package/srv/blockchain/crawler/transaction-backfill.d.ts +3 -2
  21. package/srv/blockchain/crawler/transaction-backfill.js +14 -4
  22. package/srv/blockchain/crawler/utxo-set-import.d.ts +20 -1
  23. package/srv/blockchain/crawler/utxo-set-import.js +71 -3
  24. package/srv/blockchain/ledger-state.d.ts +6 -1
  25. package/srv/blockchain/ledger-state.js +3 -0
  26. package/srv/blockchain/stored-chain.js +9 -1
  27. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +17 -0
  28. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +74 -0
  29. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +10 -1
  30. package/srv/blockchain/transaction-building/buildooor-tx.js +55 -19
  31. package/srv/blockchain/transaction-rows.d.ts +1 -1
  32. package/srv/blockchain/transaction-rows.js +2 -1
  33. package/srv/cardano-indexer-service.cds +30 -3
  34. package/srv/cardano-indexer-service.js +48 -3
  35. package/srv/cardano-service.cds +344 -332
  36. package/srv/cardano-service.js +9 -0
  37. package/srv/cbor/index.d.ts +1 -0
  38. package/srv/cbor/index.js +4 -1
  39. package/srv/cbor/plutus-data-json.d.ts +24 -0
  40. package/srv/cbor/plutus-data-json.js +32 -0
  41. package/srv/utils/agent-grants.js +1 -1
  42. package/srv/utils/db-indexes.js +5 -0
  43. package/srv/utils/mappers.d.ts +6 -2
  44. package/srv/utils/mappers.js +20 -0
  45. package/srv/utils/reference-script.d.ts +37 -0
  46. package/srv/utils/reference-script.js +95 -0
  47. package/srv/utils/types.d.ts +19 -0
@@ -1,5 +1,5 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
- import type { Amount, BlockData, Transaction as ProviderTransaction } from '../utils/types';
2
+ import type { Amount, BlockData, Transaction as ProviderTransaction, ReferenceScriptType } from '../utils/types';
3
3
  /**
4
4
  * Crawler-fed ledger state (`crawler.utxoSet`): UTxO set + per-address/per-stake-key running
5
5
  * sums in non-temporal tables. Only blocks AFTER the imported anchor are applied; a reorg past
@@ -32,6 +32,9 @@ export interface LedgerUtxoRow {
32
32
  utxo_dataHash: string | null;
33
33
  utxo_inlineDatum: string | null;
34
34
  utxo_referenceScriptHash: string | null;
35
+ utxo_referenceScriptSize: number | null;
36
+ utxo_referenceScriptType: ReferenceScriptType | null;
37
+ utxo_paymentCredential: string | null;
35
38
  hasAssets: boolean;
36
39
  }
37
40
  export interface LedgerUtxoAssetRow {
@@ -52,6 +55,8 @@ export interface LedgerOutputLike {
52
55
  dataHash?: string | null;
53
56
  inlineDatum?: string | null;
54
57
  referenceScriptHash?: string | null;
58
+ referenceScriptSize?: number | null;
59
+ referenceScriptType?: ReferenceScriptType | null;
55
60
  }
56
61
  /** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
57
62
  export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: number | null): {
@@ -61,6 +61,9 @@ function buildLedgerUtxoRows(o, createdSlot) {
61
61
  utxo_dataHash: o.dataHash || null,
62
62
  utxo_inlineDatum: o.inlineDatum || null,
63
63
  utxo_referenceScriptHash: o.referenceScriptHash || null,
64
+ utxo_referenceScriptSize: o.referenceScriptSize ?? null,
65
+ utxo_referenceScriptType: o.referenceScriptType ?? null,
66
+ utxo_paymentCredential: decoded.paymentCredential,
64
67
  hasAssets: assets.length > 0,
65
68
  },
66
69
  assets,
@@ -133,7 +133,7 @@ async function assembleTransactions(db, rows) {
133
133
  }
134
134
  return out;
135
135
  };
136
- const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers] = await Promise.all([
136
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers, datums] = await Promise.all([
137
137
  fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
138
138
  fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
139
139
  fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
@@ -143,6 +143,7 @@ async function assembleTransactions(db, rows) {
143
143
  fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
144
144
  fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
145
145
  fetchIn(cardano_1.TransactionRedeemers, 'tx_hash', hashes),
146
+ fetchIn(cardano_1.TransactionDatums, 'tx_hash', hashes),
146
147
  ]);
147
148
  const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
148
149
  const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
@@ -153,6 +154,7 @@ async function assembleTransactions(db, rows) {
153
154
  const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
154
155
  const mintsByHash = groupBy(mints, r => str(r.txHash));
155
156
  const redeemersByHash = groupBy(redeemers, r => str(r.tx_hash));
157
+ const datumsByHash = groupBy(datums, r => str(r.tx_hash));
156
158
  return rows.map((t) => {
157
159
  const seq = str(t.txSeq);
158
160
  const hash = str(t.hash);
@@ -167,6 +169,8 @@ async function assembleTransactions(db, rows) {
167
169
  dataHash: i.utxoData_dataHash ?? null,
168
170
  inlineDatum: i.utxoData_inlineDatum ?? null,
169
171
  referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
172
+ referenceScriptSize: numOrNull(i.utxoData_referenceScriptSize),
173
+ referenceScriptType: i.utxoData_referenceScriptType ?? null,
170
174
  isCollateral: Boolean(i.isCollateral),
171
175
  isReference: Boolean(i.isReference),
172
176
  }));
@@ -183,11 +187,14 @@ async function assembleTransactions(db, rows) {
183
187
  inlineDatum: o.utxo_inlineDatum ?? null,
184
188
  isCollateral: spendsCollaterals,
185
189
  referenceScriptHash: o.utxo_referenceScriptHash ?? null,
190
+ referenceScriptSize: numOrNull(o.utxo_referenceScriptSize),
191
+ referenceScriptType: o.utxo_referenceScriptType ?? null,
186
192
  }));
187
193
  const certs = certsByHash.get(hash);
188
194
  const withdrawn = withdrawalsByHash.get(hash);
189
195
  const minted = mintsByHash.get(hash);
190
196
  const redeemed = redeemersByHash.get(hash);
197
+ const witnessDatums = datumsByHash.get(hash);
191
198
  return {
192
199
  hash,
193
200
  blockHash: str(t.blockHash),
@@ -228,6 +235,7 @@ async function assembleTransactions(db, rows) {
228
235
  outputIndex: numOrNull(r.spentOutputIndex),
229
236
  policyId: r.policyId ?? null,
230
237
  })),
238
+ datums: witnessDatums?.map((d) => ({ hash: str(d.dataHash), cbor: str(d.datum) })),
231
239
  };
232
240
  });
233
241
  }
@@ -0,0 +1,17 @@
1
+ import { Tx } from '@harmoniclabs/cardano-ledger-ts';
2
+ /** Conway reference-script fee: the price per byte rises by 1.2 for every tier of this many bytes. */
3
+ export declare const REF_SCRIPT_TIER_BYTES = 25600n;
4
+ export interface Rational {
5
+ num: bigint;
6
+ den: bigint;
7
+ }
8
+ /**
9
+ * Reference-script fee as the ledger computes it: `totalBytes` priced tier by tier, each tier
10
+ * 1.2 times the previous, exact rationals, floored once at the end.
11
+ */
12
+ export declare function tierRefScriptFee(totalBytes: bigint, pricePerByte: Rational): bigint;
13
+ /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
14
+ export declare function refScriptBytesOf(tx: Tx): bigint;
15
+ /** Replace `TxBuilder.prototype.calcMinFee` once per process. */
16
+ export declare function installReferenceScriptFeePatch(): void;
17
+ //# sourceMappingURL=buildooor-fee-patch.d.ts.map
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REF_SCRIPT_TIER_BYTES = void 0;
4
+ exports.tierRefScriptFee = tierRefScriptFee;
5
+ exports.refScriptBytesOf = refScriptBytesOf;
6
+ exports.installReferenceScriptFeePatch = installReferenceScriptFeePatch;
7
+ const buildooor_1 = require("@harmoniclabs/buildooor");
8
+ const utils_1 = require("@harmoniclabs/buildooor/dist/TxBuilder/utils");
9
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
10
+ const reference_script_1 = require("../../utils/reference-script");
11
+ /** Conway reference-script fee: the price per byte rises by 1.2 for every tier of this many bytes. */
12
+ exports.REF_SCRIPT_TIER_BYTES = 25600n;
13
+ /**
14
+ * Reference-script fee as the ledger computes it: `totalBytes` priced tier by tier, each tier
15
+ * 1.2 times the previous, exact rationals, floored once at the end.
16
+ */
17
+ function tierRefScriptFee(totalBytes, pricePerByte) {
18
+ let remaining = totalBytes;
19
+ let priceNum = pricePerByte.num;
20
+ let priceDen = pricePerByte.den;
21
+ let accNum = 0n;
22
+ let accDen = 1n;
23
+ const add = (bytes) => {
24
+ accNum = accNum * priceDen + bytes * priceNum * accDen;
25
+ accDen *= priceDen;
26
+ };
27
+ while (remaining >= exports.REF_SCRIPT_TIER_BYTES) {
28
+ add(exports.REF_SCRIPT_TIER_BYTES);
29
+ priceNum *= 6n;
30
+ priceDen *= 5n;
31
+ remaining -= exports.REF_SCRIPT_TIER_BYTES;
32
+ }
33
+ add(remaining);
34
+ return accNum / accDen;
35
+ }
36
+ /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
37
+ function refScriptBytesOf(tx) {
38
+ const utxos = [...tx.body.inputs, ...(tx.body.refInputs ?? [])];
39
+ return utxos.reduce((sum, u) => sum + BigInt(u.resolved.refScript ? (0, reference_script_1.referenceScriptSize)(u.resolved.refScript) : 0), 0n);
40
+ }
41
+ function refScriptPrice(pp) {
42
+ const r = (0, cardano_ledger_ts_1.cborFromRational)(pp.minfeeRefScriptCostPerByte ?? cardano_ledger_ts_1.defaultProtocolParameters.minfeeRefScriptCostPerByte);
43
+ return { num: BigInt(r.num), den: BigInt(r.den) };
44
+ }
45
+ /**
46
+ * `TxBuilder.calcMinFee` with the ledger's reference-script rule. Buildooor 0.2.9 prices only the
47
+ * reference inputs, linearly; the ledger also counts scripts on spent inputs and prices in tiers.
48
+ * The rest (linear fee, estimated key witnesses) is Buildooor's own arithmetic.
49
+ */
50
+ function calcMinFeeWithRefScripts(tx, minimum) {
51
+ const self = this;
52
+ const pp = self.protocolParamters;
53
+ const perByte = BigInt(pp.txFeePerByte ?? cardano_ledger_ts_1.defaultProtocolParameters.txFeePerByte);
54
+ const nVkeyWits = BigInt((0, utils_1.estimateMaxSignersNeeded)(tx));
55
+ const minFee = self.calcLinearFee(tx)
56
+ + tierRefScriptFee(refScriptBytesOf(tx), refScriptPrice(pp))
57
+ // one key witness is 102 CBOR bytes plus 2 for encoding slack, plus the array header
58
+ + 104n * nVkeyWits * perByte
59
+ + BigInt(nVkeyWits < 24n ? 1 : nVkeyWits < 256n ? 2 : 4) * perByte;
60
+ if (minimum === undefined || minimum === null)
61
+ return minFee;
62
+ const min = BigInt(minimum);
63
+ return minFee < min ? min : minFee;
64
+ }
65
+ const PATCHED = Symbol.for('odatano.buildooor.refScriptFee');
66
+ /** Replace `TxBuilder.prototype.calcMinFee` once per process. */
67
+ function installReferenceScriptFeePatch() {
68
+ const proto = buildooor_1.TxBuilder.prototype;
69
+ if (proto[PATCHED])
70
+ return;
71
+ proto.calcMinFee = calcMinFeeWithRefScripts;
72
+ proto[PATCHED] = true;
73
+ }
74
+ //# sourceMappingURL=buildooor-fee-patch.js.map
@@ -34,12 +34,15 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
34
34
  */
35
35
  private _buildSimpleTransfer;
36
36
  buildUnsignedMintTransaction(req: TxBuildMintRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
37
+ private _buildMintTransaction;
37
38
  buildUnsignedPlutusSpendTransaction(req: TxBuildPlutusSpendRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
39
+ private _buildPlutusSpendTransaction;
38
40
  /**
39
41
  * Several script inputs in one transaction, each with its own redeemer (inline validator or a
40
42
  * reference-script UTxO), the outputs exactly in the given order and change after them.
41
43
  */
42
44
  buildUnsignedPlutusTransaction(req: TxBuildPlutusRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
45
+ private _buildPlutusTransaction;
43
46
  /**
44
47
  * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
45
48
  * Returns the inline datums given as CBOR, keyed by output index.
@@ -109,6 +112,11 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
109
112
  * so raw chain arrays (passed through unclamped) are substituted where available.
110
113
  */
111
114
  private _languageViewCostModels;
115
+ /**
116
+ * Run a build without the sender's reference-script UTxOs first; when that leaves the funds short
117
+ * and such UTxOs exist, build again with them in the pool (their script bytes then count in the fee).
118
+ */
119
+ private _withRefScriptFallback;
112
120
  /**
113
121
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
114
122
  * refs absent from utxos are ignored (existence is validated upstream).
@@ -179,7 +187,8 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
179
187
  private _parseReferenceScript;
180
188
  /**
181
189
  * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
182
- * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
190
+ * `scriptRef` (Koios). With the hash and size only (Blockfrost, the tables) a placeholder of
191
+ * that size stands in, so the fee counts its bytes; without the size nothing can be counted.
183
192
  */
184
193
  private _buildInputRefScript;
185
194
  /**
@@ -18,6 +18,8 @@ const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/
18
18
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
19
19
  const caller_datums_1 = require("./caller-datums");
20
20
  const const_1 = require("../../utils/const");
21
+ const buildooor_fee_patch_1 = require("./buildooor-fee-patch");
22
+ const reference_script_1 = require("../../utils/reference-script");
21
23
  const logger = cds_1.default.log('BuildooorTxBuilder');
22
24
  /**
23
25
  * Build options for script-bearing transactions. Buildooor stamps each redeemer with its
@@ -115,11 +117,13 @@ function chunkUtf8(str, maxBytes) {
115
117
  function ledgerScript(script) {
116
118
  return new cardano_ledger_ts_1.Script(script.type, script.bytes);
117
119
  }
120
+ const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
118
121
  // Hash32 inherits Hash.clone(), which returns a plain Hash; TxOut rejects that as datum when
119
122
  // Buildooor clones outputs, so a datum-hash output could never be built. Hash28 has its own clone.
120
123
  if (!Object.prototype.hasOwnProperty.call(cardano_ledger_ts_1.Hash32.prototype, 'clone')) {
121
124
  cardano_ledger_ts_1.Hash32.prototype.clone = function () { return new cardano_ledger_ts_1.Hash32(this.toString()); };
122
125
  }
126
+ (0, buildooor_fee_patch_1.installReferenceScriptFeePatch)();
123
127
  /** CardanoTxBuilder implementation on top of Buildooor. */
124
128
  class BuildooorTxBuilder {
125
129
  name = 'BuildooorTxBuilder';
@@ -167,17 +171,17 @@ class BuildooorTxBuilder {
167
171
  }
168
172
  /** Build an unsigned transfer transaction (ADA-only or with native assets). */
169
173
  buildUnsignedTransfer(req, ctx) {
170
- return this._buildSimpleTransfer(req, ctx, 'transfer');
174
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'transfer', include));
171
175
  }
172
176
  /** Build an unsigned transfer transaction with attached metadata. */
173
177
  buildUnsignedTransactionWithMetadata(req, ctx) {
174
- return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
178
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'metadata transfer', include));
175
179
  }
176
180
  /**
177
181
  * Shared non-script transfer build; assets, outputDatum and metadataJson are each
178
182
  * handled only when present in the request.
179
183
  */
180
- async _buildSimpleTransfer(req, ctx, label) {
184
+ async _buildSimpleTransfer(req, ctx, label, includeRefScriptUtxos) {
181
185
  try {
182
186
  this._ensureCurrentProtocolParameters(ctx);
183
187
  if (!ctx.utxos || ctx.utxos.length === 0) {
@@ -208,7 +212,7 @@ class BuildooorTxBuilder {
208
212
  const outputValue = recipient.value;
209
213
  const outputs = [recipient];
210
214
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
211
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
215
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
212
216
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
213
217
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
214
218
  // Coin selection on candidates only; forced inputs are prepended unconditionally
@@ -229,7 +233,10 @@ class BuildooorTxBuilder {
229
233
  (0, tx_build_helper_1.mapBuilderError)(err, undefined, undefined, 1);
230
234
  }
231
235
  }
232
- async buildUnsignedMintTransaction(req, ctx) {
236
+ buildUnsignedMintTransaction(req, ctx) {
237
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildMintTransaction(req, ctx, include));
238
+ }
239
+ async _buildMintTransaction(req, ctx, includeRefScriptUtxos) {
233
240
  // Set once the collateral partition is known: it explains insufficient-funds rejections
234
241
  // that the builder's own message cannot attribute.
235
242
  let coinSelectionContext;
@@ -251,7 +258,7 @@ class BuildooorTxBuilder {
251
258
  }
252
259
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
253
260
  // coin selection operates on the remainder only.
254
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
261
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
255
262
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
256
263
  // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
257
264
  // demand the mint itself does not cover.
@@ -322,8 +329,11 @@ class BuildooorTxBuilder {
322
329
  (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
323
330
  }
324
331
  }
325
- async buildUnsignedPlutusSpendTransaction(req, ctx) {
326
- // See buildUnsignedMintTransaction — same collateral-partition context for rejections.
332
+ buildUnsignedPlutusSpendTransaction(req, ctx) {
333
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusSpendTransaction(req, ctx, include));
334
+ }
335
+ async _buildPlutusSpendTransaction(req, ctx, includeRefScriptUtxos) {
336
+ // See _buildMintTransaction — same collateral-partition context for rejections.
327
337
  let coinSelectionContext;
328
338
  let requestedOutputs;
329
339
  try {
@@ -346,7 +356,7 @@ class BuildooorTxBuilder {
346
356
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
347
357
  // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
348
358
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
349
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
359
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
350
360
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
351
361
  // Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
352
362
  // assets the script UTxO already provides net out, so over-requesting is harmless.
@@ -455,7 +465,10 @@ class BuildooorTxBuilder {
455
465
  * Several script inputs in one transaction, each with its own redeemer (inline validator or a
456
466
  * reference-script UTxO), the outputs exactly in the given order and change after them.
457
467
  */
458
- async buildUnsignedPlutusTransaction(req, ctx) {
468
+ buildUnsignedPlutusTransaction(req, ctx) {
469
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusTransaction(req, ctx, include));
470
+ }
471
+ async _buildPlutusTransaction(req, ctx, includeRefScriptUtxos) {
459
472
  let coinSelectionContext;
460
473
  let requestedOutputs;
461
474
  try {
@@ -555,7 +568,7 @@ class BuildooorTxBuilder {
555
568
  const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
556
569
  if (scriptKeyClash)
557
570
  throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
558
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs);
571
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs, includeRefScriptUtxos);
559
572
  this._checkForeignForcedInputs(forced, req);
560
573
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
561
574
  // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
@@ -1008,15 +1021,30 @@ class BuildooorTxBuilder {
1008
1021
  return models;
1009
1022
  return { ...models, ...this.rawCostModelArrays };
1010
1023
  }
1024
+ /**
1025
+ * Run a build without the sender's reference-script UTxOs first; when that leaves the funds short
1026
+ * and such UTxOs exist, build again with them in the pool (their script bytes then count in the fee).
1027
+ */
1028
+ async _withRefScriptFallback(utxos, build) {
1029
+ try {
1030
+ return await build(false);
1031
+ }
1032
+ catch (err) {
1033
+ if (!(err instanceof errors_1.InsufficientFundsError) || !(utxos ?? []).some(hasRefScript))
1034
+ throw err;
1035
+ logger.info('Funds short without the reference-script UTxOs — building again with them in the coin-selection pool');
1036
+ return build(true);
1037
+ }
1038
+ }
1011
1039
  /**
1012
1040
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
1013
1041
  * refs absent from utxos are ignored (existence is validated upstream).
1014
1042
  */
1015
- _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs) {
1016
- const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
1043
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs, includeRefScriptUtxos = false) {
1044
+ const excluded = (u) => !includeRefScriptUtxos && hasRefScript(u);
1017
1045
  const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
1018
1046
  const protectedKeys = new Set((protectInputs ?? []).map(key));
1019
- if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(hasRefScript)) {
1047
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(excluded)) {
1020
1048
  return { forced: [], rest: utxos };
1021
1049
  }
1022
1050
  const forcedKeys = new Set((forceInputs ?? []).map(key));
@@ -1032,9 +1060,9 @@ class BuildooorTxBuilder {
1032
1060
  for (const u of utxos) {
1033
1061
  if (forcedKeys.has(key(u)))
1034
1062
  forced.push(u);
1035
- // reference inputs, protected UTxOs and UTxOs carrying a reference script stay out of coin
1036
- // selection and collateral; a deployed script is spent only when forced
1037
- else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !hasRefScript(u))
1063
+ // reference inputs and protected UTxOs stay out of coin selection; UTxOs carrying a reference
1064
+ // script too, until the other funds prove short (then their bytes are priced into the fee)
1065
+ else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !excluded(u))
1038
1066
  rest.push(u);
1039
1067
  }
1040
1068
  return { forced, rest };
@@ -1339,13 +1367,18 @@ class BuildooorTxBuilder {
1339
1367
  }
1340
1368
  /**
1341
1369
  * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
1342
- * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
1370
+ * `scriptRef` (Koios). With the hash and size only (Blockfrost, the tables) a placeholder of
1371
+ * that size stands in, so the fee counts its bytes; without the size nothing can be counted.
1343
1372
  */
1344
1373
  _buildInputRefScript(utxo) {
1345
1374
  const cbor = utxo.scriptRefCbor ?? (utxo.scriptRef && utxo.scriptRef.length > 56 ? utxo.scriptRef : undefined);
1346
1375
  if (!cbor) {
1376
+ if (utxo.scriptRef && utxo.scriptRefSize) {
1377
+ logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash and size only — fee counts ${utxo.scriptRefSize} bytes, local Plutus eval will not see the script`);
1378
+ return (0, reference_script_1.sizePlaceholderScript)(utxo.scriptRefSize);
1379
+ }
1347
1380
  if (utxo.scriptRef)
1348
- logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
1381
+ logger.warn(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — its reference-script fee cannot be counted, the node may reject the transaction as underpaid`);
1349
1382
  return undefined;
1350
1383
  }
1351
1384
  try {
@@ -1464,6 +1497,9 @@ class BuildooorTxBuilder {
1464
1497
  stakePoolTargetNum: toUInt(pp.nOpt) ?? d.stakePoolTargetNum,
1465
1498
  collateralPercentage: toUInt(pp.collateralPercent) ?? d.collateralPercentage,
1466
1499
  maxCollateralInputs: toUInt(pp.maxCollateralInputs) ?? d.maxCollateralInputs,
1500
+ minfeeRefScriptCostPerByte: pp.minFeeRefScriptCostPerByte != null && Number(pp.minFeeRefScriptCostPerByte) > 0
1501
+ ? Number(pp.minFeeRefScriptCostPerByte)
1502
+ : d.minfeeRefScriptCostPerByte,
1467
1503
  };
1468
1504
  const maxTxExMem = toUInt(pp.maxTxExMem);
1469
1505
  const maxTxExSteps = toUInt(pp.maxTxExSteps);
@@ -7,6 +7,6 @@ export interface TxKey {
7
7
  export declare const seqKey: (txSeq: number | string) => string;
8
8
  /** Hash and txSeq of the given transactions that are indexed. */
9
9
  export declare function readTxKeys(tx: CapTransaction, hashes: string[]): Promise<TxKey[]>;
10
- /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal and redeemer rows. */
10
+ /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal, redeemer and datum rows. */
11
11
  export declare function deleteTransactionRows(tx: CapTransaction, keys: TxKey[]): Promise<void>;
12
12
  //# sourceMappingURL=transaction-rows.d.ts.map
@@ -22,7 +22,7 @@ async function readTxKeys(tx, hashes) {
22
22
  }
23
23
  return keys;
24
24
  }
25
- /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal and redeemer rows. */
25
+ /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal, redeemer and datum rows. */
26
26
  async function deleteTransactionRows(tx, keys) {
27
27
  for (const keyChunk of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
28
28
  const hashes = keyChunk.map(k => k.hash);
@@ -37,6 +37,7 @@ async function deleteTransactionRows(tx, keys) {
37
37
  await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: hashes } }));
38
38
  await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: hashes } }));
39
39
  await tx.run(DELETE.from(cardano_1.TransactionRedeemers).where({ tx_hash: { in: hashes } }));
40
+ await tx.run(DELETE.from(cardano_1.TransactionDatums).where({ tx_hash: { in: hashes } }));
40
41
  await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: hashes } }));
41
42
  }
42
43
  }
@@ -54,8 +54,10 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
54
54
  utxoSet : UtxoSetStatus;
55
55
  // one-off certificate/withdrawal backfill over already crawled blocks (this process)
56
56
  certificateBackfill : CertificateBackfillStatus;
57
- // one-off input/redeemer backfill over already crawled blocks (this process)
57
+ // one-off input/redeemer/datum backfill over already crawled blocks (this process)
58
58
  transactionBackfill : TransactionBackfillStatus;
59
+ // one-off payment-credential fill of UTxO-shaped rows (this process)
60
+ credentialBackfill : CredentialBackfillStatus;
59
61
  // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
60
62
  epochSnapshots : EpochSnapshotStatus;
61
63
  }
@@ -96,6 +98,7 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
96
98
  transactions : Integer64;
97
99
  inputs : Integer64; // input rows that got at least one field
98
100
  redeemers : Integer64;
101
+ datums : Integer64;
99
102
  rewritten : Integer64; // transactions whose stored rows differed in order or extent from the ledger view, now rewritten
100
103
  skipped : Integer64; // transactions whose stored inputs differ from the stream
101
104
  startedAt : Timestamp;
@@ -103,6 +106,25 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
103
106
  error : String;
104
107
  }
105
108
 
109
+ @title : 'Credential Backfill Status'
110
+ @description: 'Progress of the payment-credential fill started with backfillPaymentCredentials; process-local, none after a restart'
111
+ type CredentialBackfillStatus {
112
+ status : String; // none | running | done | failed
113
+ table : String; // table being walked: TransactionOutputs | TransactionInputs | LedgerUTxOs; null when finished
114
+ outputs : Integer64; // rows that received a credential
115
+ inputs : Integer64;
116
+ ledgerUtxos : Integer64;
117
+ startedAt : Timestamp;
118
+ finishedAt : Timestamp;
119
+ error : String;
120
+ }
121
+
122
+ @title : 'Backfill Result'
123
+ type BackfillResult {
124
+ accepted : Boolean;
125
+ message : String;
126
+ }
127
+
106
128
  @title : 'Certificate Backfill Result'
107
129
  type CertificateBackfillResult {
108
130
  accepted : Boolean;
@@ -185,7 +207,7 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
185
207
  action resumeCrawler() returns Boolean;
186
208
 
187
209
  @title : 'Import UTxO Set'
188
- @description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. source=aggregates rebuilds only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an earlier import left, e.g. after its aggregate phase failed; a cursor past the anchor is set back to it. Runs in the background; progress via getStatus().utxoSet.'
210
+ @description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. source=aggregates rebuilds only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an earlier import left, e.g. after its aggregate phase failed; a cursor past the anchor is set back to it. source=scripts fills the reference-script columns (utxo_referenceScriptHash, utxo_referenceScriptSize, utxo_referenceScriptType) of rows an earlier import left empty: from the same dump (filePath), or without filePath from Ogmios for the unspent rows that hold a hash but no size; the set stays active. Runs in the background; progress via getStatus().utxoSet and the log.'
189
211
  @requires : 'Admin'
190
212
  action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
191
213
 
@@ -195,7 +217,12 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
195
217
  action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
196
218
 
197
219
  @title : 'Backfill Transactions'
198
- @description: 'Complete transactions the crawl already holds from a second chain-sync stream (Ogmios): input outpoints, the spent output datum and reference-script hash, missing input addresses, and TransactionRedeemers. Fills empty fields only; a transaction whose stored inputs differ from the stream is skipped. fromSlot defaults to the crawl start, toSlot to the cursor; the crawler may keep running. Runs in the background; progress via getStatus().transactionBackfill.'
220
+ @description: 'Complete transactions the crawl already holds from a second chain-sync stream (Ogmios): input outpoints, the spent output datum and reference-script hash, missing input addresses, TransactionRedeemers and TransactionDatums. Fills empty fields only; a transaction whose stored inputs differ from the stream is skipped. fromSlot defaults to the crawl start, toSlot to the cursor; the crawler may keep running. Runs in the background; progress via getStatus().transactionBackfill.'
199
221
  @requires : 'Admin'
200
222
  action backfillTransactions(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
223
+
224
+ @title : 'Backfill Payment Credentials'
225
+ @description: 'Fill utxo.paymentCredential on TransactionOutputs, TransactionInputs and LedgerUTxOs rows written before the column existed, decoded from the stored address. Walks each table once in key order; rows that carry a credential are left alone, so a second run is a no-op. No backend call; the crawler may keep running. Runs in the background; progress via getStatus().credentialBackfill.'
226
+ @requires : 'Admin'
227
+ action backfillPaymentCredentials() returns BackfillResult;
201
228
  }
@@ -11,6 +11,7 @@ const sync_state_1 = require("./blockchain/crawler/sync-state");
11
11
  const utxo_set_import_1 = require("./blockchain/crawler/utxo-set-import");
12
12
  const certificate_backfill_1 = require("./blockchain/crawler/certificate-backfill");
13
13
  const transaction_backfill_1 = require("./blockchain/crawler/transaction-backfill");
14
+ const credential_backfill_1 = require("./blockchain/crawler/credential-backfill");
14
15
  const validators_1 = require("./utils/validators");
15
16
  const server_1 = require("./server");
16
17
  const liveness_1 = require("./utils/liveness");
@@ -27,9 +28,12 @@ let certificateBackfill = {
27
28
  };
28
29
  let transactionBackfillStarting = false;
29
30
  let transactionBackfill = {
30
- status: 'none', fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0,
31
+ status: 'none', fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0,
31
32
  startedAt: null, finishedAt: null, error: null,
32
33
  };
34
+ let credentialBackfill = {
35
+ status: 'none', table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, startedAt: null, finishedAt: null, error: null,
36
+ };
33
37
  /** Slot range of a backfill: defaults to crawl start .. cursor, never past the cursor. */
34
38
  async function backfillRange(db, data) {
35
39
  const cursor = await (0, sync_state_1.readCursor)(db);
@@ -125,12 +129,14 @@ module.exports = (srv) => {
125
129
  transactions: transactionBackfill.transactions,
126
130
  inputs: transactionBackfill.inputs,
127
131
  redeemers: transactionBackfill.redeemers,
132
+ datums: transactionBackfill.datums,
128
133
  rewritten: transactionBackfill.rewritten,
129
134
  skipped: transactionBackfill.skipped,
130
135
  startedAt: transactionBackfill.startedAt,
131
136
  finishedAt: transactionBackfill.finishedAt,
132
137
  error: transactionBackfill.error,
133
138
  },
139
+ credentialBackfill: { ...credentialBackfill },
134
140
  epochSnapshots: {
135
141
  enabled: epochSnapshotsConfigured(),
136
142
  source: epochSnapshotSource(),
@@ -204,7 +210,7 @@ module.exports = (srv) => {
204
210
  return await (0, backend_request_handler_1.handleRequest)(req, async (db) => {
205
211
  const { fromSlot, toSlot } = await backfillRange(db, data);
206
212
  transactionBackfill = {
207
- status: 'running', fromSlot, toSlot, atSlot: fromSlot, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0,
213
+ status: 'running', fromSlot, toSlot, atSlot: fromSlot, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0,
208
214
  startedAt: new Date().toISOString(), finishedAt: null, error: null,
209
215
  };
210
216
  void (0, transaction_backfill_1.backfillTransactions)({
@@ -233,6 +239,23 @@ module.exports = (srv) => {
233
239
  transactionBackfillStarting = false;
234
240
  }
235
241
  });
242
+ // backfillPaymentCredentials — walks the UTxO-shaped tables once and fills the credential
243
+ // from the stored address. No backend; runs detached, progress via getStatus().credentialBackfill.
244
+ srv.on('backfillPaymentCredentials', async (req) => {
245
+ if (credentialBackfill.status === 'running')
246
+ return (0, errors_1.rejectInvalid)(req, 'backfillPaymentCredentials', 'A payment-credential backfill is already running');
247
+ credentialBackfill = { status: 'running', table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
248
+ void (0, credential_backfill_1.backfillUtxoCredentials)({
249
+ onProgress: (p) => { Object.assign(credentialBackfill, p); },
250
+ })
251
+ .then((r) => { Object.assign(credentialBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
252
+ .catch((err) => {
253
+ const message = err instanceof Error ? err.message : String(err);
254
+ Object.assign(credentialBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
255
+ logger.error(`Payment-credential backfill failed: ${message}`);
256
+ });
257
+ return { accepted: true, message: 'Payment-credential backfill started; poll getStatus().credentialBackfill.' };
258
+ });
236
259
  // importUtxoSet — one-off snapshot import that anchors crawler.utxoSet. Validates, then
237
260
  // runs detached; progress via getStatus().utxoSet.
238
261
  srv.on('importUtxoSet', async (req) => {
@@ -259,9 +282,31 @@ module.exports = (srv) => {
259
282
  };
260
283
  });
261
284
  }
285
+ if (data.source === 'scripts') {
286
+ if ((0, crawler_1.isCrawlerRunning)())
287
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process — pauseCrawler first');
288
+ if (utxoSetImportInFlight)
289
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
290
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
291
+ const cursor = await (0, sync_state_1.readCursor)(db);
292
+ const { anchorSlot, anchorHash } = cursor?.utxoSet ?? {};
293
+ if (anchorSlot == null || !anchorHash)
294
+ throw new errors_1.TransactionValidationError('No imported UTxO set to fill — run importUtxoSet first.');
295
+ utxoSetImportInFlight = (0, utxo_set_import_1.refreshUtxoSetReferenceScripts)({ filePath: data.filePath, client: (0, server_1.getCardanoClient)() })
296
+ .then((r) => logger.info(`UTxO set reference scripts filled: ${r.updated} of ${r.candidates} rows`))
297
+ .catch((err) => logger.error(`UTxO set reference-script fill failed: ${err instanceof Error ? err.message : String(err)}`))
298
+ .finally(() => { utxoSetImportInFlight = null; });
299
+ return {
300
+ accepted: true,
301
+ anchorSlot: String(anchorSlot),
302
+ anchorHash,
303
+ message: `Reference-script columns of the UTxO set are being filled (${data.filePath ? 'from the dump' : 'from the node'}); watch the log, then resumeCrawler.`,
304
+ };
305
+ });
306
+ }
262
307
  const source = data.source === 'file' || data.source === 'ogmios' ? data.source : null;
263
308
  if (!source)
264
- return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'source must be "ogmios", "file" or "aggregates"', 'source');
309
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'source must be "ogmios", "file", "aggregates" or "scripts"', 'source');
265
310
  if (source === 'file' && !data.filePath)
266
311
  return (0, errors_1.rejectMissing)(req, 'importUtxoSet', 'filePath');
267
312
  const anchorGiven = data.anchorSlot != null || !!data.anchorHash;