@odatano/core 2.0.0-rc.42 → 2.0.0-rc.44

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 (43) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +78 -0
  2. package/@cds-models/CardanoIndexerService/index.js +11 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +36 -0
  4. package/@cds-models/CardanoODataService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +1 -0
  6. package/@cds-models/CardanoTransactionService/index.d.ts +1 -0
  7. package/@cds-models/index.d.ts +1 -0
  8. package/@cds-models/odatano/cardano/index.d.ts +25 -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 -417
  13. package/package.json +1 -1
  14. package/srv/blockchain/asset-decimals.d.ts +16 -0
  15. package/srv/blockchain/asset-decimals.js +86 -0
  16. package/srv/blockchain/backends/ogmios-backend.js +1 -0
  17. package/srv/blockchain/cardano-indexer.js +10 -1
  18. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +20 -0
  19. package/srv/blockchain/crawler/asset-decimals-backfill.js +59 -0
  20. package/srv/blockchain/crawler/credential-backfill.d.ts +38 -0
  21. package/srv/blockchain/crawler/credential-backfill.js +126 -0
  22. package/srv/blockchain/crawler/transaction-backfill.d.ts +3 -2
  23. package/srv/blockchain/crawler/transaction-backfill.js +8 -4
  24. package/srv/blockchain/ledger-state.d.ts +1 -0
  25. package/srv/blockchain/ledger-state.js +1 -0
  26. package/srv/blockchain/stored-chain.js +5 -1
  27. package/srv/blockchain/transaction-rows.d.ts +1 -1
  28. package/srv/blockchain/transaction-rows.js +2 -1
  29. package/srv/cardano-indexer-service.cds +48 -2
  30. package/srv/cardano-indexer-service.js +47 -2
  31. package/srv/cardano-service.cds +344 -332
  32. package/srv/cardano-service.js +9 -0
  33. package/srv/cbor/cip68.d.ts +17 -0
  34. package/srv/cbor/cip68.js +58 -0
  35. package/srv/cbor/index.d.ts +2 -0
  36. package/srv/cbor/index.js +9 -1
  37. package/srv/cbor/plutus-data-json.d.ts +24 -0
  38. package/srv/cbor/plutus-data-json.js +32 -0
  39. package/srv/utils/agent-grants.js +1 -1
  40. package/srv/utils/db-indexes.js +5 -0
  41. package/srv/utils/mappers.d.ts +6 -2
  42. package/srv/utils/mappers.js +16 -0
  43. package/srv/utils/types.d.ts +9 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.42",
