@odatano/core 2.0.0-rc.47 → 2.0.0-rc.49

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.
@@ -12,6 +12,7 @@ export default class {
12
12
  static readonly backfillTransactions: typeof backfillTransactions;
13
13
  static readonly backfillPaymentCredentials: typeof backfillPaymentCredentials;
14
14
  static readonly backfillAssetDecimals: typeof backfillAssetDecimals;
15
+ static readonly backfillAssetRegistry: typeof backfillAssetRegistry;
15
16
  }
16
17
 
17
18
  // entity 'SyncState'
@@ -93,6 +94,7 @@ export declare function _CrawlerStatusAspect<TBase extends new (...args: any[])
93
94
  transactionBackfill?: TransactionBackfillStatus | null
94
95
  credentialBackfill?: CredentialBackfillStatus | null
95
96
  decimalsBackfill?: DecimalsBackfillStatus | null
97
+ registryBackfill?: RegistryBackfillStatus | null
96
98
  epochSnapshots?: EpochSnapshotStatus | null
97
99
  } & InstanceType<TBase>
98
100
  readonly kind: 'type';
@@ -207,6 +209,26 @@ export declare function _DecimalsBackfillStatusAspect<TBase extends new (...args
207
209
  export class DecimalsBackfillStatus extends _DecimalsBackfillStatusAspect(__.Entity) {
208
210
  }
209
211
 
212
+ // entity 'RegistryBackfillStatus'
213
+ export declare function _RegistryBackfillStatusAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
214
+ new (...args: any[]): {
215
+ status?: string | null
216
+ units?: number | null
217
+ processed?: number | null
218
+ filled?: number | null
219
+ failed?: number | null
220
+ startedAt?: __.CdsTimestamp | null
221
+ finishedAt?: __.CdsTimestamp | null
222
+ error?: string | null
223
+ } & InstanceType<TBase>
224
+ readonly kind: 'type';
225
+ readonly keys: __.KeysOf<RegistryBackfillStatus>;
226
+ readonly elements: __.ElementsOf<RegistryBackfillStatus>;
227
+ readonly actions: globalThis.Record<never, never>;
228
+ };
229
+ export class RegistryBackfillStatus extends _RegistryBackfillStatusAspect(__.Entity) {
230
+ }
231
+
210
232
  // entity 'BackfillResult'
211
233
  export declare function _BackfillResultAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
