@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.41",
3
+ "version": "2.0.0-rc.43",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -369,6 +369,7 @@ class BlockfrostBackend {
369
369
  collateralPercent: protocolParams.collateral_percent,
370
370
  maxCollateralInputs: protocolParams.max_collateral_inputs,
371
371
  coinsPerUtxoSize: protocolParams.coins_per_utxo_size,
372
+ minFeeRefScriptCostPerByte: protocolParams.min_fee_ref_script_cost_per_byte ?? null,
372
373
  maxBlockHeaderSize: protocolParams.max_block_header_size,
373
374
  maxTxSize: protocolParams.max_tx_size,
374
375
  keyDeposit: protocolParams.key_deposit,
@@ -13,6 +13,7 @@ const mappers_1 = require("../../utils/mappers");
13
13
  const const_1 = require("../../utils/const");
14
14
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
15
15
  const logger = cds_1.default.log('KoiosBackend');
16
+ const reference_script_1 = require("../../utils/reference-script");
16
17
  /** Bounded retries for instance-specific PostgREST server errors (42703, 57014, …). */
17
18
  const PG_SERVER_ERROR_MAX_RETRIES = 2;
18
19
  const PG_SERVER_ERROR_RETRY_DELAY_MS = 300;
@@ -42,6 +43,14 @@ function koiosRefScriptHash(ref) {
42
43
  const obj = ref;
43
44
  return obj.hash || null;
44
45
  }
46
+ /** Size and type of a Koios `reference_script` object; both null for the bare-hash form. */
47
+ function koiosRefScriptMeta(ref) {
48
+ if (!ref || typeof ref !== 'object')
49
+ return { size: null, type: null };
50
+ const obj = ref;
51
+ const size = Number(obj.size);
52
+ return { size: Number.isInteger(size) && size > 0 ? size : null, type: (0, reference_script_1.normalizeScriptType)(obj.type) };
53
+ }
45
54
  /** Sort Koios /address_txs rows newest-first — Koios gives no ordering guarantee. */
46
55
  function sortAddressTxsDesc(rows) {
47
56
  return [...rows].sort((a, b) => Number(b.block_height ?? b.block_time ?? 0) - Number(a.block_height ?? a.block_time ?? 0));
@@ -307,6 +316,8 @@ class KoiosBackend {
307
316
  amount: amount,
308
317
  datumHash: utxo.datum_hash || null,
309
318
  scriptRef: koiosRefScriptBytes(utxo.reference_script),
319
+ scriptRefSize: koiosRefScriptMeta(utxo.reference_script).size,
320
+ scriptRefType: koiosRefScriptMeta(utxo.reference_script).type,
310
321
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
311
322
  };
312
323
  });
@@ -341,6 +352,8 @@ class KoiosBackend {
341
352
  amount: amount,
342
353
  datumHash: utxo.datum_hash || null,
343
354
  scriptRef: koiosRefScriptBytes(utxo.reference_script),
355
+ scriptRefSize: koiosRefScriptMeta(utxo.reference_script).size,
356
+ scriptRefType: koiosRefScriptMeta(utxo.reference_script).type,
344
357
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
345
358
  };
346
359
  });
@@ -727,6 +740,8 @@ class KoiosBackend {
727
740
  collateralPercent: data.collateralPercentage,
728
741
  maxCollateralInputs: data.maxCollateralInputs,
729
742
  coinsPerUtxoSize: data.utxoCostPerByte.toString(),
743
+ // cardano-cli spelling, as /cli_protocol_params publishes it
744
+ minFeeRefScriptCostPerByte: data.minFeeRefScriptCostPerByte ?? null,
730
745
  // --- Housekeeping ---
731
746
  fetchedAt: new Date().toISOString(),
732
747
  source: this.name
@@ -1131,6 +1146,8 @@ function mapKoiosInput(input, flags = {}) {
1131
1146
  dataHash: input.datum_hash || null,
1132
1147
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1133
1148
  referenceScriptHash: koiosRefScriptHash(input.reference_script),
1149
+ referenceScriptSize: koiosRefScriptMeta(input.reference_script).size,
1150
+ referenceScriptType: koiosRefScriptMeta(input.reference_script).type,
1134
1151
  ...flags,
1135
1152
  };
1136
1153
  }
@@ -1144,6 +1161,8 @@ function mapKoiosOutput(txHash, output, isCollateral) {
1144
1161
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1145
1162
  isCollateral,
1146
1163
  referenceScriptHash: koiosRefScriptHash(output.reference_script),
1164
+ referenceScriptSize: koiosRefScriptMeta(output.reference_script).size,
1165
+ referenceScriptType: koiosRefScriptMeta(output.reference_script).type,
1147
1166
  };