3
+ "version": "2.0.0-rc.44",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -0,0 +1,16 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { Transaction as ProviderTransaction } from '../utils/types';
3
+ /**
4
+ * CIP-68 decimals of a user token (label 333 or 444) from the crawled chain. `mintTxHash` is the
5
+ * token's own mint, tried when AssetHistory has no mint of the reference NFT. null for any other
6
+ * unit or when the chain does not answer.
7
+ */
8
+ export declare function cip68Decimals(tx: CapTransaction, unit: string, mintTxHash?: string | null): Promise<number | null>;
9
+ /** Write `decimals` on every slice of the unit; returns the rows changed. */
10
+ export declare function setAssetDecimals(tx: CapTransaction, unit: string, decimals: number): Promise<number>;
11
+ /**
12
+ * Apply the reference datums a block carries: for every output holding a reference NFT, the
13
+ * decimals of its datum go to the catalogue rows of the matching user tokens. Returns the rows changed.
14
+ */
15
+ export declare function applyReferenceDatums(tx: CapTransaction, txs: ProviderTransaction[]): Promise<number>;
16
+ //# sourceMappingURL=asset-decimals.d.ts.map
@@ -0,0 +1,86 @@
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.cip68Decimals = cip68Decimals;
7
+ exports.setAssetDecimals = setAssetDecimals;
8
+ exports.applyReferenceDatums = applyReferenceDatums;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
+ const cip68_1 = require("../cbor/cip68");
12
+ const { SELECT, UPDATE } = cds_1.default.ql;
13
+ /** Spending transactions a reference NFT is followed through before the trail is given up. */
14
+ const MAX_HOPS = 10_000;
15
+ async function storedDatum(tx, dataHash) {
16
+ const row = await tx.run(SELECT.one.from(cardano_1.TransactionDatums).columns('datum').where({ dataHash }));
17
+ return row?.datum ?? null;
18
+ }
19
+ /**
20
+ * Datum on the output that holds a reference NFT now: from the NFT's latest mint, each output is
21
+ * followed to the transaction that spent it until an unspent one is reached. A datum given by
22
+ * hash is read from TransactionDatums. null when the crawled chain has no trail.
23
+ */
24
+ async function currentReferenceDatum(tx, referenceUnit, mintTxHash) {
25
+ const mint = await tx.run(SELECT.one.from(cardano_1.AssetHistory).columns('txHash').where({ unit: referenceUnit, action: 'mint' }).orderBy('blockHeight desc'));
26
+ let txHash = mint?.txHash ?? mintTxHash;
27
+ let datum = null;
28
+ for (let hop = 0; txHash && hop < MAX_HOPS; hop++) {
29
+ const head = await tx.run(SELECT.one.from(cardano_1.Transactions).columns('txSeq').where({ hash: txHash }));
30
+ if (head?.txSeq == null)
31
+ break;
32
+ const holder = await tx.run(SELECT.one.from(cardano_1.TransactionOutputAssets).columns('output_outputIndex').where({ output_txSeq: head.txSeq, unit: referenceUnit }));
33
+ if (holder?.output_outputIndex == null)
34
+ break;
35
+ const output = await tx.run(SELECT.one.from(cardano_1.TransactionOutputs).columns('utxo_inlineDatum', 'utxo_dataHash').where({ txSeq: head.txSeq, outputIndex: holder.output_outputIndex }));
36
+ datum = output?.utxo_inlineDatum ?? (output?.utxo_dataHash ? await storedDatum(tx, output.utxo_dataHash) : null) ?? datum;
37
+ const spender = await tx.run(SELECT.one.from(cardano_1.TransactionInputs).columns('txSeq').where({ spentTxHash: txHash, spentOutputIndex: holder.output_outputIndex }));
38
+ if (spender?.txSeq == null)
39
+ break;
40
+ const next = await tx.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ txSeq: spender.txSeq }));
41
+ txHash = next?.hash ?? null;
42
+ }
43
+ return datum;
44
+ }
45
+ /**
46
+ * CIP-68 decimals of a user token (label 333 or 444) from the crawled chain. `mintTxHash` is the
47
+ * token's own mint, tried when AssetHistory has no mint of the reference NFT. null for any other
48
+ * unit or when the chain does not answer.
49
+ */
50
+ async function cip68Decimals(tx, unit, mintTxHash = null) {
51
+ const referenceUnit = (0, cip68_1.cip68ReferenceUnit)(unit);
52
+ if (!referenceUnit)
53
+ return null;
54
+ const datum = await currentReferenceDatum(tx, referenceUnit, mintTxHash);
55
+ return datum ? (0, cip68_1.cip68DecimalsFromDatum)(datum) : null;
56
+ }
57
+ /** Write `decimals` on every slice of the unit; returns the rows changed. */
58
+ async function setAssetDecimals(tx, unit, decimals) {
59
+ const changed = await tx.run(UPDATE.entity(cardano_1.Assets).set({ decimals }).where({ unit }));
60
+ return Number(changed) || 0;
61
+ }
62
+ /**
63
+ * Apply the reference datums a block carries: for every output holding a reference NFT, the
64
+ * decimals of its datum go to the catalogue rows of the matching user tokens. Returns the rows changed.
65
+ */
66
+ async function applyReferenceDatums(tx, txs) {
67
+ let changed = 0;
68
+ for (const t of txs) {
69
+ const witness = new Map((t.datums ?? []).map((d) => [d.hash, d.cbor]));
70
+ for (const o of t.outputs ?? []) {
71
+ for (const a of o.amount ?? []) {
72
+ const users = (0, cip68_1.cip68UserUnits)(a.unit);
73
+ if (!users)
74
+ continue;
75
+ const datum = o.inlineDatum ?? (o.dataHash ? witness.get(o.dataHash) ?? await storedDatum(tx, o.dataHash) : null);
76
+ const decimals = datum ? (0, cip68_1.cip68DecimalsFromDatum)(datum) : null;
77
+ if (decimals == null)
78
+ continue;
79
+ for (const unit of users)
80
+ changed += await setAssetDecimals(tx, unit, decimals);
81
+ }
82
+ }
83
+ }
84
+ return changed;
85
+ }
86
+ //# sourceMappingURL=asset-decimals.js.map
@@ -1225,6 +1225,7 @@ class OgmiosBackend {
1225
1225
  amount: (value?.ada?.lovelace ?? 0).toString(),
1226
1226
  })),
