@odatano/core 2.0.0-rc.43 → 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.
@@ -28,6 +28,7 @@ export default class {
28
28
  static readonly backfillCertificates: typeof backfillCertificates;
29
29
  static readonly backfillTransactions: typeof backfillTransactions;
30
30
  static readonly backfillPaymentCredentials: typeof backfillPaymentCredentials;
31
+ static readonly backfillAssetDecimals: typeof backfillAssetDecimals;
31
32
  }
32
33
 
33
34
  // entity 'SyncState'
@@ -106,6 +107,7 @@ export declare function _CrawlerStatusAspect<TBase extends new (...args: any[])
106
107
  certificateBackfill?: CertificateBackfillStatus | null
107
108
  transactionBackfill?: TransactionBackfillStatus | null
108
109
  credentialBackfill?: CredentialBackfillStatus | null
110
+ decimalsBackfill?: DecimalsBackfillStatus | null
109
111
  epochSnapshots?: EpochSnapshotStatus | null
110
112
  } & InstanceType<TBase>
111
113
  readonly kind: 'type';
@@ -201,6 +203,25 @@ export declare function _CredentialBackfillStatusAspect<TBase extends new (...ar
201
203
  export class CredentialBackfillStatus extends _CredentialBackfillStatusAspect(__.Entity) {
202
204
  }
203
205
 
206
+ // entity 'DecimalsBackfillStatus'
207
+ export declare function _DecimalsBackfillStatusAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
208
+ new (...args: any[]): {
209
+ status?: string | null
210
+ scanned?: number | null
211
+ candidates?: number | null
212
+ filled?: number | null
213
+ startedAt?: __.CdsTimestamp | null
214
+ finishedAt?: __.CdsTimestamp | null
215
+ error?: string | null
216
+ } & InstanceType<TBase>
217
+ readonly kind: 'type';
218
+ readonly keys: __.KeysOf<DecimalsBackfillStatus>;
219
+ readonly elements: __.ElementsOf<DecimalsBackfillStatus>;
220
+ readonly actions: globalThis.Record<never, never>;
221
+ };
222
+ export class DecimalsBackfillStatus extends _DecimalsBackfillStatusAspect(__.Entity) {
223
+ }
224
+
204
225
  // entity 'BackfillResult'
205
226
  export declare function _BackfillResultAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