1148
1167
  }
1149
1168
  /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
@@ -16,6 +16,7 @@ const node_http_1 = __importDefault(require("node:http"));
16
16
  const client_1 = require("@cardano-ogmios/client");
17
17
  const bech32_1 = require("bech32");
18
18
  const crypto_1 = require("@harmoniclabs/crypto");
19
+ const reference_script_1 = require("../../utils/reference-script");
19
20
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
20
21
  const errors_1 = require("../../utils/errors");
21
22
  const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
@@ -37,20 +38,18 @@ function parseOgmiosRatio(ratio) {
37
38
  const n = Number(ratio);
38
39
  return Number.isFinite(n) ? n : 0;
39
40
  }
40
- const SCRIPT_LANGUAGE_TAG = { native: 0, 'plutus:v1': 1, 'plutus:v2': 2, 'plutus:v3': 3 };
41
41
  /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
42
42
  function ogmiosScriptHash(script) {
43
- const s = script;
44
- const tag = s?.language === undefined ? undefined : SCRIPT_LANGUAGE_TAG[s.language];
45
- if (tag === undefined || typeof s?.cbor !== 'string' || s.cbor.length === 0)
46
- return null;
47
- const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
48
- return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
43
+ return (0, reference_script_1.ogmiosReferenceScript)(script)?.hash ?? null;
49
44
  }
50
45
  /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
51
46
  function ogmiosPlutusScriptCbor(script) {
52
- const s = script;
53
- return s?.language?.startsWith('plutus:') && typeof s.cbor === 'string' && s.cbor.length > 0 ? s.cbor : null;
47
+ return (0, reference_script_1.ogmiosReferenceScript)(script)?.cbor ?? null;
48
+ }
49
+ /** Reference-script columns of an output or UTxO from an Ogmios `script`. */
50
+ function ogmiosReferenceScriptFields(script) {
51
+ const ref = (0, reference_script_1.ogmiosReferenceScript)(script);
52
+ return { referenceScriptHash: ref?.hash ?? null, referenceScriptSize: ref?.size ?? null, referenceScriptType: ref?.type ?? null };
54
53
  }
55
54
  /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