1227
1227
  redeemers: mapOgmiosRedeemers(tx),
1228
+ datums: Object.entries(tx.datums ?? {}).map(([hash, cbor]) => ({ hash, cbor })),
1228
1229
  });
1229
1230
  }
1230
1231
  /**
@@ -17,6 +17,7 @@ const collections_1 = require("../utils/collections");
17
17
  const transaction_rows_1 = require("./transaction-rows");
18
18
  const ledger_state_1 = require("./ledger-state");
19
19
  const sync_state_1 = require("./crawler/sync-state");
20
+ const asset_decimals_1 = require("./asset-decimals");
20
21
  const epoch_slots_1 = require("../utils/epoch-slots");
21
22
  const const_1 = require("../utils/const");
22
23
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
@@ -1032,8 +1033,9 @@ class CardanoIndexer {
1032
1033
  : [];
1033
1034
  if (this.crawlCertificates)
1034
1035
  this.warnIfCertificatesUnreported(txs);
1035
- // Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
1036
+ // Redeemers and witness datums come with the block on chain-sync; keyed by tx like the certificates.
1036
1037
  const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
1038
+ const datumRows = txs.flatMap(t => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
1037
1039
  // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
1038
1040
  // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
1039
1041
  const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
@@ -1055,6 +1057,8 @@ class CardanoIndexer {
1055
1057
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
1056
1058
  if (redeemerRows.length)
1057
1059
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
1060
+ if (datumRows.length)
1061
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionDatums).entries(datumRows));
1058
1062
  // Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
1059
1063
  if (ledgerDue) {
1060
1064
  if (priorInvalidation) {
@@ -1076,6 +1080,8 @@ class CardanoIndexer {
1076
1080
  const newAssets = this.crawlAssetCatalogue === 'off'
1077
1081
  ? 0
1078
1082
  : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
1083
+ // A reference NFT moved or minted in this block carries the current CIP-68 metadata of its token.
1084
+ await (0, asset_decimals_1.applyReferenceDatums)(tx, txs);
1079
1085
  logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
1080
1086
  `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
1081
1087
  }
@@ -1338,6 +1344,8 @@ class CardanoIndexer {
1338
1344
  if (!missing.length)
1339
1345
  return 0;
1340
1346
  const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
1347
+ for (const row of rows)
1348
+ row.decimals = await (0, asset_decimals_1.cip68Decimals)(tx, row.unit);
1341
1349
  // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
1342
1350
  for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
1343
1351
  await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
@@ -1565,6 +1573,7 @@ class CardanoIndexer {
1565
1573
  async indexAsset(tx, unit) {
1566
1574
  const assetInfo = await this.resolveAssetInfo(tx, unit);
1567
1575
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1576
+ assetEntity.decimals = (await (0, asset_decimals_1.cip68Decimals)(tx, unit, assetInfo.initialMintTxHash)) ?? assetInfo.registryDecimals;
1568
1577
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
1569
1578
  return assetEntity;
1570
1579
  }
@@ -0,0 +1,20 @@
1
+ export interface DecimalsBackfillProgress {
2
+ /** Catalogue rows read. */
3
+ scanned: number;
4
+ /** Units with label 333 or 444. */
5
+ candidates: number;
6
+ /** Units that received a decimals value. */
7
+ filled: number;
8
+ }
9
+ export interface DecimalsBackfillOptions {
10
+ /** Rows per page. */
11
+ chunkSize?: number;
12
+ onProgress?: (p: DecimalsBackfillProgress) => void;
13
+ }
14
+ /**
15
+ * Fills Assets.decimals from the CIP-68 reference datum for every catalogue unit with label 333
16
+ * or 444. The catalogue is paged by unit alone, so the page query never depends on column
17
+ * statistics; a repeat resolves every unit again and so refreshes the values.
18
+ */
19
+ export declare function backfillAssetDecimals(opts?: DecimalsBackfillOptions): Promise<DecimalsBackfillProgress>;
20
+ //# sourceMappingURL=asset-decimals-backfill.d.ts.map
@@ -0,0 +1,59 @@
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.backfillAssetDecimals = backfillAssetDecimals;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const cardano_1 = require("#cds-models/odatano/cardano");
9
+ const cip68_1 = require("../../cbor/cip68");
10
+ const asset_decimals_1 = require("../asset-decimals");
11
+ const { SELECT } = cds_1.default.ql;
12
+ const logger = cds_1.default.log('DecimalsBackfill');
13
+ /**
14
+ * Fills Assets.decimals from the CIP-68 reference datum for every catalogue unit with label 333
15
+ * or 444. The catalogue is paged by unit alone, so the page query never depends on column
16
+ * statistics; a repeat resolves every unit again and so refreshes the values.
17
+ */
18
+ async function backfillAssetDecimals(opts = {}) {
19
+ const chunkSize = opts.chunkSize ?? 5000;
20
+ const progress = { scanned: 0, candidates: 0, filled: 0 };
21
+ let cursor = null;
22
+ for (;;) {
23
+ const done = await cds_1.default.tx(async (tx) => {
24
+ const rows = (await tx.run(SELECT.from(cardano_1.Assets).columns('unit', 'initialMintTxHash').where(cursor ? { unit: { '>': cursor } } : {}).orderBy('unit').limit(chunkSize))) ?? [];
25
+ if (!rows.length)
26
+ return true;
27
+ const full = rows.length === chunkSize;
28
+ const lastUnit = rows[rows.length - 1].unit;
29
+ const allSame = rows.every((r) => r.unit === lastUnit);
30
+ // The slices of a unit are adjacent. The last unit of a full page may continue on the next
31
+ // one, so its rows wait there; a page holding one unit only is resolved as a whole.
32
+ const complete = full && !allSame ? rows.filter((r) => r.unit !== lastUnit) : rows;
33
+ const mints = new Map();
34
+ for (const r of complete) {
35
+ if (!(0, cip68_1.cip68ReferenceUnit)(r.unit))
36
+ continue;
37
+ if (!mints.has(r.unit) || r.initialMintTxHash)
38
+ mints.set(r.unit, r.initialMintTxHash ?? null);
39
+ }
40
+ for (const [unit, mintTxHash] of mints) {
41
+ const decimals = await (0, asset_decimals_1.cip68Decimals)(tx, unit, mintTxHash);
42
+ if (decimals == null)
43
+ continue;
44
+ await (0, asset_decimals_1.setAssetDecimals)(tx, unit, decimals);
45
+ progress.filled++;
46
+ }
47
+ progress.scanned += complete.length;
48
+ progress.candidates += mints.size;
49
+ cursor = complete[complete.length - 1].unit;
50
+ return !full;
51
+ });
52
+ opts.onProgress?.({ ...progress });
53
+ if (done)
54
+ break;
55
+ }
56
+ logger.info(`asset decimals filled: ${progress.filled} of ${progress.candidates} CIP-68 units, ${progress.scanned} catalogue rows read`);
57
+ return progress;
58
+ }
59
+ //# sourceMappingURL=asset-decimals-backfill.js.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Fills the payment credential of UTxO-shaped rows written before the column existed:
3
+ * TransactionOutputs, TransactionInputs and LedgerUTxOs. Each table is paged by its primary key
4
+ * alone, so the page query never depends on column statistics; rows that already carry a
5
+ * credential are skipped in process, and a second run changes nothing.
6
+ */
7
+ export interface CredentialBackfillProgress {
8
+ /** Table being walked; null when finished. */
9
+ table: 'TransactionOutputs' | 'TransactionInputs' | 'LedgerUTxOs' | null;
10
+ outputs: number;
11
+ inputs: number;
12
+ ledgerUtxos: number;
13
+ }
14
+ export interface CredentialBackfillOptions {
15
+ /** Rows per statement. */
16
+ chunkSize?: number;
17
+ onProgress?: (p: CredentialBackfillProgress) => void;
18
+ }
19
+ export interface CredentialTableSpec {
20
+ name: NonNullable<CredentialBackfillProgress['table']>;
21
+ entity: unknown;
22
+ table: string;
23
+ /** Primary key in walk order. */
24
+ keys: [first: string, second: string];
25
+ /** Postgres type of the first key column. */
26
+ firstKeyType: 'bigint' | 'text';
27
+ column: string;
28
+ address: string;
29
+ counter: 'outputs' | 'inputs' | 'ledgerUtxos';
30
+ }
31
+ export declare const CREDENTIAL_TABLES: readonly CredentialTableSpec[];
32
+ /**
33
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on the key. Only rows
34
+ * still without a credential are touched. Postgres and SQLite; other databases get one UPDATE per row.
35
+ */
36
+ export declare function credentialFillStatement(kind: string, spec: CredentialTableSpec): string | null;
37
+ export declare function backfillUtxoCredentials(opts?: CredentialBackfillOptions): Promise<CredentialBackfillProgress>;
38
+ //# sourceMappingURL=credential-backfill.d.ts.map
@@ -0,0 +1,126 @@
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 = {};
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, spec.column).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
+ if (r[spec.column] != null)
88
+ continue;
89
+ const address = r[spec.address];
90
+ if (!address)
91
+ continue;
92
+ if (!decoded.has(address))
93
+ decoded.set(address, (0, mappers_1.paymentCredentialOf)(address));
94
+ const credential = decoded.get(address);
95
+ if (credential)
96
+ fills.push({ first: keyValue(r[k1], spec.firstKeyType), second: Number(r[k2]), credential });
97
+ }
98
+ await writeFills(tx, spec, fills, chunkSize);
99
+ filled += fills.length;
100
+ const last = complete[complete.length - 1];
101
+ cursor = { first: keyValue(last[k1], spec.firstKeyType), second: Number(last[k2]), within: full && allSame };
102
+ return !full && !wasWithin;
103
+ });
104
+ onChunk(filled);
105
+ if (decoded.size > 50_000)
106
+ decoded.clear();
107
+ if (done)
108
+ return filled;
109
+ }
110
+ }
111
+ async function backfillUtxoCredentials(opts = {}) {
112
+ const chunkSize = opts.chunkSize ?? 5000;
113
+ const progress = { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0 };
114
+ for (const spec of exports.CREDENTIAL_TABLES) {
115
+ progress.table = spec.name;
116
+ opts.onProgress?.({ ...progress });
117
+ progress[spec.counter] = await fillTable(spec, chunkSize, (filled) => {
118
+ progress[spec.counter] = filled;
119
+ opts.onProgress?.({ ...progress });
120
+ });
121
+ }
122
+ progress.table = null;
123
+ logger.info(`payment credentials filled: ${progress.outputs} outputs, ${progress.inputs} inputs, ${progress.ledgerUtxos} ledger UTxOs`);
124
+ return progress;
125
+ }
126
+ //# 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) {
@@ -199,7 +199,7 @@ async function dropUnappliedOutputs(tx, txs) {
199
199
  }