212
234
  new (...args: any[]): {
@@ -394,4 +416,14 @@ export declare const backfillAssetDecimals: {
394
416
  // metadata (do not use)
395
417
  __parameters: globalThis.Record<never, never>, __returns: globalThis.Promise<BackfillResult | null> | BackfillResult | null, __self: never
396
418
  kind: 'action'
419
+ }
420
+
421
+ export declare const backfillAssetRegistry: {
422
+ // positional
423
+ (): globalThis.Promise<BackfillResult | null> | BackfillResult | null
424
+ // named
425
+ ({}: globalThis.Record<never, never>): globalThis.Promise<BackfillResult | null> | BackfillResult | null
426
+ // metadata (do not use)
427
+ __parameters: globalThis.Record<never, never>, __returns: globalThis.Promise<BackfillResult | null> | BackfillResult | null, __self: never
428
+ kind: 'action'
397
429
  }
@@ -28,6 +28,9 @@ module.exports.__Array_CredentialBackfillStatus_ = createEntityProxy(['CardanoIn
28
28
  // DecimalsBackfillStatus
29
29
  module.exports.DecimalsBackfillStatus = createEntityProxy(['CardanoIndexerService', 'DecimalsBackfillStatus'], { target: { is_singular: true } })
30
30
  module.exports.__Array_DecimalsBackfillStatus_ = createEntityProxy(['CardanoIndexerService', 'DecimalsBackfillStatus'], { target: { is_singular: false }})
31
+ // RegistryBackfillStatus
32
+ module.exports.RegistryBackfillStatus = createEntityProxy(['CardanoIndexerService', 'RegistryBackfillStatus'], { target: { is_singular: true } })
33
+ module.exports.__Array_RegistryBackfillStatus_ = createEntityProxy(['CardanoIndexerService', 'RegistryBackfillStatus'], { target: { is_singular: false }})
31
34
  // BackfillResult
32
35
  module.exports.BackfillResult = createEntityProxy(['CardanoIndexerService', 'BackfillResult'], { target: { is_singular: true } })
33
36
  module.exports.__Array_BackfillResult_ = createEntityProxy(['CardanoIndexerService', 'BackfillResult'], { target: { is_singular: false }})
@@ -56,4 +59,5 @@ module.exports.backfillCertificates = 'backfillCertificates'
56
59
  module.exports.backfillTransactions = 'backfillTransactions'
57
60
  module.exports.backfillPaymentCredentials = 'backfillPaymentCredentials'
58
61
  module.exports.backfillAssetDecimals = 'backfillAssetDecimals'
62
+ module.exports.backfillAssetRegistry = 'backfillAssetRegistry'
59
63
  // enums
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.47",
3
+ "version": "2.0.0-rc.49",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -133,6 +133,12 @@ export interface EpochStateBackend extends CardanoBackend {
133
133
  }
134
134
  /** Type guard: can this backend read epoch state at a block? */
135
135
  export declare function isEpochStateBackend(backend: CardanoBackend): backend is EpochStateBackend;
136
+ export interface TokenRegistryBackend extends CardanoBackend {
137
+ /** Units (policyId + assetNameHex) that have a registry entry. */
138
+ getTokenRegistryUnits(): Promise<string[]>;
139
+ }
140
+ /** Type guard: can this backend list the token registry? */
141
+ export declare function isTokenRegistryBackend(backend: CardanoBackend): backend is TokenRegistryBackend;
136
142
  /** Type guard: can this backend enumerate pools and DReps? */
137
143
  export declare function isEnumeratingBackend(backend: CardanoBackend): backend is EnumeratingBackend;
138
144
  //# sourceMappingURL=cardano-backend.d.ts.map
@@ -5,6 +5,7 @@ exports.isChainSyncBackend = isChainSyncBackend;
5
5
  exports.isLedgerStateBackend = isLedgerStateBackend;
6
6
  exports.isPaginatingBackend = isPaginatingBackend;
7
7
  exports.isEpochStateBackend = isEpochStateBackend;
8
+ exports.isTokenRegistryBackend = isTokenRegistryBackend;
8
9
  exports.isEnumeratingBackend = isEnumeratingBackend;
9
10
  /** Type guard: does this backend support transaction evaluation? */
10
11
  function isEvaluatingBackend(backend) {
@@ -28,6 +29,10 @@ function isPaginatingBackend(backend) {
28
29
  function isEpochStateBackend(backend) {
29
30
  return typeof backend.epochStateAt === 'function';
30
31
  }
32
+ /** Type guard: can this backend list the token registry? */
33
+ function isTokenRegistryBackend(backend) {
34
+ return typeof backend.getTokenRegistryUnits === 'function';
35
+ }
31
36
  /** Type guard: can this backend enumerate pools and DReps? */
32
37
  function isEnumeratingBackend(backend) {
33
38
  const b = backend;
@@ -1,4 +1,4 @@
1
- import { CardanoBackend, PaginatingBackend, EnumeratingBackend } from './cardano-backend';
1
+ import { CardanoBackend, PaginatingBackend, EnumeratingBackend, TokenRegistryBackend } from './cardano-backend';
2
2
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, TxCertificate } from '../../utils/types';
3
3
  import { Network } from '../cardano-client';
4
4
  /** Shape of a Koios tx-in/tx-out row from /tx_info */
@@ -60,7 +60,7 @@ interface KoiosTxInfo {
60
60
  }> | null;
61
61
  }
62
62
  /** CardanoBackend implementation on the Koios REST API (Axios). */
63
- export declare class KoiosBackend implements CardanoBackend, PaginatingBackend, EnumeratingBackend {
63
+ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend, EnumeratingBackend, TokenRegistryBackend {
64
64
  readonly name = "koios";
65
65
  private api;
66
66
  private network;
@@ -120,6 +120,8 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
120
120
  private static readonly LIST_MAX_PAGES;
121
121
  /** Pages through a PostgREST list endpoint for one id column. Stops on the first short page. */
122
122
  private listAllIds;
123
+ /** Units with a CIP-26 registry entry, from `asset_token_registry` (the whole registry, paged). */
124
+ getTokenRegistryUnits(): Promise<string[]>;
123
125
  /** All pool ids, including retired ones, so a snapshot does not drop retiring pools. */
124
126
  getPoolIds(): Promise<string[]>;
125
127
  /** Resolve pool ids in batches. Ids Koios does not return are omitted, never filled with empty rows. */
@@ -871,6 +871,31 @@ class KoiosBackend {
871
871
  logger.warn(`${label}: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages, the list may be truncated`);
872
872
  return ids;
873
873
  }
874
+ /** Units with a CIP-26 registry entry, from `asset_token_registry` (the whole registry, paged). */
875
+ async getTokenRegistryUnits() {
876
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
877
+ const units = [];
878
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
879
+ const offset = page * KoiosBackend.LIST_PAGE_SIZE;
880
+ const { data } = await this.getWithRetryOn42804(`/asset_token_registry?select=policy_id,asset_name&limit=${KoiosBackend.LIST_PAGE_SIZE}&offset=${offset}`, {}, 'getTokenRegistryUnits');
881
+ if (!Array.isArray(data) || data.length === 0)
882
+ return units;
883
+ for (const row of data) {
884
+ const r = row;
885
+ if (typeof r.policy_id !== 'string' || !/^[0-9a-f]{56}$/i.test(r.policy_id))
886
+ continue;
887
+ const name = typeof r.asset_name === 'string' ? r.asset_name : '';
888
+ if (!/^([0-9a-f]{2}){0,32}$/i.test(name))
889
+ continue;
890
+ units.push((r.policy_id + name).toLowerCase());
891
+ }
892
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
893
+ return units;
894
+ }
895
+ logger.warn(`getTokenRegistryUnits: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages, the list may be truncated`);
896
+ return units;
897
+ }, this.name);
898
+ }
874
899
  /** All pool ids, including retired ones, so a snapshot does not drop retiring pools. */
875
900
  async getPoolIds() {
876
901
  return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OdatanoBackend = exports.ODATANO_API_URLS = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const axios_1 = __importDefault(require("axios"));
9
- const client_1 = require("@cardano-ogmios/client");
9
+ const deep_json_1 = require("../../utils/deep-json");
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
12
  const logger = cds_1.default.log('OdatanoBackend');
@@ -117,7 +117,7 @@ class OdatanoBackend {
117
117
  }
118
118
  return out;
119
119
  }
120
- // POSTs one operation and parses the JSON answer with safeJSON to keep big integers.
120
+ // POSTs one operation and parses the JSON answer with exact big integers.
121
121
  // The remote error message stays verbatim, so `CHAIN_POINT_MISMATCH:` reaches the crawler.
122
122
  async call(operation, body = {}) {
123
123
  try {
@@ -126,7 +126,7 @@ class OdatanoBackend {
126
126
  if (Number.isFinite(left))
127
127
  this.unitsLeft = left;
128
128
  const value = res.data?.value;
129
- return (typeof value === 'string' ? client_1.safeJSON.parse(value) : value);
129
+ return (typeof value === 'string' ? (0, deep_json_1.parseJson)(value) : value);
130
130
  }
131
131
  catch (err) {
132
132
  throw this.mapError(operation, err);
@@ -8,8 +8,6 @@ export interface UnparseableFrame {
8
8
  reason: string;
9
9
  bytes: number;
10
10
  }
11
- /** Quote integers beyond 2^53 so `JSON.parse` cannot round them. One pass, no recursion. */
12
- export declare function widenBigIntegers(text: string): string;
13
11
  export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): () => void;
14
12
  /** Tests only: drop the wrapper so each case starts from the untouched client. */
15
13
  export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
@@ -3,68 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.widenBigIntegers = widenBigIntegers;
7
6
  exports.installOgmiosFrameGuard = installOgmiosFrameGuard;
8
7
  exports.resetOgmiosFrameGuardForTests = resetOgmiosFrameGuardForTests;
9
- // The Ogmios client's `safeJSON.parse` recurses per nesting level. A deeply nested native script
10
- // overflows the stack in a socket handler and ends the process, so on RangeError we use `JSON.parse`.
8
+ // The Ogmios client's `safeJSON.parse` recurses per nesting level and refuses a "__proto__" key.
9
+ // Either throw lands in a socket handler and ends the process, so such frames are parsed here.
11
10
  const client_1 = require("@cardano-ogmios/client");
12
11
  const cds_1 = __importDefault(require("@sap/cds"));
12
+ const deep_json_1 = require("../../utils/deep-json");
13
13
  const logger = cds_1.default.log('OgmiosFrameGuard');
14
- /** Quote integers beyond 2^53 so `JSON.parse` cannot round them. One pass, no recursion. */
15
- function widenBigIntegers(text) {
16
- const SAFE_DIGITS = String(Number.MAX_SAFE_INTEGER).length; // 16
17
- let out = '';
18
- let last = 0;
19
- let inString = false;
20
- let escaped = false;
21
- for (let i = 0; i < text.length; i++) {
22
- const c = text[i];
23
- if (inString) {
24
- if (escaped)
25
- escaped = false;
26
- else if (c === '\\')
27
- escaped = true;
28
- else if (c === '"')
29
- inString = false;
30
- continue;
31
- }
32
- if (c === '"') {
33
- inString = true;
34
- continue;
35
- }
36
- // a number literal starts here only after a structural character
37
- if (c !== '-' && (c < '0' || c > '9'))
38
- continue;
39
- const prev = text[i - 1];
40
- if (prev !== ':' && prev !== ',' && prev !== '[' && prev !== ' ' && prev !== '\n' && prev !== '\t' && prev !== '\r')
41
- continue;
42
- let j = i;
43
- if (text[j] === '-')
44
- j++;
45
- const digitsFrom = j;
46
- while (j < text.length && text[j] >= '0' && text[j] <= '9')
47
- j++;
48
- const digits = j - digitsFrom;
49
- if (digits === 0)
50
- continue;
51
- // a fraction or exponent means it was never an exact integer
52
- const after = text[j];
53
- if (after === '.' || after === 'e' || after === 'E') {
54
- i = j;
55
- continue;
56
- }
57
- if (digits >= SAFE_DIGITS) {
58
- const literal = text.slice(i, j);
59
- if (!Number.isSafeInteger(Number(literal))) {
60
- out += text.slice(last, i) + '"' + literal + '"';
61
- last = j;
62
- }
63
- }
64
- i = j - 1;
65
- }
66
- return last === 0 ? text : out + text.slice(last);
67
- }
68
14
  /** Block height/id from the front of an unparseable frame, to name the block in logs and `lastError`. */
69
15
  function readBlockHeader(text) {
70
16
  const head = text.slice(0, 4096);
@@ -74,6 +20,17 @@ function readBlockHeader(text) {
74
20
  }
75
21
  let installed = false;
76
22
  const reporters = new Set();
23
+ // Why the client's parser gave up, or null for a genuine syntax error. json-bigint throws a plain
24
+ // object named SyntaxError for a "__proto__" key; the client only rewrites the "constructor" case.
25
+ function fallbackReason(err) {
26
+ if (err instanceof RangeError)
27
+ return "too deeply nested for the client's parser";
28
+ const e = err;
29
+ if (e?.name === 'SyntaxError' && typeof e.message === 'string' && e.message.includes('forbidden prototype')) {
30
+ return 'carries a "__proto__" key the client\'s parser refuses';
31
+ }
32
+ return null;
33
+ }
77
34
  // Wraps `safeJSON.parse` once per process and returns an unregister function. The parser is shared
78
35
  // by all chain-sync sockets, so an unusable frame goes to every callback. That stream then stalls.
79
36
  function installOgmiosFrameGuard(onUnparseableFrame) {
@@ -88,15 +45,17 @@ function installOgmiosFrameGuard(onUnparseableFrame) {
88
45
  return original(raw);
89
46
  }
90
47
  catch (err) {
91
- if (!(err instanceof RangeError))
48
+ const why = fallbackReason(err);
49
+ if (why === null)
92
50
  throw err; // a genuine syntax error stays a syntax error
93
51
  const text = String(raw);
94
52
  const where = readBlockHeader(text);
95
53
  try {
96
- const parsed = JSON.parse(widenBigIntegers(text));
97
- logger.warn(`chain-sync frame too deeply nested for the client's parser (block ${where.height ?? '?'} ` +
98
- `${where.id ?? ''}, ${text.length} bytes), parsed without it. Integers beyond 2^53 are ` +
99
- `strings on this path; the chain-sync mapper stringifies them anyway.`);
54
+ // Without the client's bigint pass (it recurses too), so short integers stay numbers here.
55
+ // Every reader of a quantity stringifies it, so the two shapes are read the same way.
56
+ const parsed = (0, deep_json_1.parseJson)(text);
57
+ logger.warn(`chain-sync frame ${why} (block ${where.height ?? '?'} ${where.id ?? ''}, ${text.length} bytes), ` +
58
+ 'parsed without it.');
100
59
  return parsed;
101
60
  }
102
61
  catch (fallbackErr) {
@@ -1,4 +1,4 @@
1
- import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend } from './backends/cardano-backend';
1
+ import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend, TokenRegistryBackend } from './backends/cardano-backend';
2
2
  import { PendingSpends } from './pending-spends';
3
3
  import { type CircuitBreakerConfig } from './circuit-breaker';
4
4
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
@@ -107,6 +107,8 @@ export declare class CardanoClient {
107
107
  getEpochStateBackend(): EpochStateBackend | null;
108
108
  /** Without one, epoch snapshots stay off instead of making thousands of single requests. */
109
109
  getEnumeratingBackend(): EnumeratingBackend | null;
110
+ /** Backend that lists the CIP-26 token registry (Koios). Null when none is configured. */
111
+ getTokenRegistryBackend(): TokenRegistryBackend | null;
110
112
  /** Prefers Koios, because it batches 100 txs per call and Blockfrost needs about 3 calls per tx. */
111
113
  getPaginatingBackend(): PaginatingBackend | null;
112
114
  /** Protocol parameters with a 5-minute in-memory cache and coalesced refresh. */
@@ -487,6 +487,15 @@ class CardanoClient {
487
487
  }
488
488
  return null;
489
489
  }
490
+ /** Backend that lists the CIP-26 token registry (Koios). Null when none is configured. */
491
+ getTokenRegistryBackend() {
492
+ const candidates = [...this.historicalBackends, this.liveBackend];
493
+ for (const b of candidates) {
494
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isTokenRegistryBackend)(b))
495
+ return b;
496
+ }
497
+ return null;
498
+ }
490
499
  /** Prefers Koios, because it batches 100 txs per call and Blockfrost needs about 3 calls per tx. */
491
500
  getPaginatingBackend() {
492
501
  const usable = this.historicalBackends.filter((b) => !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isPaginatingBackend)(b));
@@ -173,6 +173,9 @@ export declare class CardanoIndexer {
173
173
  resolvePool(tx: CapTransaction, poolId: string): Promise<PoolData>;
174
174
  /** Index an asset by unit (policyId + assetNameHex). */
175
175
  indexAsset(tx: CapTransaction, unit: string): Promise<Asset>;
176
+ /** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
177
+ indexAssetFromBackend(tx: CapTransaction, unit: string): Promise<Asset>;
178
+ private writeAsset;
176
179
  /** Always fresh. Rows are keyed by unit and tx, so older cached entries persist. */
177
180
  indexAssetHistory(tx: CapTransaction, unit: string, limit?: number): Promise<AssetHistory[]>;
178
181
  /** Build a transaction and persist the build result with inputs/outputs/address association. */
@@ -14,6 +14,7 @@ const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const mappers_1 = require("../utils/mappers");
15
15
  const errors_1 = require("../utils/errors");
16
16
  const collections_1 = require("../utils/collections");
17
+ const deep_json_1 = require("../utils/deep-json");
17
18
  const transaction_rows_1 = require("./transaction-rows");
18
19
  const ledger_state_1 = require("./ledger-state");
19
20
  const sync_state_1 = require("./crawler/sync-state");
@@ -175,7 +176,7 @@ class CardanoIndexer {
175
176
  const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
176
177
  if (meta?.payload) {
177
178
  try {
178
- onchainMetadata = JSON.parse(meta.payload);
179
+ onchainMetadata = (0, deep_json_1.parseJson)(meta.payload);
179
180
  }
180
181
  catch { /* unparseable payload: leave empty */ }
181
182
  }
@@ -1487,7 +1488,13 @@ class CardanoIndexer {
1487
1488
  }
1488
1489
  /** Index an asset by unit (policyId + assetNameHex). */
1489
1490
  async indexAsset(tx, unit) {
1490
- const assetInfo = await this.resolveAssetInfo(tx, unit);
1491
+ return this.writeAsset(tx, unit, await this.resolveAssetInfo(tx, unit));
1492
+ }
1493
+ /** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
1494
+ async indexAssetFromBackend(tx, unit) {
1495
+ return this.writeAsset(tx, unit, await this.client.getAssetInfo(unit));
1496
+ }
1497
+ async writeAsset(tx, unit, assetInfo) {
1491
1498
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1492
1499
  assetEntity.decimals = (await (0, asset_decimals_1.cip68Decimals)(tx, unit, assetInfo.initialMintTxHash)) ?? assetInfo.registryDecimals;
1493
1500
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
@@ -0,0 +1,21 @@
1
+ import type { CardanoClient } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ export interface RegistryBackfillProgress {
4
+ /** Units with a CIP-26 registry entry. */
5
+ units: number;
6
+ /** Units handled so far, filled or failed. */
7
+ processed: number;
8
+ /** Units whose Assets rows received the registry values. */
9
+ filled: number;
10
+ /** Units the backend did not resolve. */
11
+ failed: number;
12
+ }
13
+ export interface RegistryBackfillOptions {
14
+ client: CardanoClient;
15
+ indexer: CardanoIndexer;
16
+ /** Backend calls per second; one unit is one call. */
17
+ unitsPerSecond?: number;
18
+ onProgress?: (p: RegistryBackfillProgress) => void;
19
+ }
20
+ export declare function backfillAssetRegistry(opts: RegistryBackfillOptions): Promise<RegistryBackfillProgress>;
21
+ //# sourceMappingURL=asset-registry-backfill.d.ts.map
@@ -0,0 +1,63 @@
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.backfillAssetRegistry = backfillAssetRegistry;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const cardano_1 = require("#cds-models/odatano/cardano");
9
+ const errors_1 = require("../../utils/errors");
10
+ const { UPDATE } = cds_1.default.ql;
11
+ const logger = cds_1.default.log('RegistryBackfill');
12
+ /** The run stops when this many units in a row fail: the backend is down, not the units. */
13
+ const MAX_CONSECUTIVE_FAILURES = 25;
14
+ // Fill the CIP-26 registry fields of every Assets slice for the units the registry lists. The
15
+ // registry is off-chain, so each unit is read from the backend; a repeat run refreshes the values.
16
+ async function backfillAssetRegistry(opts) {
17
+ const backend = opts.client.getTokenRegistryBackend();
18
+ if (!backend)
19
+ throw new errors_1.ProviderUnavailableError('No backend lists the token registry (needs Koios)');
20
+ const units = await backend.getTokenRegistryUnits();
21
+ const intervalMs = 1000 / Math.max(1, opts.unitsPerSecond ?? 4);
22
+ const progress = { units: units.length, processed: 0, filled: 0, failed: 0 };
23
+ let consecutiveFailures = 0;
24
+ for (const unit of units) {
25
+ const started = Date.now();
26
+ try {
27
+ await cds_1.default.tx(async (tx) => {
28
+ const row = await opts.indexer.indexAssetFromBackend(tx, unit);
29
+ // Every slice of the unit carries the registry values, the bare catalogue row included.
30
+ await tx.run(UPDATE.entity(cardano_1.Assets).set({
31
+ registryName: row.registryName ?? null,
32
+ registryTicker: row.registryTicker ?? null,
33
+ registryDecimals: row.registryDecimals ?? null,
34
+ registryDescription: row.registryDescription ?? null,
35
+ registryUrl: row.registryUrl ?? null,
36
+ registryLogo: row.registryLogo ?? null,
37
+ }).where({ unit }));
38
+ if (row.decimals != null) {
39
+ await tx.run(UPDATE.entity(cardano_1.Assets).set({ decimals: row.decimals }).where({ unit, decimals: null }));
40
+ }
41
+ });
42
+ progress.filled++;
43
+ consecutiveFailures = 0;
44
+ }
45
+ catch (err) {
46
+ progress.failed++;
47
+ consecutiveFailures++;
48
+ logger.debug(`registry fill for ${unit} failed:`, err);
49
+ if (!(err instanceof errors_1.NotFoundError) && consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
50
+ const last = err instanceof Error ? err.message : String(err);
51
+ throw new errors_1.ProviderUnavailableError(`${consecutiveFailures} units in a row failed, last: ${last}`);
52
+ }
53
+ }
54
+ progress.processed++;
55
+ opts.onProgress?.({ ...progress });
56
+ const wait = intervalMs - (Date.now() - started);
57
+ if (wait > 0)
58
+ await new Promise((r) => setTimeout(r, wait));
59
+ }
60
+ logger.info(`asset registry filled: ${progress.filled} of ${progress.units} registered units, ${progress.failed} failed`);
61
+ return progress;
62
+ }
63
+ //# sourceMappingURL=asset-registry-backfill.js.map
@@ -37,14 +37,12 @@ export interface UtxoSetImportResult {
37
37
  /** `cardano-cli query utxo` value: `{ lovelace: n, [policyId]: { [assetNameHex]: qty } }`. */
38
38
  export interface CliUtxoValue {
39
39
  address: string;
40
- value: Record<string, number | string | Record<string, number | string>>;
40
+ value: Record<string, number | bigint | string | Record<string, number | bigint | string>>;
41
41
  datumhash?: string | null;
42
42
  datumHash?: string | null;
43
43
  inlineDatumRaw?: string | null;
44
44
  referenceScript?: unknown;
45
45
  }
46
- /** `JSON.parse` that quotes integer literals first, so quantities above 2^53 are never rounded. */
47
- export declare function parseJsonLossless<T = unknown>(text: string): T;
48
46
  /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
49
47
  export declare function parseCliUtxoEntry(key: string, value: CliUtxoValue | null | undefined): UtxoSetEntry | null;
50
48
  /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
@@ -4,7 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.UtxoSetLeaseLostError = exports.UtxoSetImportError = void 0;
7
- exports.parseJsonLossless = parseJsonLossless;
8
7
  exports.parseCliUtxoEntry = parseCliUtxoEntry;
9
8
  exports.readUtxoSetFile = readUtxoSetFile;
10
9
  exports.aggregateStatements = aggregateStatements;
@@ -16,6 +15,7 @@ const node_fs_1 = require("node:fs");
16
15
  const promises_1 = require("node:fs/promises");
17
16
  const node_readline_1 = require("node:readline");
18
17
  const reference_script_1 = require("../../utils/reference-script");
18
+ const deep_json_1 = require("../../utils/deep-json");
19
19
  const ledger_state_1 = require("../ledger-state");
20
20
  const sync_state_1 = require("./sync-state");
21
21
  const cardano_1 = require("#cds-models/odatano/cardano");
@@ -39,12 +39,6 @@ class UtxoSetLeaseLostError extends UtxoSetImportError {
39
39
  }
40
40
  }
41
41
  exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
42
- /** `JSON.parse` that quotes integer literals first, so quantities above 2^53 are never rounded. */
43
- function parseJsonLossless(text) {
44
- // string literals pass through untouched; floats keep their JSON meaning
45
- const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
46
- return JSON.parse(rewritten);
47
- }
48
42
  /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
49
43
  function parseCliUtxoEntry(key, value) {
50
44
  const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
@@ -80,7 +74,7 @@ function parseCliUtxoEntry(key, value) {
80
74
  /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
81
75
  async function* readUtxoSetFile(filePath) {
82
76
  if (/\.json$/i.test(filePath)) {
83
- const parsed = parseJsonLossless(await (0, promises_1.readFile)(filePath, 'utf8'));
77
+ const parsed = (0, deep_json_1.parseJson)(await (0, promises_1.readFile)(filePath, 'utf8'));
84
78
  for (const [key, value] of Object.entries(parsed)) {
85
79
  const entry = parseCliUtxoEntry(key, value);
86
80
  if (entry)
@@ -93,7 +87,7 @@ async function* readUtxoSetFile(filePath) {
93
87
  const trimmed = line.trim();
94
88
  if (!trimmed)
95
89
  continue;
96
- const obj = parseJsonLossless(trimmed);
90
+ const obj = (0, deep_json_1.parseJson)(trimmed);
97
91
  if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
98
92
  const entry = parseCliUtxoEntry(obj.key, obj.value);
99
93
  if (entry)
@@ -12,7 +12,7 @@ exports.readTransactionsByHash = readTransactionsByHash;
12
12
  exports.readBlockTransactions = readBlockTransactions;
13
13
  exports.readTransactionMetadata = readTransactionMetadata;
14
14
  const cds_1 = __importDefault(require("@sap/cds"));
15
- const client_1 = require("@cardano-ogmios/client");
15
+ const deep_json_1 = require("../utils/deep-json");
16
16
  const cardano_1 = require("#cds-models/odatano/cardano");
17
17
  const collections_1 = require("../utils/collections");
18
18
  const { SELECT } = cds_1.default.ql;
@@ -95,7 +95,7 @@ function metadataRow(r) {
95
95
  return {
96
96
  txHash: str(r.tx_hash),
97
97
  label: str(r.label),
98
- json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
98
+ json: r.payload == null ? undefined : (0, deep_json_1.parseJson)(String(r.payload)),
99
99
  };
100
100
  }
101
101
  /** Amount list with lovelace first, as the providers deliver it. */
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const cds_1 = __importDefault(require("@sap/cds"));
7
- const client_1 = require("@cardano-ogmios/client");
7
+ const deep_json_1 = require("./utils/deep-json");
8
8
  const backend_request_handler_1 = require("./utils/backend-request-handler");
9
9
  const errors_1 = require("./utils/errors");
10
10
  const validators_1 = require("./utils/validators");
@@ -23,7 +23,7 @@ module.exports = (srv) => {
23
23
  srv.on(name, async (req) => {
24
24
  const data = (req.data ?? {});
25
25
  validate?.(req, data);
26
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => client_1.safeJSON.stringify(toPlain(await run(data, db))));
26
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => (0, deep_json_1.stringifyJson)(toPlain(await run(data, db))));
27
27
  });
28
28
  };
29
29
  // --- validation helpers ----------------------------------------------------------------------
@@ -44,6 +44,8 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
44
44
  credentialBackfill : CredentialBackfillStatus;
45
45
  // one-off CIP-68 decimals fill of the asset catalogue (this process)
46
46
  decimalsBackfill : DecimalsBackfillStatus;
47
+ // one-off CIP-26 registry fill of the asset catalogue (this process)
48
+ registryBackfill : RegistryBackfillStatus;
47
49
  // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
48
50
  epochSnapshots : EpochSnapshotStatus;
49
51
  }
@@ -117,6 +119,19 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
117
119
  error : String;
118
120
  }
119
121
 
122
+ @title : 'Registry Backfill Status'
123
+ @description: 'Progress of the CIP-26 registry fill started with backfillAssetRegistry; process-local, none after a restart'
124
+ type RegistryBackfillStatus {
125
+ status : String; // none | running | done | failed
126
+ units : Integer64; // units with a registry entry
127
+ processed : Integer64; // units handled so far
128
+ filled : Integer64; // units whose rows received the registry values
129
+ failed : Integer64; // units the backend did not resolve
130
+ startedAt : Timestamp;
131
+ finishedAt : Timestamp;
132
+ error : String;
133
+ }
134
+
120
135
  @title : 'Backfill Result'
121
136
  type BackfillResult {
122
137
  accepted : Boolean;
@@ -223,4 +238,9 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
223
238
  @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.'
224
239
  @requires : 'Admin'
225
240
  action backfillAssetDecimals() returns BackfillResult;
241
+
242
+ @title : 'Backfill Asset Registry'
243
+ @description: 'Fill the CIP-26 registry fields (registryName, registryTicker, registryDecimals, registryDescription, registryUrl, registryLogo) on every slice of every Assets unit the token registry lists, and decimals where it is still empty. The registry is off-chain, so each unit is read from the backend (needs Koios), rate limited; the crawler may keep running; a repeat refreshes the values. Runs in the background; progress via getStatus().registryBackfill.'
244
+ @requires : 'Admin'
245
+ action backfillAssetRegistry() returns BackfillResult;
226
246
  }
@@ -15,6 +15,7 @@ const certificate_backfill_1 = require("./blockchain/crawler/certificate-backfil
15
15
  const transaction_backfill_1 = require("./blockchain/crawler/transaction-backfill");
16
16
  const credential_backfill_1 = require("./blockchain/crawler/credential-backfill");
17
17
  const asset_decimals_backfill_1 = require("./blockchain/crawler/asset-decimals-backfill");
18
+ const asset_registry_backfill_1 = require("./blockchain/crawler/asset-registry-backfill");
18
19
  const validators_1 = require("./utils/validators");
19
20
  const server_1 = require("./server");
20
21
  const liveness_1 = require("./utils/liveness");
@@ -40,6 +41,9 @@ let credentialBackfill = {
40
41
  let decimalsBackfill = {
41
42
  status: 'none', scanned: 0, candidates: 0, filled: 0, startedAt: null, finishedAt: null, error: null,
42
43
  };
44
+ let registryBackfill = {
45
+ status: 'none', units: 0, processed: 0, filled: 0, failed: 0, startedAt: null, finishedAt: null, error: null,
46
+ };
43
47
  /** Slot range of a backfill: defaults to crawl start .. cursor, never past the cursor. */
44
48
  async function backfillRange(db, data) {
45
49
  const cursor = await (0, sync_state_1.readCursor)(db);
@@ -151,6 +155,7 @@ module.exports = (srv) => {
151
155
  },
152
156
  credentialBackfill: { ...credentialBackfill },
153
157
  decimalsBackfill: { ...decimalsBackfill },
158
+ registryBackfill: { ...registryBackfill },
154
159
  epochSnapshots: {
155
160
  enabled: epochSnapshotsConfigured(),
156
161
  source: epochSnapshotSource(),
@@ -287,6 +292,26 @@ module.exports = (srv) => {
287
292
  });
288
293
  return { accepted: true, message: 'Asset-decimals backfill started; poll getStatus().decimalsBackfill.' };
289
294
  });
295
+ // backfillAssetRegistry: writes the CIP-26 registry fields of every registered unit. The registry
296
+ // is off-chain, so this needs a backend that lists it. Progress is in getStatus().registryBackfill.
297
+ srv.on('backfillAssetRegistry', async (req) => {
298
+ if (registryBackfill.status === 'running')
299
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', 'An asset-registry backfill is already running');
300
+ if (!(0, server_1.getCardanoClient)().getTokenRegistryBackend())
301
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', 'No backend lists the token registry (needs Koios)');
302
+ registryBackfill = { status: 'running', units: 0, processed: 0, filled: 0, failed: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
303
+ void (0, asset_registry_backfill_1.backfillAssetRegistry)({
304
+ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(),
305
+ onProgress: (p) => { Object.assign(registryBackfill, p); },
306
+ })
307
+ .then((r) => { Object.assign(registryBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
308
+ .catch((err) => {
309
+ const message = err instanceof Error ? err.message : String(err);
310
+ Object.assign(registryBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
311
+ logger.error(`Asset-registry backfill failed: ${message}`);
312
+ });
313
+ return { accepted: true, message: 'Asset-registry backfill started; poll getStatus().registryBackfill.' };
314
+ });
290
315
  // importUtxoSet: one-off snapshot import that anchors crawler.utxoSet.
291
316
  // Runs detached. Progress is in getStatus().utxoSet.
292
317
  srv.on('importUtxoSet', async (req) => {
@@ -0,0 +1,6 @@
1
+ import type { JSONValue } from './types';
2
+ /** JSON.stringify without a replacer. Big integers are written as plain digits. */
3
+ export declare function stringifyJson(root: unknown): string;
4
+ /** JSON.parse with long integer literals as bigint. No key rewrite and no field-specific rule. */
5
+ export declare function parseJson(text: string): JSONValue;
6
+ //# sourceMappingURL=deep-json.d.ts.map
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stringifyJson = stringifyJson;
4
+ exports.parseJson = parseJson;
5
+ const native = JSON;
6
+ /** The Ogmios client's rule: an integer literal longer than 15 characters is read as bigint. */
7
+ const isBigLiteral = (src) => src.length > 15 && /^-?\d+$/.test(src);
8
+ /** Scalar text of a value, or undefined for what JSON leaves out (undefined, functions, symbols). */
9
+ function scalar(v) {
10
+ if (v === null)
11
+ return 'null';
12
+ switch (typeof v) {
13
+ case 'string': return JSON.stringify(v);
14
+ case 'number': return Number.isFinite(v) ? String(v) : 'null';
15
+ case 'bigint': return v.toString();
16
+ case 'boolean': return v ? 'true' : 'false';
17
+ default: return undefined;
18
+ }
19
+ }
20
+ // only objects are asked for toJSON; a bigint keeps its digits even with a toJSON polyfill
21
+ function withToJson(v, key) {
22
+ if (typeof v !== 'object' || v === null)
23
+ return v;
24
+ const toJSON = v.toJSON;
25
+ const r = typeof toJSON === 'function' ? toJSON.call(v, key) : v;
26
+ // a boxed primitive is written as the primitive, as JSON.stringify does
27
+ return r instanceof Number || r instanceof String || r instanceof Boolean || r instanceof BigInt ? r.valueOf() : r;
28
+ }
29
+ // a boxed BigInt is unboxed here, before the writer rejects it as a bigint
30
+ function replaceBigInt(_key, value) {
31
+ const v = value instanceof BigInt ? value.valueOf() : value;
32
+ return typeof v === 'bigint' ? native.rawJSON(v.toString()) : v;
33
+ }
34
+ /** JSON.stringify without a replacer. Big integers are written as plain digits. */
35
+ function stringifyJson(root) {
36
+ // a toJSON on BigInt.prototype (a common polyfill) would quote the digits before the replacer sees them
37
+ if (!('toJSON' in BigInt.prototype)) {
38
+ try {
39
+ const text = JSON.stringify(root, replaceBigInt);
40
+ if (text === undefined)
41
+ throw new TypeError('undefined has no JSON text');
42
+ return text;
43
+ }
44
+ catch (err) {
45
+ if (!(err instanceof RangeError))
46
+ throw err;
47
+ }
48
+ }
49
+ return stringifyJsonLoop(root);
50
+ }
51
+ function stringifyJsonLoop(root) {
52
+ let out = '';
53
+ const stack = [];
54
+ const open = new Set(); // containers on the current path, to refuse cycles like JSON.stringify
55
+ // writes a value; containers are pushed and written by the loop
56
+ const emit = (v, inArray) => {
57
+ if (typeof v === 'object' && v !== null) {
58
+ if (open.has(v))
59
+ throw new TypeError('Converting circular structure to JSON');
60
+ open.add(v);
61
+ if (Array.isArray(v)) {
62
+ out += '[';
63
+ stack.push({ kind: 'array', value: v, i: 0 });
64
+ }
65
+ else {
66
+ out += '{';
67
+ stack.push({ kind: 'object', value: v, keys: Object.keys(v), i: 0, wrote: false });
68
+ }
69
+ return true;
70
+ }
71
+ const s = scalar(v);
72
+ if (s === undefined) {
73
+ if (!inArray)
74
+ return false;
75
+ out += 'null';
76
+ return true;
77
+ }
78
+ out += s;
79
+ return true;
80
+ };
81
+ if (!emit(withToJson(root, ''), false))
82
+ throw new TypeError('undefined has no JSON text');
83
+ while (stack.length > 0) {
84
+ const top = stack[stack.length - 1];
85
+ if (top.kind === 'array') {
86
+ if (top.i >= top.value.length) {
87
+ out += ']';
88
+ open.delete(top.value);
89
+ stack.pop();
90
+ continue;
91
+ }
92
+ if (top.i > 0)
93
+ out += ',';
94
+ const i = top.i++;
95
+ emit(withToJson(top.value[i], String(i)), true);
96
+ }
97
+ else {
98
+ if (top.i >= top.keys.length) {
99
+ out += '}';
100
+ open.delete(top.value);
101
+ stack.pop();
102
+ continue;
103
+ }
104
+ const key = top.keys[top.i++];
105
+ const v = withToJson(top.value[key], key);
106
+ if ((typeof v !== 'object' || v === null) && scalar(v) === undefined)
107
+ continue;
108
+ out += (top.wrote ? ',' : '') + JSON.stringify(key) + ':';
109
+ top.wrote = true;
110
+ emit(v, false);
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+ function reviveBigInt(_key, value, context) {
116
+ return typeof value === 'number' && context?.source !== undefined && isBigLiteral(context.source)
117
+ ? BigInt(context.source)
118
+ : value;
119
+ }
120
+ /** JSON.parse with long integer literals as bigint. No key rewrite and no field-specific rule. */
121
+ function parseJson(text) {
122
+ try {
123
+ return native.parse(text, reviveBigInt);
124
+ }
125
+ catch (err) {
126
+ if (!(err instanceof RangeError))
127
+ throw err;
128
+ return parseJsonLoop(text);
129
+ }
130
+ }
131
+ const NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
132
+ // JSON.parse checks the string body, including raw control characters
133
+ const STRING = /"(?:[^"\\]|\\.)*"/y;
134
+ const SPACE = /[ \t\n\r]*/y;
135
+ function parseJsonLoop(text) {
136
+ let pos = 0;
137
+ const fail = (what) => { throw new SyntaxError(`${what} in JSON at position ${pos}`); };
138
+ const skip = () => { SPACE.lastIndex = pos; SPACE.exec(text); pos = SPACE.lastIndex; };
139
+ const match = (re) => {
140
+ re.lastIndex = pos;
141
+ const m = re.exec(text);
142
+ if (!m)
143
+ return null;
144
+ pos = re.lastIndex;
145
+ return m[0];
146
+ };
147
+ const stack = [];
148
+ let result;
149
+ let done = false;
150
+ const put = (v) => {
151
+ const top = stack[stack.length - 1];
152
+ if (!top) {
153
+ result = v;
154
+ done = true;
155
+ return;
156
+ }
157
+ if (top.kind === 'array')
158
+ top.value.push(v);
159
+ else {
160
+ // an own property, as JSON.parse makes it, even for the key "__proto__"
161
+ if (top.key === '__proto__')
162
+ Object.defineProperty(top.value, top.key, { value: v, writable: true, enumerable: true, configurable: true });
163
+ else
164
+ top.value[top.key] = v;
165
+ top.key = null;
166
+ }
167
+ };
168
+ // after a value inside a container: a comma or the closing bracket
169
+ const close = () => {
170
+ while (stack.length > 0) {
171
+ skip();
172
+ const top = stack[stack.length - 1];
173
+ const c = text[pos];
174
+ if (c === ',') {
175
+ pos++;
176
+ return;
177
+ }
178
+ if ((top.kind === 'array' && c === ']') || (top.kind === 'object' && c === '}')) {
179
+ pos++;
180
+ stack.pop();
181
+ put(top.value);
182
+ continue;
183
+ }
184
+ fail(`Unexpected ${c === undefined ? 'end' : `token ${c}`}`);
185
+ }
186
+ };
187
+ while (!done) {
188
+ skip();
189
+ const top = stack[stack.length - 1];
190
+ if (top?.kind === 'object' && top.key === null) {
191
+ const k = match(STRING) ?? fail('Expected property name');
192
+ skip();
193
+ if (text[pos] !== ':')
194
+ fail('Expected colon');
195
+ pos++;
196
+ top.key = JSON.parse(k);
197
+ continue;
198
+ }
199
+ const c = text[pos];
200
+ if (c === '[' || c === '{') {
201
+ pos++;
202
+ skip();
203
+ const empty = text[pos] === (c === '[' ? ']' : '}');
204
+ if (empty) {
205
+ pos++;
206
+ put(c === '[' ? [] : {});
207
+ }
208
+ else {
209
+ stack.push(c === '[' ? { kind: 'array', value: [] } : { kind: 'object', value: {}, key: null });
210
+ continue;
211
+ }
212
+ }
213
+ else if (c === '"') {
214
+ put(JSON.parse(match(STRING) ?? fail('Bad string')));
215
+ }
216
+ else if (text.startsWith('true', pos)) {
217
+ pos += 4;
218
+ put(true);
219
+ }
220
+ else if (text.startsWith('false', pos)) {
221
+ pos += 5;
222
+ put(false);
223
+ }
224
+ else if (text.startsWith('null', pos)) {
225
+ pos += 4;
226
+ put(null);
227
+ }
228
+ else {
229
+ const n = match(NUMBER) ?? fail(`Unexpected ${c === undefined ? 'end' : `token ${c}`}`);
230
+ put(isBigLiteral(n) ? BigInt(n) : Number(n));
231
+ }
232
+ if (!done)
233
+ close();
234
+ }
235
+ skip();
236
+ if (pos < text.length)
237
+ fail(`Unexpected token ${text[pos]}`);
238
+ return result;
239
+ }
240
+ //# sourceMappingURL=deep-json.js.map
@@ -56,7 +56,7 @@ const cds_1 = __importDefault(require("@sap/cds"));
56
56
  const node_util_1 = require("node:util");
57
57
  const blake2b_1 = __importDefault(require("blake2b"));
58
58
  const bech32_1 = require("bech32");
59
- const client_1 = require("@cardano-ogmios/client");
59
+ const deep_json_1 = require("./deep-json");
60
60
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
61
61
  const logger = cds_1.default.log('mappers');
62
62
  const errors_1 = require("./errors");
@@ -469,8 +469,8 @@ function mapTransactionMetadata(providerLabels) {
469
469
  id: id,
470
470
  tx_hash: lbl.txHash,
471
471
  label: lbl.label.toString(),
472
- // Ogmios exposes numeric metadata as bigint; safeJSON writes exact number tokens
473
- payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
472
+ // Ogmios exposes numeric metadata as bigint; written as exact number tokens
473
+ payload: lbl.json !== undefined ? (0, deep_json_1.stringifyJson)(lbl.json) : null,
474
474
  });
475
475
  }
476
476
  return rows;
@@ -577,7 +577,7 @@ function mapAsset(providerAssetInfo, max_age) {
577
577
  initialMintTxHash: providerAssetInfo.initialMintTxHash,
578
578
  initialMintTime: providerAssetInfo.initialMintTime,
579
579
  onchainMetadata: providerAssetInfo.onchainMetadata
580
- ? JSON.stringify(providerAssetInfo.onchainMetadata)
580
+ ? (0, deep_json_1.stringifyJson)(providerAssetInfo.onchainMetadata)
581
581
  : null,
582
582
  registryName: providerAssetInfo.registryName,
583
583
  registryTicker: providerAssetInfo.registryTicker,
@@ -5,8 +5,8 @@ export type { ReferenceScriptType };
5
5
  export type Hex = string;
6
6
  /** Lovelace amount; a string preserves precision above Number.MAX_SAFE_INTEGER (max supply is 4.5e16). */
7
7
  export type Lovelace = number | string;
8
- /** Any valid JSON value */
9
- export type JSONValue = string | number | boolean | {
8
+ /** Any JSON value; an integer literal too long for a double is read as bigint */
9
+ export type JSONValue = string | number | bigint | boolean | {
10
10
  [key: string]: JSONValue;
11
11
  } | JSONValue[] | null;
12
12
  /** Multi-asset amount line as returned by common Cardano APIs */