206
227
  new (...args: any[]): {
@@ -378,4 +399,14 @@ export declare const backfillPaymentCredentials: {
378
399
  // metadata (do not use)
379
400
  __parameters: globalThis.Record<never, never>, __returns: globalThis.Promise<BackfillResult | null> | BackfillResult | null, __self: never
380
401
  kind: 'action'
402
+ }
403
+
404
+ export declare const backfillAssetDecimals: {
405
+ // positional
406
+ (): globalThis.Promise<BackfillResult | null> | BackfillResult | null
407
+ // named
408
+ ({}: globalThis.Record<never, never>): globalThis.Promise<BackfillResult | null> | BackfillResult | null
409
+ // metadata (do not use)
410
+ __parameters: globalThis.Record<never, never>, __returns: globalThis.Promise<BackfillResult | null> | BackfillResult | null, __self: never
411
+ kind: 'action'
381
412
  }
@@ -25,6 +25,9 @@ module.exports.__Array_TransactionBackfillStatus_ = createEntityProxy(['CardanoI
25
25
  // CredentialBackfillStatus
26
26
  module.exports.CredentialBackfillStatus = createEntityProxy(['CardanoIndexerService', 'CredentialBackfillStatus'], { target: { is_singular: true } })
27
27
  module.exports.__Array_CredentialBackfillStatus_ = createEntityProxy(['CardanoIndexerService', 'CredentialBackfillStatus'], { target: { is_singular: false }})
28
+ // DecimalsBackfillStatus
29
+ module.exports.DecimalsBackfillStatus = createEntityProxy(['CardanoIndexerService', 'DecimalsBackfillStatus'], { target: { is_singular: true } })
30
+ module.exports.__Array_DecimalsBackfillStatus_ = createEntityProxy(['CardanoIndexerService', 'DecimalsBackfillStatus'], { target: { is_singular: false }})
28
31
  // BackfillResult
29
32
  module.exports.BackfillResult = createEntityProxy(['CardanoIndexerService', 'BackfillResult'], { target: { is_singular: true } })
30
33
  module.exports.__Array_BackfillResult_ = createEntityProxy(['CardanoIndexerService', 'BackfillResult'], { target: { is_singular: false }})
@@ -52,4 +55,5 @@ module.exports.importUtxoSet = 'importUtxoSet'
52
55
  module.exports.backfillCertificates = 'backfillCertificates'
53
56
  module.exports.backfillTransactions = 'backfillTransactions'
54
57
  module.exports.backfillPaymentCredentials = 'backfillPaymentCredentials'
58
+ module.exports.backfillAssetDecimals = 'backfillAssetDecimals'
55
59
  // enums
@@ -295,6 +295,7 @@ export declare function _AssetAspect<TBase extends new (...args: any[]) => objec
295
295
  registryName?: string | null
296
296
  registryTicker?: string | null
297
297
  registryDecimals?: number | null
298
+ decimals?: number | null
298
299
  registryDescription?: string | null
299
300
  registryUrl?: string | null
300
301
  registryLogo?: string | null
@@ -218,6 +218,7 @@ export declare function _AssetAspect<TBase extends new (...args: any[]) => objec
218
218
  registryName?: string | null
219
219
  registryTicker?: string | null
220
220
  registryDecimals?: number | null
221
+ decimals?: number | null
221
222
  registryDescription?: string | null
222
223
  registryUrl?: string | null
223
224
  registryLogo?: string | null
package/db/schema.cds CHANGED
@@ -453,6 +453,10 @@ entity Assets : temporal {
453
453
  @description: 'CIP-26 off-chain registry: decimal precision'
454
454
  registryDecimals : Integer;
455
455
 
456
+ @title : 'Decimals'
457
+ @description: 'Decimal places of the token: the decimals field of the CIP-68 reference datum for a unit with label 333 or 444, else the CIP-26 registry value; null when neither is known'
458
+ decimals : Integer;
459
+
456
460
  @title : 'Registry Description'
457
461
  @description: 'CIP-26 off-chain registry: human-readable description'
458
462
  registryDescription : LargeString;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.43",
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
@@ -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;
@@ -1079,6 +1080,8 @@ class CardanoIndexer {
1079
1080
  const newAssets = this.crawlAssetCatalogue === 'off'
1080
1081
  ? 0
1081
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);
1082
1085
  logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
1083
1086
  `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
1084
1087
  }
@@ -1341,6 +1344,8 @@ class CardanoIndexer {
1341
1344
  if (!missing.length)
1342
1345
  return 0;
1343
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);
1344
1349
  // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
1345
1350
  for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
1346
1351
  await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
@@ -1568,6 +1573,7 @@ class CardanoIndexer {
1568
1573
  async indexAsset(tx, unit) {
1569
1574
  const assetInfo = await this.resolveAssetInfo(tx, unit);
1570
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;
1571
1577
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
1572
1578
  return assetEntity;
1573
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
@@ -1,7 +1,8 @@
1
1
  /**
2
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.
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.
5
6
  */
6
7
  export interface CredentialBackfillProgress {
7
8
  /** Table being walked; null when finished. */
@@ -60,7 +60,7 @@ async function fillTable(spec, chunkSize, onChunk) {
60
60
  const decoded = new Map();
61
61
  for (;;) {
62
62
  const done = await cds_1.default.tx(async (tx) => {
63
- const where = { [spec.column]: null };
63
+ const where = {};
64
64
  if (cursor?.within) {
65
65
  where[k1] = cursor.first;
66
66
  where[k2] = { '>': cursor.second };
@@ -68,7 +68,7 @@ async function fillTable(spec, chunkSize, onChunk) {
68
68
  else if (cursor) {
69
69
  where[k1] = { '>': cursor.first };
70
70
  }
71
- const rows = (await tx.run(SELECT.from(spec.entity).columns(k1, k2, spec.address).where(where).orderBy(k1, k2).limit(chunkSize))) ?? [];
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
72
  const wasWithin = cursor?.within ?? false;
73
73
  if (!rows.length) {
74
74
  if (!wasWithin)
@@ -84,6 +84,8 @@ async function fillTable(spec, chunkSize, onChunk) {
84
84
  const complete = full && !allSame ? rows.filter((r) => r[k1] !== lastFirst) : rows;
85
85
  const fills = [];
86
86
  for (const r of complete) {
87
+ if (r[spec.column] != null)
88
+ continue;
87
89
  const address = r[spec.address];
88
90
  if (!address)
89
91
  continue;
@@ -58,6 +58,8 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
58
58
  transactionBackfill : TransactionBackfillStatus;
59
59
  // one-off payment-credential fill of UTxO-shaped rows (this process)
60
60
  credentialBackfill : CredentialBackfillStatus;
61
+ // one-off CIP-68 decimals fill of the asset catalogue (this process)
62
+ decimalsBackfill : DecimalsBackfillStatus;
61
63
  // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
62
64
  epochSnapshots : EpochSnapshotStatus;
63
65
  }
@@ -119,6 +121,18 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
119
121
  error : String;
120
122
  }
121
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
+
122
136
  @title : 'Backfill Result'
123
137
  type BackfillResult {
124
138
  accepted : Boolean;
@@ -225,4 +239,9 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
225
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.'
226
240
  @requires : 'Admin'
227
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;
228
247
  }
@@ -12,6 +12,7 @@ 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
14
  const credential_backfill_1 = require("./blockchain/crawler/credential-backfill");
15
+ const asset_decimals_backfill_1 = require("./blockchain/crawler/asset-decimals-backfill");
15
16
  const validators_1 = require("./utils/validators");
16
17
  const server_1 = require("./server");
17
18
  const liveness_1 = require("./utils/liveness");
@@ -34,6 +35,9 @@ let transactionBackfill = {
34
35
  let credentialBackfill = {
35
36
  status: 'none', table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, startedAt: null, finishedAt: null, error: null,
36
37
  };
38
+ let decimalsBackfill = {
39
+ status: 'none', scanned: 0, candidates: 0, filled: 0, startedAt: null, finishedAt: null, error: null,
40
+ };
37
41
  /** Slot range of a backfill: defaults to crawl start .. cursor, never past the cursor. */
38
42
  async function backfillRange(db, data) {
39
43
  const cursor = await (0, sync_state_1.readCursor)(db);
@@ -137,6 +141,7 @@ module.exports = (srv) => {
137
141
  error: transactionBackfill.error,
138
142
  },
139
143
  credentialBackfill: { ...credentialBackfill },
144
+ decimalsBackfill: { ...decimalsBackfill },
140
145
  epochSnapshots: {
141
146
  enabled: epochSnapshotsConfigured(),
142
147
  source: epochSnapshotSource(),
@@ -256,6 +261,23 @@ module.exports = (srv) => {
256
261
  });
257
262
  return { accepted: true, message: 'Payment-credential backfill started; poll getStatus().credentialBackfill.' };
258
263
  });
264
+ // backfillAssetDecimals — resolves the CIP-68 reference datum of every label-333/444 catalogue
265
+ // unit from the crawled chain. No backend; runs detached, progress via getStatus().decimalsBackfill.
266
+ srv.on('backfillAssetDecimals', async (req) => {
267
+ if (decimalsBackfill.status === 'running')
268
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetDecimals', 'An asset-decimals backfill is already running');
269
+ decimalsBackfill = { status: 'running', scanned: 0, candidates: 0, filled: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
270
+ void (0, asset_decimals_backfill_1.backfillAssetDecimals)({
271
+ onProgress: (p) => { Object.assign(decimalsBackfill, p); },
272
+ })
273
+ .then((r) => { Object.assign(decimalsBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
274
+ .catch((err) => {
275
+ const message = err instanceof Error ? err.message : String(err);
276
+ Object.assign(decimalsBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
277
+ logger.error(`Asset-decimals backfill failed: ${message}`);
278
+ });
279
+ return { accepted: true, message: 'Asset-decimals backfill started; poll getStatus().decimalsBackfill.' };
280
+ });
259
281
  // importUtxoSet — one-off snapshot import that anchors crawler.utxoSet. Validates, then
260
282
  // runs detached; progress via getStatus().utxoSet.
261
283
  srv.on('importUtxoSet', async (req) => {
@@ -0,0 +1,17 @@
1
+ /** CIP-67 asset-name labels of the CIP-68 token classes, as the first 4 bytes of the asset name. */
2
+ export declare const CIP68_LABEL: {
3
+ readonly reference: "000643b0";
4
+ readonly nft: "000de140";
5
+ readonly ft: "0014df10";
6
+ readonly rft: "001bc280";
7
+ };
8
+ /** Reference-NFT unit of a CIP-68 user token with label 333 or 444; null for any other unit. */
9
+ export declare function cip68ReferenceUnit(unit: string): string | null;
10
+ /** The label-333 and label-444 units a CIP-68 reference NFT describes; null for any other unit. */
11
+ export declare function cip68UserUnits(referenceUnit: string): string[] | null;
12
+ /**
13
+ * `decimals` of a CIP-68 reference datum: Constr 0 whose first field is the metadata map, keyed
14
+ * by UTF-8 byte strings. null when the datum has no such integer in 0..255 or is not that shape.
15
+ */
16
+ export declare function cip68DecimalsFromDatum(cborHex: string): number | null;
17
+ //# sourceMappingURL=cip68.d.ts.map
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CIP68_LABEL = void 0;
4
+ exports.cip68ReferenceUnit = cip68ReferenceUnit;
5
+ exports.cip68UserUnits = cip68UserUnits;
6
+ exports.cip68DecimalsFromDatum = cip68DecimalsFromDatum;
7
+ const plutus_data_1 = require("@harmoniclabs/plutus-data");
8
+ /** CIP-67 asset-name labels of the CIP-68 token classes, as the first 4 bytes of the asset name. */
9
+ exports.CIP68_LABEL = {
10
+ reference: '000643b0',
11
+ nft: '000de140',
12
+ ft: '0014df10',
13
+ rft: '001bc280',
14
+ };
15
+ /** Labels whose reference datum may carry `decimals`. */
16
+ const USER_LABELS_WITH_DECIMALS = [exports.CIP68_LABEL.ft, exports.CIP68_LABEL.rft];
17
+ const labelOf = (unit) => unit.slice(56, 64);
18
+ /** Reference-NFT unit of a CIP-68 user token with label 333 or 444; null for any other unit. */
19
+ function cip68ReferenceUnit(unit) {
20
+ if (unit.length < 64 || !USER_LABELS_WITH_DECIMALS.includes(labelOf(unit)))
21
+ return null;
22
+ return unit.slice(0, 56) + exports.CIP68_LABEL.reference + unit.slice(64);
23
+ }
24
+ /** The label-333 and label-444 units a CIP-68 reference NFT describes; null for any other unit. */
25
+ function cip68UserUnits(referenceUnit) {
26
+ if (referenceUnit.length < 64 || labelOf(referenceUnit) !== exports.CIP68_LABEL.reference)
27
+ return null;
28
+ return USER_LABELS_WITH_DECIMALS.map((label) => referenceUnit.slice(0, 56) + label + referenceUnit.slice(64));
29
+ }
30
+ const DECIMALS_KEY = Buffer.from('decimals');
31
+ /**
32
+ * `decimals` of a CIP-68 reference datum: Constr 0 whose first field is the metadata map, keyed
33
+ * by UTF-8 byte strings. null when the datum has no such integer in 0..255 or is not that shape.
34
+ */
35
+ function cip68DecimalsFromDatum(cborHex) {
36
+ let data;
37
+ try {
38
+ data = (0, plutus_data_1.dataFromCbor)(cborHex);
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ if (!(data instanceof plutus_data_1.DataConstr) || data.constr !== 0n)
44
+ return null;
45
+ const metadata = data.fields[0];
46
+ if (!(metadata instanceof plutus_data_1.DataMap))
47
+ return null;
48
+ for (const kv of metadata.map) {
49
+ if (!(kv.fst instanceof plutus_data_1.DataB) || !DECIMALS_KEY.equals(Buffer.from(kv.fst.bytes)))
50
+ continue;
51
+ if (!(kv.snd instanceof plutus_data_1.DataI))
52
+ return null;
53
+ const n = kv.snd.int;
54
+ return n >= 0n && n <= 255n ? Number(n) : null;
55
+ }
56
+ return null;
57
+ }
58
+ //# sourceMappingURL=cip68.js.map
@@ -1,3 +1,4 @@
1
1
  export { parseTransaction, type ParsedTransaction, type ParsedInput, type ParsedOutput, type ParsedAsset, type ParsedWitnesses, type ParsedWithdrawal, type ParsedCertificate, } from './parse';
2
2
  export { decodePlutusData, plutusDataToJson, type PlutusDataJson } from './plutus-data-json';
3
+ export { CIP68_LABEL, cip68ReferenceUnit, cip68UserUnits, cip68DecimalsFromDatum } from './cip68';
3
4
  //# sourceMappingURL=index.d.ts.map
package/srv/cbor/index.js CHANGED
@@ -1,9 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.plutusDataToJson = exports.decodePlutusData = exports.parseTransaction = void 0;
3
+ exports.cip68DecimalsFromDatum = exports.cip68UserUnits = exports.cip68ReferenceUnit = exports.CIP68_LABEL = exports.plutusDataToJson = exports.decodePlutusData = exports.parseTransaction = void 0;
4
4
  var parse_1 = require("./parse");
5
5
  Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return parse_1.parseTransaction; } });
6
6
  var plutus_data_json_1 = require("./plutus-data-json");
7
7
  Object.defineProperty(exports, "decodePlutusData", { enumerable: true, get: function () { return plutus_data_json_1.decodePlutusData; } });
8
8
  Object.defineProperty(exports, "plutusDataToJson", { enumerable: true, get: function () { return plutus_data_json_1.plutusDataToJson; } });
9
+ var cip68_1 = require("./cip68");
10
+ Object.defineProperty(exports, "CIP68_LABEL", { enumerable: true, get: function () { return cip68_1.CIP68_LABEL; } });
11
+ Object.defineProperty(exports, "cip68ReferenceUnit", { enumerable: true, get: function () { return cip68_1.cip68ReferenceUnit; } });
12
+ Object.defineProperty(exports, "cip68UserUnits", { enumerable: true, get: function () { return cip68_1.cip68UserUnits; } });
13
+ Object.defineProperty(exports, "cip68DecimalsFromDatum", { enumerable: true, get: function () { return cip68_1.cip68DecimalsFromDatum; } });
9
14
  //# sourceMappingURL=index.js.map
@@ -590,6 +590,8 @@ function mapAsset(providerAssetInfo, max_age) {
590
590
  registryName: providerAssetInfo.registryName,
591
591
  registryTicker: providerAssetInfo.registryTicker,
592
592
  registryDecimals: providerAssetInfo.registryDecimals,
593
+ // the registry value until the caller resolves a CIP-68 reference datum
594
+ decimals: providerAssetInfo.registryDecimals,
593
595
  registryDescription: providerAssetInfo.registryDescription,
594
596
  registryUrl: providerAssetInfo.registryUrl,
595
597
  registryLogo: providerAssetInfo.registryLogo,
@@ -629,6 +631,7 @@ function mapBareAsset(unit) {
629
631
  registryName: null,
630
632
  registryTicker: null,
631
633
  registryDecimals: null,
634
+ decimals: null,
632
635
  registryDescription: null,
633
636
  registryUrl: null,
634
637
  registryLogo: null,