200
200
  async function backfillTransactions(opts) {
201
201
  const { fromSlot, toSlot, indexer } = opts;
202
- 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 };
203
203
  let started = false;
204
204
  const intersection = await (0, certificate_backfill_1.streamCrawledBlocks)({ ...opts, errorType: TransactionBackfillError }, (_block, txs) => txs, async (tx, blocks) => {
205
205
  const txs = blocks.flatMap((b) => b.payload);
@@ -275,6 +275,10 @@ async function backfillTransactions(opts) {
275
275
  progress.redeemers += redeemerRows.length;
276
276
  if (redeemerRows.length)
277
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));
278
282
  }, (atSlot) => {
279
283
  started = true;
280
284
  progress.atSlot = atSlot;
@@ -283,7 +287,7 @@ async function backfillTransactions(opts) {
283
287
  if (!started)
284
288
  progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
285
289
  logger.info(`Transaction backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.inputs} inputs, ` +
286
- `${progress.redeemers} redeemers, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
290
+ `${progress.redeemers} redeemers, ${progress.datums} datums, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
287
291
  return { ...progress, fromSlot, toSlot, intersection };
288
292
  }
289
293
  //# sourceMappingURL=transaction-backfill.js.map
@@ -34,6 +34,7 @@ export interface LedgerUtxoRow {
34
34
  utxo_referenceScriptHash: string | null;
35
35
  utxo_referenceScriptSize: number | null;
36
36
  utxo_referenceScriptType: ReferenceScriptType | null;
37
+ utxo_paymentCredential: string | null;
37
38
  hasAssets: boolean;
38
39
  }
39
40
  export interface LedgerUtxoAssetRow {
@@ -63,6 +63,7 @@ function buildLedgerUtxoRows(o, createdSlot) {
63
63
  utxo_referenceScriptHash: o.referenceScriptHash || null,
64
64
  utxo_referenceScriptSize: o.referenceScriptSize ?? null,
65
65
  utxo_referenceScriptType: o.referenceScriptType ?? null,
66
+ utxo_paymentCredential: decoded.paymentCredential,
66
67
  hasAssets: assets.length > 0,
67
68
  },
68
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);
@@ -192,6 +194,7 @@ async function assembleTransactions(db, rows) {
192
194
  const withdrawn = withdrawalsByHash.get(hash);
193
195
  const minted = mintsByHash.get(hash);
194
196
  const redeemed = redeemersByHash.get(hash);
197
+ const witnessDatums = datumsByHash.get(hash);
195
198
  return {
196
199
  hash,
197
200
  blockHash: str(t.blockHash),
@@ -232,6 +235,7 @@ async function assembleTransactions(db, rows) {
232
235
  outputIndex: numOrNull(r.spentOutputIndex),
233
236
  policyId: r.policyId ?? null,
234
237
  })),
238
+ datums: witnessDatums?.map((d) => ({ hash: str(d.dataHash), cbor: str(d.datum) })),
235
239
  };
236
240
  });