56
55
  function issuerKeyToPoolId(verificationKeyHex) {
@@ -557,6 +556,7 @@ class OgmiosBackend {
557
556
  }
558
557
  /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
559
558
  mapOgmiosUtxo(u, fallbackAddress = '') {
559
+ const ref = (0, reference_script_1.ogmiosReferenceScript)(u.script);
560
560
  return {
561
561
  txHash: u.transaction?.id || '',
562
562
  outputIndex: u.index || 0,
@@ -566,8 +566,10 @@ class OgmiosBackend {
566
566
  datumHash: u.datumHash,
567
567
  // Ogmios delivers the inline datum as CBOR hex in `datum`
568
568
  inlineDatum: typeof u.datum === 'string' ? u.datum : null,
569
- scriptRef: ogmiosScriptHash(u.script) ?? undefined,
570
- scriptRefCbor: ogmiosPlutusScriptCbor(u.script),
569
+ scriptRef: ref?.hash,
570
+ scriptRefCbor: ref?.cbor ?? null,
571
+ scriptRefSize: ref?.size ?? null,
572
+ scriptRefType: ref?.type ?? null,
571
573
  };
572
574
  }
573
575
  /**
@@ -794,6 +796,7 @@ class OgmiosBackend {
794
796
  collateralPercent: params.collateralPercentage || 0,
795
797
  maxCollateralInputs: params.maxCollateralInputs || 0,
796
798
  coinsPerUtxoSize: params.minUtxoDepositCoefficient?.toString() || '0',
799
+ minFeeRefScriptCostPerByte: params.minFeeReferenceScripts?.base ?? null,
797
800
  maxBlockHeaderSize: params.maxBlockHeaderSize?.bytes || 0,
798
801
  maxTxSize: params.maxTransactionSize?.bytes || 0,
799
802
  keyDeposit: params.stakeCredentialDeposit?.ada?.lovelace?.toString() || '0',
@@ -1173,7 +1176,7 @@ class OgmiosBackend {
1173
1176
  dataHash: output.datumHash ?? null,
1174
1177
  inlineDatum: output.datum ?? null,
1175
1178
  isCollateral,
1176
- referenceScriptHash: ogmiosScriptHash(output.script),
1179
+ ...ogmiosReferenceScriptFields(output.script),
1177
1180
  });
1178
1181
  const outputs = spendsCollaterals
1179
1182
  ? (tx.collateralReturn
@@ -1222,6 +1225,7 @@ class OgmiosBackend {
1222
1225
  amount: (value?.ada?.lovelace ?? 0).toString(),
1223
1226
  })),
1224
1227
  redeemers: mapOgmiosRedeemers(tx),
1228
+ datums: Object.entries(tx.datums ?? {}).map(([hash, cbor]) => ({ hash, cbor })),
1225
1229
  });
1226
1230
  }
1227
1231
  /**
@@ -21,11 +21,23 @@ const epoch_slots_1 = require("../utils/epoch-slots");
21
21
  const const_1 = require("../utils/const");
22
22
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
23
23
  const logger = cds_1.default.log('CardanoIndexer');
24
- /** Datum hash, inline datum and reference-script hash of the spent output onto its input. */
25
- function copyUtxoData(input, dataHash, inlineDatum, referenceScriptHash) {
26
- input.dataHash = input.dataHash ?? dataHash ?? null;
27
- input.inlineDatum = input.inlineDatum ?? inlineDatum ?? null;
28
- input.referenceScriptHash = input.referenceScriptHash ?? referenceScriptHash ?? null;
24
+ /** Datum hash, inline datum and reference script of the spent output onto its input. */
25
+ function copyUtxoData(input, out) {
26
+ input.dataHash = input.dataHash ?? out.utxo_dataHash ?? null;
27
+ input.inlineDatum = input.inlineDatum ?? out.utxo_inlineDatum ?? null;
28
+ input.referenceScriptHash = input.referenceScriptHash ?? out.utxo_referenceScriptHash ?? null;
29
+ input.referenceScriptSize = input.referenceScriptSize ?? out.utxo_referenceScriptSize ?? null;
30
+ input.referenceScriptType = input.referenceScriptType ?? out.utxo_referenceScriptType ?? null;
31
+ }
32
+ /** A provider output in the stored-column shape, for copyUtxoData. */
33
+ function utxoDataOf(o) {
34
+ return {
35
+ utxo_dataHash: o.dataHash,
36
+ utxo_inlineDatum: o.inlineDatum,
37
+ utxo_referenceScriptHash: o.referenceScriptHash,
38
+ utxo_referenceScriptSize: o.referenceScriptSize,
39
+ utxo_referenceScriptType: o.referenceScriptType,
40
+ };
29
41
  }
30
42
  function lovelaceSum(value) {
31
43
  if (value === null || value === undefined || value === '')
@@ -752,6 +764,8 @@ class CardanoIndexer {
752
764
  datumHash: u.utxo_dataHash ?? undefined,
753
765
  inlineDatum: u.utxo_inlineDatum ?? null,
754
766
  scriptRef: u.utxo_referenceScriptHash ?? undefined,
767
+ scriptRefSize: u.utxo_referenceScriptSize == null ? null : Number(u.utxo_referenceScriptSize),
768
+ scriptRefType: u.utxo_referenceScriptType ?? null,
755
769
  });
756
770
  }
757
771
  }
@@ -1018,8 +1032,9 @@ class CardanoIndexer {
1018
1032
  : [];
1019
1033
  if (this.crawlCertificates)
1020
1034
  this.warnIfCertificatesUnreported(txs);
1021
- // Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
1035
+ // Redeemers and witness datums come with the block on chain-sync; keyed by tx like the certificates.
1022
1036
  const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
1037
+ const datumRows = txs.flatMap(t => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
1023
1038
  // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
1024
1039
  // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
1025
1040
  const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
@@ -1041,6 +1056,8 @@ class CardanoIndexer {
1041
1056
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
1042
1057
  if (redeemerRows.length)
1043
1058
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
1059
+ if (datumRows.length)
1060
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionDatums).entries(datumRows));
1044
1061
  // Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
1045
1062
  if (ledgerDue) {
1046
1063
  if (priorInvalidation) {
@@ -1138,7 +1155,7 @@ class CardanoIndexer {
1138
1155
  if (local) {
1139
1156
  input.address = local.address;
1140
1157
  input.amount = local.amount ?? [];
1141
- copyUtxoData(input, local.dataHash, local.inlineDatum, local.referenceScriptHash);
1158
+ copyUtxoData(input, utxoDataOf(local));
1142
1159
  }
1143
1160
  else {
1144
1161
  unresolved.push({ input, key });
@@ -1157,7 +1174,7 @@ class CardanoIndexer {
1157
1174
  continue;
1158
1175
  unresolved[i].input.address = row.address;
1159
1176
  unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
1160
- copyUtxoData(unresolved[i].input, row.utxo_dataHash, row.utxo_inlineDatum, row.utxo_referenceScriptHash);
1177
+ copyUtxoData(unresolved[i].input, row);
1161
1178
  unresolved.splice(i, 1);
1162
1179
  }
1163
1180
  if (!unresolved.length)
@@ -1193,7 +1210,7 @@ class CardanoIndexer {
1193
1210
  if (out?.address_address != null)
1194
1211
  input.address = out.address_address;
1195
1212
  if (out)
1196
- copyUtxoData(input, out.utxo_dataHash, out.utxo_inlineDatum, out.utxo_referenceScriptHash);
1213
+ copyUtxoData(input, out);
1197
1214
  const amt = amtByKey.get(key);
1198
1215
  if (amt)
1199
1216
  input.amount = amt;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Fills the payment credential of UTxO-shaped rows written before the column existed:
3
+ * TransactionOutputs, TransactionInputs and LedgerUTxOs. Each table is walked once in key
4
+ * order; rows that already carry a credential are skipped, so a second run changes nothing.
5
+ */
6
+ export interface CredentialBackfillProgress {
7
+ /** Table being walked; null when finished. */
8
+ table: 'TransactionOutputs' | 'TransactionInputs' | 'LedgerUTxOs' | null;
9
+ outputs: number;
10
+ inputs: number;
11
+ ledgerUtxos: number;
12
+ }
13
+ export interface CredentialBackfillOptions {
14
+ /** Rows per statement. */
15
+ chunkSize?: number;
16
+ onProgress?: (p: CredentialBackfillProgress) => void;
17
+ }
18
+ export interface CredentialTableSpec {
19
+ name: NonNullable<CredentialBackfillProgress['table']>;
20
+ entity: unknown;
21
+ table: string;
22
+ /** Primary key in walk order. */
23
+ keys: [first: string, second: string];
24
+ /** Postgres type of the first key column. */
25
+ firstKeyType: 'bigint' | 'text';
26
+ column: string;
27
+ address: string;
28
+ counter: 'outputs' | 'inputs' | 'ledgerUtxos';
29
+ }
30
+ export declare const CREDENTIAL_TABLES: readonly CredentialTableSpec[];
31
+ /**
32
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on the key. Only rows
33
+ * still without a credential are touched. Postgres and SQLite; other databases get one UPDATE per row.
34
+ */
35
+ export declare function credentialFillStatement(kind: string, spec: CredentialTableSpec): string | null;
36
+ export declare function backfillUtxoCredentials(opts?: CredentialBackfillOptions): Promise<CredentialBackfillProgress>;
37
+ //# sourceMappingURL=credential-backfill.d.ts.map
@@ -0,0 +1,124 @@
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.CREDENTIAL_TABLES = void 0;
7
+ exports.credentialFillStatement = credentialFillStatement;
8
+ exports.backfillUtxoCredentials = backfillUtxoCredentials;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const collections_1 = require("../../utils/collections");
12
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
+ const { SELECT, UPDATE } = cds_1.default.ql;
14
+ const logger = cds_1.default.log('CredentialBackfill');
15
+ exports.CREDENTIAL_TABLES = [
16
+ { name: 'TransactionOutputs', entity: cardano_1.TransactionOutputs, table: 'odatano_cardano_TransactionOutputs', keys: ['txSeq', 'outputIndex'], firstKeyType: 'bigint', column: 'utxo_paymentCredential', address: 'address_address', counter: 'outputs' },
17
+ { name: 'TransactionInputs', entity: cardano_1.TransactionInputs, table: 'odatano_cardano_TransactionInputs', keys: ['txSeq', 'inputIndex'], firstKeyType: 'bigint', column: 'utxoData_paymentCredential', address: 'address_address', counter: 'inputs' },
18
+ { name: 'LedgerUTxOs', entity: cardano_1.LedgerUTxOs, table: 'odatano_cardano_LedgerUTxOs', keys: ['txHash', 'outputIndex'], firstKeyType: 'text', column: 'utxo_paymentCredential', address: 'address', counter: 'ledgerUtxos' },
19
+ ];
20
+ /**
21
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on the key. Only rows
22
+ * still without a credential are touched. Postgres and SQLite; other databases get one UPDATE per row.
23
+ */
24
+ function credentialFillStatement(kind, spec) {
25
+ const [k1, k2] = spec.keys;
26
+ if (kind === 'postgres') {
27
+ return `UPDATE ${spec.table} AS t SET ${spec.column} = v.credential ` +
28
+ `FROM json_to_recordset($1::json) AS v(${k1.toLowerCase()} ${spec.firstKeyType}, ${k2.toLowerCase()} integer, credential text) ` +
29
+ `WHERE t.${k1} = v.${k1.toLowerCase()} AND t.${k2} = v.${k2.toLowerCase()} AND t.${spec.column} IS NULL`;
30
+ }
31
+ if (kind === 'sqlite' || kind === 'better-sqlite') {
32
+ const cols = [k1, k2, 'credential'].map((c) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
33
+ return `UPDATE ${spec.table} AS t SET ${spec.column} = v.credential FROM (SELECT ${cols} FROM json_each(?)) AS v ` +
34
+ `WHERE t.${k1} = v.${k1} AND t.${k2} = v.${k2} AND t.${spec.column} IS NULL`;
35
+ }
36
+ return null;
37
+ }
38
+ async function writeFills(tx, spec, fills, chunkSize) {
39
+ if (!fills.length)
40
+ return;
41
+ const sql = credentialFillStatement(cds_1.default.db?.kind ?? '', spec);
42
+ const [k1, k2] = spec.keys;
43
+ if (!sql) {
44
+ for (const f of fills) {
45
+ await tx.run(UPDATE.entity(spec.entity).set({ [spec.column]: f.credential }).where({ [k1]: f.first, [k2]: f.second, [spec.column]: null }));
46
+ }
47
+ return;
48
+ }
49
+ for (const part of (0, collections_1.chunk)(fills, chunkSize)) {
50
+ const records = part.map((f) => ({ [k1.toLowerCase()]: f.first, [k2.toLowerCase()]: f.second, credential: f.credential }));
51
+ await tx.run(sql, [JSON.stringify(records)]);
52
+ }
53
+ }
54
+ const keyValue = (v, type) => type === 'bigint' ? Number(v) : String(v);
55
+ /** Walks one table from its lowest key; returns the rows that received a credential. */
56
+ async function fillTable(spec, chunkSize, onChunk) {
57
+ const [k1, k2] = spec.keys;
58
+ let filled = 0;
59
+ let cursor = null;
60
+ const decoded = new Map();
61
+ for (;;) {
62
+ const done = await cds_1.default.tx(async (tx) => {
63
+ const where = { [spec.column]: null };
64
+ if (cursor?.within) {
65
+ where[k1] = cursor.first;
66
+ where[k2] = { '>': cursor.second };
67
+ }
68
+ else if (cursor) {
69
+ where[k1] = { '>': cursor.first };
70
+ }
71
+ const rows = (await tx.run(SELECT.from(spec.entity).columns(k1, k2, spec.address).where(where).orderBy(k1, k2).limit(chunkSize))) ?? [];
72
+ const wasWithin = cursor?.within ?? false;
73
+ if (!rows.length) {
74
+ if (!wasWithin)
75
+ return true;
76
+ cursor = { ...cursor, within: false };
77
+ return false;
78
+ }
79
+ const full = rows.length === chunkSize;
80
+ const lastFirst = rows[rows.length - 1][k1];
81
+ const allSame = rows.every((r) => r[k1] === lastFirst);
82
+ // The last key of a full batch may continue in the next one: its rows wait for it. When the
83
+ // whole batch is that one key, the walk continues inside it by the second key.
84
+ const complete = full && !allSame ? rows.filter((r) => r[k1] !== lastFirst) : rows;
85
+ const fills = [];
86
+ for (const r of complete) {
87
+ const address = r[spec.address];
88
+ if (!address)
89
+ continue;
90
+ if (!decoded.has(address))
91
+ decoded.set(address, (0, mappers_1.paymentCredentialOf)(address));
92
+ const credential = decoded.get(address);
93
+ if (credential)
94
+ fills.push({ first: keyValue(r[k1], spec.firstKeyType), second: Number(r[k2]), credential });
95
+ }
96
+ await writeFills(tx, spec, fills, chunkSize);
97
+ filled += fills.length;
98
+ const last = complete[complete.length - 1];
99
+ cursor = { first: keyValue(last[k1], spec.firstKeyType), second: Number(last[k2]), within: full && allSame };
100
+ return !full && !wasWithin;
101
+ });
102
+ onChunk(filled);
103
+ if (decoded.size > 50_000)
104
+ decoded.clear();
105
+ if (done)
106
+ return filled;
107
+ }
108
+ }
109
+ async function backfillUtxoCredentials(opts = {}) {
110
+ const chunkSize = opts.chunkSize ?? 5000;
111
+ const progress = { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0 };
112
+ for (const spec of exports.CREDENTIAL_TABLES) {
113
+ progress.table = spec.name;
114
+ opts.onProgress?.({ ...progress });
115
+ progress[spec.counter] = await fillTable(spec, chunkSize, (filled) => {
116
+ progress[spec.counter] = filled;
117
+ opts.onProgress?.({ ...progress });
118
+ });
119
+ }
120
+ progress.table = null;
121
+ logger.info(`payment credentials filled: ${progress.outputs} outputs, ${progress.inputs} inputs, ${progress.ledgerUtxos} ledger UTxOs`);
122
+ return progress;
123
+ }
124
+ //# sourceMappingURL=credential-backfill.js.map
@@ -6,8 +6,8 @@ import type { LedgerLookup } from '../ledger-state';
6
6
  /**
7
7
  * Completes transactions the crawl already holds from a second chain-sync stream: input
8
8
  * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
9
- * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
10
- * transaction whose stored inputs do not line up with the stream is left as it is.
9
+ * hash, a missing input address, the redeemers and the witness datums. Only empty input fields
10
+ * are filled; a transaction whose stored inputs do not line up with the stream is left as it is.
11
11
  */
12
12
  export declare class TransactionBackfillError extends Error {
13
13
  constructor(message: string);
@@ -20,6 +20,7 @@ export interface TransactionBackfillProgress {
20
20
  /** Input rows that got at least one field. */
21
21
  inputs: number;
22
22
  redeemers: number;
23
+ datums: number;
23
24
  /** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
24
25
  rewritten: number;
25
26
  /** Transactions left as they are: stored inputs differ from the stream. */
@@ -16,8 +16,8 @@ const logger = cds_1.default.log('TransactionBackfill');
16
16
  /**
17
17
  * Completes transactions the crawl already holds from a second chain-sync stream: input
18
18
  * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
19
- * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
20
- * transaction whose stored inputs do not line up with the stream is left as it is.
19
+ * hash, a missing input address, the redeemers and the witness datums. Only empty input fields
20
+ * are filled; a transaction whose stored inputs do not line up with the stream is left as it is.
21
21
  */
22
22
  class TransactionBackfillError extends Error {
23
23
  constructor(message) {
@@ -83,6 +83,10 @@ function missingFields(row, fresh) {
83
83
  set.utxoData_inlineDatum = fresh.inlineDatum;
84
84
  if (row.utxoData_referenceScriptHash == null && fresh.referenceScriptHash)
85
85
  set.utxoData_referenceScriptHash = fresh.referenceScriptHash;
86
+ if (row.utxoData_referenceScriptSize == null && fresh.referenceScriptSize != null)
87
+ set.utxoData_referenceScriptSize = fresh.referenceScriptSize;
88
+ if (row.utxoData_referenceScriptType == null && fresh.referenceScriptType)
89
+ set.utxoData_referenceScriptType = fresh.referenceScriptType;
86
90
  if (!row.address_address && fresh.address) {
87
91
  set.address_address = fresh.address;
88
92
  set.hasAddresses = true;
@@ -100,6 +104,8 @@ const FILL_COLUMNS = [
100
104
  ['utxoData_dataHash', 'text'],
101
105
  ['utxoData_inlineDatum', 'text'],
102
106
  ['utxoData_referenceScriptHash', 'text'],
107
+ ['utxoData_referenceScriptSize', 'integer'],
108
+ ['utxoData_referenceScriptType', 'text'],
103
109
  ['address_address', 'text'],
104
110
  ['hasAddresses', 'boolean'],
105
111
  ['hasAssets', 'boolean'],
@@ -193,7 +199,7 @@ async function dropUnappliedOutputs(tx, txs) {
193
199
  }
194
200
  async function backfillTransactions(opts) {
195
201
  const { fromSlot, toSlot, indexer } = opts;
196
- const progress = { atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0 };
202
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0 };
197
203
  let started = false;
198
204
  const intersection = await (0, certificate_backfill_1.streamCrawledBlocks)({ ...opts, errorType: TransactionBackfillError }, (_block, txs) => txs, async (tx, blocks) => {
199
205
  const txs = blocks.flatMap((b) => b.payload);
@@ -269,6 +275,10 @@ async function backfillTransactions(opts) {
269
275
  progress.redeemers += redeemerRows.length;
270
276
  if (redeemerRows.length)
271
277
  await tx.run(UPSERT.into(cardano_1.TransactionRedeemers).entries(redeemerRows));
278
+ const datumRows = txs.flatMap((t) => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
279
+ progress.datums += datumRows.length;
280
+ if (datumRows.length)
281
+ await tx.run(UPSERT.into(cardano_1.TransactionDatums).entries(datumRows));
272
282
  }, (atSlot) => {
273
283
  started = true;
274
284
  progress.atSlot = atSlot;
@@ -277,7 +287,7 @@ async function backfillTransactions(opts) {
277
287
  if (!started)
278
288
  progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
279
289
  logger.info(`Transaction backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.inputs} inputs, ` +
280
- `${progress.redeemers} redeemers, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
290
+ `${progress.redeemers} redeemers, ${progress.datums} datums, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
281
291
  return { ...progress, fromSlot, toSlot, intersection };
282
292
  }
283
293
  //# sourceMappingURL=transaction-backfill.js.map
@@ -1,6 +1,6 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
- import type { Amount } from '../../utils/types';
3
+ import type { Amount, ReferenceScriptType } from '../../utils/types';
4
4
  import { type LedgerAnchor } from '../ledger-state';
5
5
  /**
6
6
  * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
@@ -22,6 +22,8 @@ export interface UtxoSetEntry {
22
22
  dataHash?: string | null;
23
23
  inlineDatum?: string | null;
24
24
  referenceScriptHash?: string | null;
25
+ referenceScriptSize?: number | null;
26
+ referenceScriptType?: ReferenceScriptType | null;
25
27
  }
26
28
  export interface UtxoSetImportOptions {
27
29
  source: 'ogmios' | 'file';
@@ -75,4 +77,21 @@ export declare function importUtxoSet(opts: UtxoSetImportOptions): Promise<UtxoS
75
77
  export declare function rebuildUtxoSetAggregates(opts: {
76
78
  indexer: CardanoIndexer;
77
79
  }): Promise<UtxoSetImportResult>;
80
+ export interface UtxoSetScriptRefreshResult {
81
+ /** Rows whose reference-script columns were written. */
82
+ updated: number;
83
+ /** Rows looked at: dump entries carrying a script, or stored rows with a hash but no size. */
84
+ candidates: number;
85
+ }
86
+ /**
87
+ * Fill the reference-script columns (hash, size, type) of `LedgerUTxOs` rows an earlier import
88
+ * left empty: from the same cardano-cli dump, or, without a file, from the node for the unspent
89
+ * rows that hold a hash but no size. Takes the cursor lease like an import, so the crawler must
90
+ * be paused; the set stays `active` throughout.
91
+ */
92
+ export declare function refreshUtxoSetReferenceScripts(opts: {
93
+ filePath?: string;
94
+ client: CardanoClient;
95
+ batchSize?: number;
96
+ }): Promise<UtxoSetScriptRefreshResult>;
78
97
  //# sourceMappingURL=utxo-set-import.d.ts.map
@@ -10,15 +10,17 @@ exports.readUtxoSetFile = readUtxoSetFile;
10
10
  exports.aggregateStatements = aggregateStatements;
11
11
  exports.importUtxoSet = importUtxoSet;
12
12
  exports.rebuildUtxoSetAggregates = rebuildUtxoSetAggregates;
13
+ exports.refreshUtxoSetReferenceScripts = refreshUtxoSetReferenceScripts;
13
14
  const cds_1 = __importDefault(require("@sap/cds"));
14
15
  const node_fs_1 = require("node:fs");
15
16
  const promises_1 = require("node:fs/promises");
16
17
  const node_readline_1 = require("node:readline");
18
+ const reference_script_1 = require("../../utils/reference-script");
17
19
  const ledger_state_1 = require("../ledger-state");
18
20
  const sync_state_1 = require("./sync-state");
19
21
  const cardano_1 = require("#cds-models/odatano/cardano");
20
22
  const collections_1 = require("../../utils/collections");
21
- const { UPSERT, DELETE, SELECT } = cds_1.default.ql;
23
+ const { UPSERT, DELETE, SELECT, UPDATE } = cds_1.default.ql;
22
24
  const logger = cds_1.default.log('LedgerState');
23
25
  /**
24
26
  * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
@@ -68,6 +70,7 @@ function parseCliUtxoEntry(key, value) {
68
70
  }
69
71
  if (!amount.some(a => a.unit === 'lovelace'))
70
72
  amount.unshift({ unit: 'lovelace', quantity: '0' });
73
+ const ref = (0, reference_script_1.cliReferenceScript)(value.referenceScript);
71
74
  return {
72
75
  txHash: m[1].toLowerCase(),
73
76
  outputIndex: Number(m[2]),
@@ -75,8 +78,9 @@ function parseCliUtxoEntry(key, value) {
75
78
  amount,
76
79
  dataHash: value.datumhash ?? value.datumHash ?? null,
77
80
  inlineDatum: typeof value.inlineDatumRaw === 'string' ? value.inlineDatumRaw : null,
78
- // the cli prints the script itself, not its hash — resolved lazily, like every other path
79
- referenceScriptHash: null,
81
+ referenceScriptHash: ref?.hash ?? null,
82
+ referenceScriptSize: ref?.size ?? null,
83
+ referenceScriptType: ref?.type ?? null,
80
84
  };
81
85
  }
82
86
  /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
@@ -124,6 +128,8 @@ async function* readFromOgmios(client, anchor) {
124
128
  dataHash: u.datumHash ?? null,
125
129
  inlineDatum: u.inlineDatum ?? null,
126
130
  referenceScriptHash: u.scriptRef ?? null,
131
+ referenceScriptSize: u.scriptRefSize ?? null,
132
+ referenceScriptType: u.scriptRefType ?? null,
127
133
  };
128
134
  }
129
135
  }
@@ -360,4 +366,66 @@ async function rebuildUtxoSetAggregates(opts) {
360
366
  return { utxos, anchor };
361
367
  });
362
368
  }
369
+ /**
370
+ * Fill the reference-script columns (hash, size, type) of `LedgerUTxOs` rows an earlier import
371
+ * left empty: from the same cardano-cli dump, or, without a file, from the node for the unspent
372
+ * rows that hold a hash but no size. Takes the cursor lease like an import, so the crawler must
373
+ * be paused; the set stays `active` throughout.
374
+ */
375
+ async function refreshUtxoSetReferenceScripts(opts) {
376
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
377
+ if (!cursor)
378
+ throw new UtxoSetImportError('No crawler cursor yet.');
379
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
380
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
381
+ if (cursor.utxoSet.anchorSlot == null)
382
+ throw new UtxoSetImportError('No imported UTxO set — run importUtxoSet first.');
383
+ const batchSize = opts.batchSize ?? 2000;
384
+ return withImportLease(async (lease) => {
385
+ let candidates = 0;
386
+ let updated = 0;
387
+ const write = async (fills) => {
388
+ if (!fills.length)
389
+ return;
390
+ await lease.writeTx(async (tx) => {
391
+ for (const f of fills) {
392
+ const n = await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs)
393
+ .set({ utxo_referenceScriptHash: f.hash, utxo_referenceScriptSize: f.size, utxo_referenceScriptType: f.type })
394
+ .where({ txHash: f.txHash, outputIndex: f.outputIndex }));
395
+ updated += Number(n) || 0;
396
+ }
397
+ });
398
+ };
399
+ if (opts.filePath) {
400
+ let fills = [];
401
+ for await (const e of readUtxoSetFile(opts.filePath)) {
402
+ if (!e.referenceScriptHash || e.referenceScriptSize == null || !e.referenceScriptType)
403
+ continue;
404
+ candidates++;
405
+ fills.push({ txHash: e.txHash, outputIndex: e.outputIndex, hash: e.referenceScriptHash, size: e.referenceScriptSize, type: e.referenceScriptType });
406
+ if (fills.length >= batchSize) {
407
+ await write(fills);
408
+ fills = [];
409
+ }
410
+ }
411
+ await write(fills);
412
+ }
413
+ else {
414
+ const backend = opts.client.getLedgerStateBackend();
415
+ if (!backend)
416
+ throw new UtxoSetImportError('No Ogmios backend available — pass the cardano-cli dump as filePath instead.');
417
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex')
418
+ .where({ spentTxHash: null, utxo_referenceScriptHash: { '!=': null }, utxo_referenceScriptSize: null })));
419
+ candidates = rows?.length ?? 0;
420
+ for (const refs of (0, collections_1.chunk)(rows ?? [], collections_1.IN_CHUNK)) {
421
+ const live = await backend.getUnspentOutputs(refs.map(r => ({ txHash: r.txHash, outputIndex: Number(r.outputIndex) })));
422
+ await write(live.flatMap(u => (u.scriptRef && u.scriptRefSize != null && u.scriptRefType
423
+ ? [{ txHash: u.txHash, outputIndex: u.outputIndex, hash: u.scriptRef, size: u.scriptRefSize, type: u.scriptRefType }]
424
+ : [])));
425
+ }
426
+ }
427
+ logger.info(`UTxO set reference scripts refreshed: ${updated} of ${candidates} rows (${opts.filePath ? 'dump' : 'node'})`);
428
+ return { updated, candidates };
429
+ });
430
+ }
363
431
  //# sourceMappingURL=utxo-set-import.js.map