237
241
  }
@@ -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,12 @@ 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;
61
+ // one-off CIP-68 decimals fill of the asset catalogue (this process)
62
+ decimalsBackfill : DecimalsBackfillStatus;
59
63
  // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
60
64
  epochSnapshots : EpochSnapshotStatus;
61
65
  }
@@ -96,6 +100,7 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
96
100
  transactions : Integer64;
97
101
  inputs : Integer64; // input rows that got at least one field
98
102
  redeemers : Integer64;
103
+ datums : Integer64;
99
104
  rewritten : Integer64; // transactions whose stored rows differed in order or extent from the ledger view, now rewritten
100
105
  skipped : Integer64; // transactions whose stored inputs differ from the stream
101
106
  startedAt : Timestamp;
@@ -103,6 +108,37 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
103
108
  error : String;
104
109
  }
105
110
 
111
+ @title : 'Credential Backfill Status'
112
+ @description: 'Progress of the payment-credential fill started with backfillPaymentCredentials; process-local, none after a restart'
113
+ type CredentialBackfillStatus {
114
+ status : String; // none | running | done | failed
115
+ table : String; // table being walked: TransactionOutputs | TransactionInputs | LedgerUTxOs; null when finished
116
+ outputs : Integer64; // rows that received a credential
117
+ inputs : Integer64;
118
+ ledgerUtxos : Integer64;
119
+ startedAt : Timestamp;
120
+ finishedAt : Timestamp;
121
+ error : String;
122
+ }
123
+
124
+ @title : 'Decimals Backfill Status'
125
+ @description: 'Progress of the CIP-68 decimals fill started with backfillAssetDecimals; process-local, none after a restart'
126
+ type DecimalsBackfillStatus {
127
+ status : String; // none | running | done | failed
128
+ scanned : Integer64; // catalogue rows read
129
+ candidates : Integer64; // units with label 333 or 444
130
+ filled : Integer64; // units that received a decimals value
131
+ startedAt : Timestamp;
132
+ finishedAt : Timestamp;
133
+ error : String;
134
+ }
135
+
136
+ @title : 'Backfill Result'
137
+ type BackfillResult {
138
+ accepted : Boolean;
139
+ message : String;
140
+ }
141
+
106
142
  @title : 'Certificate Backfill Result'
107
143
  type CertificateBackfillResult {
108
144
  accepted : Boolean;
@@ -195,7 +231,17 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
195
231
  action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
196
232
 
197
233
  @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.'
234
+ @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
235
  @requires : 'Admin'
200
236
  action backfillTransactions(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
237
+
238
+ @title : 'Backfill Payment Credentials'
239
+ @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.'
240
+ @requires : 'Admin'
241
+ action backfillPaymentCredentials() returns BackfillResult;
242
+
243
+ @title : 'Backfill Asset Decimals'
244
+ @description: 'Fill Assets.decimals from the CIP-68 reference datum for every catalogue unit with label 333 or 444: the reference NFT is followed from its mint through the crawled transactions to the output that holds it now, and the decimals of that datum are written to every slice of the unit. No backend call; the crawler may keep running; a repeat refreshes the values. Runs in the background; progress via getStatus().decimalsBackfill.'
245
+ @requires : 'Admin'
246
+ action backfillAssetDecimals() returns BackfillResult;
201
247
  }