@odatano/core 2.0.0-rc.10 → 2.0.0-rc.12

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 (32) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +54 -0
  2. package/@cds-models/CardanoODataService/index.js +6 -0
  3. package/@cds-models/odatano/cardano/index.d.ts +54 -0
  4. package/@cds-models/odatano/cardano/index.js +6 -0
  5. package/db/schema.cds +1844 -1738
  6. package/package.json +1 -1
  7. package/srv/blockchain/backends/blockfrost-backend.js +7 -2
  8. package/srv/blockchain/backends/cardano-backend.d.ts +22 -0
  9. package/srv/blockchain/backends/cardano-backend.js +9 -0
  10. package/srv/blockchain/backends/koios-backend.d.ts +34 -2
  11. package/srv/blockchain/backends/koios-backend.js +133 -39
  12. package/srv/blockchain/backends/ogmios-backend.d.ts +6 -1
  13. package/srv/blockchain/backends/ogmios-backend.js +27 -2
  14. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  15. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  16. package/srv/blockchain/cardano-client.d.ts +8 -1
  17. package/srv/blockchain/cardano-client.js +14 -0
  18. package/srv/blockchain/cardano-indexer.d.ts +127 -0
  19. package/srv/blockchain/cardano-indexer.js +345 -3
  20. package/srv/blockchain/crawler/crawler.d.ts +88 -0
  21. package/srv/blockchain/crawler/crawler.js +180 -2
  22. package/srv/cardano-service.cds +10 -0
  23. package/srv/server.js +26 -1
  24. package/srv/utils/const.d.ts +1 -1
  25. package/srv/utils/const.js +1 -1
  26. package/srv/utils/errors.d.ts +18 -0
  27. package/srv/utils/errors.js +24 -1
  28. package/srv/utils/mappers.d.ts +54 -1
  29. package/srv/utils/mappers.js +111 -0
  30. package/srv/utils/types.d.ts +27 -0
  31. package/srv/utils/validators.d.ts +1 -1
  32. package/srv/utils/validators.js +2 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.10",
3
+ "version": "2.0.0-rc.12",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -120,6 +120,9 @@ class BlockfrostBackend {
120
120
  fee: tx.fees,
121
121
  deposit: tx.deposit,
122
122
  size: tx.size,
123
+ // `spends === 'collaterals'` in Ogmios terms: the script phase failed, so the
124
+ // ledger applied neither the declared inputs/outputs nor the declared mint.
125
+ spendsCollaterals: tx.valid_contract === false,
123
126
  inputs: txUtxos.inputs.map(input => ({
124
127
  address: input.address,
125
128
  txHash: input.tx_hash,
@@ -128,8 +131,10 @@ class BlockfrostBackend {
128
131
  dataHash: input.data_hash,
129
132
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
130
133
  referenceScriptHash: input.reference_script_hash,
131
- collateral: input.collateral,
132
- reference: input.reference,
134
+ // TxInputLine's names — these were mapped as `collateral`/`reference` before,
135
+ // which nothing reads, so every consumer saw a reference input as a consumed one.
136
+ isCollateral: input.collateral === true,
137
+ isReference: input.reference === true,
133
138
  })),
134
139
  outputs: txUtxos.outputs.map(output => ({
135
140
  address: output.address,
@@ -248,4 +248,26 @@ export interface PaginatingBackend extends CardanoBackend {
248
248
  }
249
249
  /** Type guard: can this backend be walked forward by pagination? */
250
250
  export declare function isPaginatingBackend(backend: CardanoBackend): backend is PaginatingBackend;
251
+ /**
252
+ * Backend that can enumerate the full stake-pool and DRep set and fetch them in batches —
253
+ * what the crawler's epoch-boundary snapshots need (v2.0 analytics coverage).
254
+ *
255
+ * Koios only, and deliberately so: it lists ids (`/pool_list`, `/drep_list`) and resolves
256
+ * them in batches (`POST /pool_info`, `POST /drep_info`), which turns a mainnet snapshot of
257
+ * ~3 200 pools into a handful of requests. Blockfrost can list ids but has no batch info
258
+ * endpoint, so the same snapshot would be thousands of single requests — the snapshots stay
259
+ * off rather than being served that way (same rule as GetUTxOsByCredential).
260
+ */
261
+ export interface EnumeratingBackend extends CardanoBackend {
262
+ /** All known stake-pool ids (bech32). */
263
+ getPoolIds(): Promise<string[]>;
264
+ /** Resolve a batch of pool ids. Ids the backend does not know are omitted, not faked. */
265
+ getPools(poolIds: string[]): Promise<PoolData[]>;
266
+ /** All known DRep ids (bech32). */
267
+ getDrepIds(): Promise<string[]>;
268
+ /** Resolve a batch of DRep ids. Ids the backend does not know are omitted. */
269
+ getDreps(drepIds: string[]): Promise<DrepData[]>;
270
+ }
271
+ /** Type guard: can this backend enumerate pools and DReps? */
272
+ export declare function isEnumeratingBackend(backend: CardanoBackend): backend is EnumeratingBackend;
251
273
  //# sourceMappingURL=cardano-backend.d.ts.map
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isEvaluatingBackend = isEvaluatingBackend;
4
4
  exports.isChainSyncBackend = isChainSyncBackend;
5
5
  exports.isPaginatingBackend = isPaginatingBackend;
6
+ exports.isEnumeratingBackend = isEnumeratingBackend;
6
7
  /**
7
8
  * Type guard to check if a backend supports transaction evaluation
8
9
  * @param backend - The backend to check
@@ -22,4 +23,12 @@ function isPaginatingBackend(backend) {
22
23
  && typeof b.getNextBlocks === 'function'
23
24
  && typeof b.getBlockTransactions === 'function';
24
25
  }
26
+ /** Type guard: can this backend enumerate pools and DReps? */
27
+ function isEnumeratingBackend(backend) {
28
+ const b = backend;
29
+ return typeof b.getPoolIds === 'function'
30
+ && typeof b.getPools === 'function'
31
+ && typeof b.getDrepIds === 'function'
32
+ && typeof b.getDreps === 'function';
33
+ }
25
34
  //# sourceMappingURL=cardano-backend.js.map
@@ -1,11 +1,11 @@
1
- import { CardanoBackend, PaginatingBackend } from './cardano-backend';
1
+ import { CardanoBackend, PaginatingBackend, EnumeratingBackend } from './cardano-backend';
2
2
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters } from '../../utils/types';
3
3
  import { Network } from '../cardano-client';
4
4
  /**
5
5
  * KoiosBackend Implementation for CardanoBackend Interface
6
6
  * Implements the CardanoBackend interface using Koios API with Axios
7
7
  */
8
- export declare class KoiosBackend implements CardanoBackend, PaginatingBackend {
8
+ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend, EnumeratingBackend {
9
9
  readonly name = "koios";
10
10
  private api;
11
11
  private network;
@@ -95,6 +95,8 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend {
95
95
  * @returns {Promise<PoolData>} pool data
96
96
  */
97
97
  getPool(poolId: string): Promise<PoolData>;
98
+ /** Map one Koios /pool_info row to the canonical PoolData. */
99
+ private _mapKoiosPool;
98
100
  /**
99
101
  * Get Asset Info (supply, mint history, CIP-25 + CIP-26 metadata).
100
102
  * Koios's `asset_info` returns total_supply, mint/burn counts split,
@@ -120,6 +122,8 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend {
120
122
  * @returns {Promise<DrepData>} drep data
121
123
  */
122
124
  getDrep(drepId: string): Promise<DrepData>;
125
+ /** Map one Koios /drep_info row to the canonical DrepData. */
126
+ private _mapKoiosDrep;
123
127
  /**
124
128
  * Get Account Data for specified stake address
125
129
  * @param accountId account id
@@ -191,6 +195,34 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend {
191
195
  * round-trip is skipped entirely.
192
196
  */
193
197
  getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
198
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
199
+ private static readonly LIST_PAGE_SIZE;
200
+ /** Ids resolved per /pool_info / /drep_info request. */
201
+ private static readonly INFO_BATCH_SIZE;
202
+ /**
203
+ * Refuse to page forever if an endpoint keeps returning full pages — 500 pages is
204
+ * 500 000 ids, far beyond any real pool or DRep set.
205
+ */
206
+ private static readonly LIST_MAX_PAGES;
207
+ /**
208
+ * Page through a PostgREST list endpoint and collect one id column. Stops on the first
209
+ * short page, so a complete set costs exactly ceil(n / 1000) + 1 requests.
210
+ */
211
+ private listAllIds;
212
+ /**
213
+ * All stake-pool ids known to Koios (bech32), including retired ones — a snapshot that
214
+ * silently dropped retiring pools would misreport the epoch's pool set.
215
+ */
216
+ getPoolIds(): Promise<string[]>;
217
+ /**
218
+ * Resolve pool ids in batches. Ids Koios does not return are omitted rather than
219
+ * substituted with empty rows — a missing pool is better than an invented one.
220
+ */
221
+ getPools(poolIds: string[]): Promise<PoolData[]>;
222
+ /** All DRep ids known to Koios (bech32). */
223
+ getDrepIds(): Promise<string[]>;
224
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
225
+ getDreps(drepIds: string[]): Promise<DrepData[]>;
194
226
  /**
195
227
  * Get the full transaction list of a block in block order via /block_txs → /tx_info
196
228
  * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
@@ -450,28 +450,31 @@ class KoiosBackend {
450
450
  if (!Array.isArray(data) || data.length === 0) {
451
451
  throw new errors_1.NotFoundError('Pool', this.name);
452
452
  }
453
- const poolData = data[0];
454
- return {
455
- poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || poolId,
456
- vrfKeyHash: poolData.vrf_key_hash,
457
- blocksMinted: poolData.block_count,
458
- // Koios pool_info has no blocks-in-current-epoch figure — epoch_no
459
- // (the epoch NUMBER) was mapped here before, which is a different
460
- // semantic than Blockfrost's blocks_epoch. 0 = not available.
461
- blocksEpoch: 0,
462
- liveStake: poolData.live_stake || '0',
463
- liveSize: poolData.live_size || 0,
464
- liveDelegators: poolData.live_delegators || 0,
465
- liveSaturation: poolData.live_saturation || 0,
466
- activeStake: poolData.active_stake || '0',
467
- activeSize: poolData.active_size || 0,
468
- pledge: poolData.pledge || '0',
469
- margin: poolData.margin || 0,
470
- fixedCost: poolData.fixed_cost || '0',
471
- rewardAccount: poolData.reward_addr,
472
- };
453
+ return this._mapKoiosPool(data[0], poolId);
473
454
  }, this.name);
474
455
  }
456
+ /** Map one Koios /pool_info row to the canonical PoolData. */
457
+ _mapKoiosPool(poolData, fallbackId) {
458
+ return {
459
+ poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
460
+ vrfKeyHash: poolData.vrf_key_hash,
461
+ blocksMinted: poolData.block_count,
462
+ // Koios pool_info has no blocks-in-current-epoch figure — epoch_no
463
+ // (the epoch NUMBER) was mapped here before, which is a different
464
+ // semantic than Blockfrost's blocks_epoch. 0 = not available.
465
+ blocksEpoch: 0,
466
+ liveStake: poolData.live_stake || '0',
467
+ liveSize: poolData.live_size || 0,
468
+ liveDelegators: poolData.live_delegators || 0,
469
+ liveSaturation: poolData.live_saturation || 0,
470
+ activeStake: poolData.active_stake || '0',
471
+ activeSize: poolData.active_size || 0,
472
+ pledge: poolData.pledge || '0',
473
+ margin: poolData.margin || 0,
474
+ fixedCost: poolData.fixed_cost || '0',
475
+ rewardAccount: poolData.reward_addr,
476
+ };
477
+ }
475
478
  /**
476
479
  * Get Asset Info (supply, mint history, CIP-25 + CIP-26 metadata).
477
480
  * Koios's `asset_info` returns total_supply, mint/burn counts split,
@@ -596,27 +599,30 @@ class KoiosBackend {
596
599
  if (!Array.isArray(data) || data.length === 0) {
597
600
  throw new errors_1.NotFoundError('Drep', this.name);
598
601
  }
599
- const drepData = data[0];
600
- // Koios changed the /drep_info schema (observed 2026-07): the old
601
- // `expired`/`retired`/`last_active_epoch` fields were replaced by
602
- // `drep_status` ('registered' | 'retired'), `active` (boolean) and
603
- // `expires_epoch_no`. Read the old fields first (mainnet/preprod may
604
- // lag the migration), then derive from the new ones.
605
- const retired = drepData.retired ?? drepData.drep_status === 'retired';
606
- const expired = drepData.expired ?? (drepData.active === false && !retired);
607
- return {
608
- drepId: drepData.drep_id,
609
- hex: drepData.hex,
610
- amount: drepData.amount,
611
- hasScript: drepData.has_script,
612
- // The new schema no longer reports the last-activity epoch (only
613
- // `expires_epoch_no`, which has different semantics) — keep 0 there.
614
- lastActiveEpoch: drepData.last_active_epoch ?? 0,
615
- expired,
616
- retired,
617
- };
602
+ return this._mapKoiosDrep(data[0]);
618
603
  }, this.name);
619
604
  }
605
+ /** Map one Koios /drep_info row to the canonical DrepData. */
606
+ _mapKoiosDrep(drepData) {
607
+ // Koios changed the /drep_info schema (observed 2026-07): the old
608
+ // `expired`/`retired`/`last_active_epoch` fields were replaced by
609
+ // `drep_status` ('registered' | 'retired'), `active` (boolean) and
610
+ // `expires_epoch_no`. Read the old fields first (mainnet/preprod may
611
+ // lag the migration), then derive from the new ones.
612
+ const retired = drepData.retired ?? drepData.drep_status === 'retired';
613
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
614
+ return {
615
+ drepId: drepData.drep_id,
616
+ hex: drepData.hex,
617
+ amount: drepData.amount,
618
+ hasScript: drepData.has_script,
619
+ // The new schema no longer reports the last-activity epoch (only
620
+ // `expires_epoch_no`, which has different semantics) — keep 0 there.
621
+ lastActiveEpoch: drepData.last_active_epoch ?? 0,
622
+ expired,
623
+ retired,
624
+ };
625
+ }
620
626
  /**
621
627
  * Get Account Data for specified stake address
622
628
  * @param accountId account id
@@ -935,6 +941,84 @@ class KoiosBackend {
935
941
  .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
936
942
  }, this.name);
937
943
  }
944
+ // ---------------------------------------------------------------------------
945
+ // EnumeratingBackend — full pool/DRep set for the crawler's epoch snapshots
946
+ // ---------------------------------------------------------------------------
947
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
948
+ static LIST_PAGE_SIZE = 1000;
949
+ /** Ids resolved per /pool_info / /drep_info request. */
950
+ static INFO_BATCH_SIZE = 50;
951
+ /**
952
+ * Refuse to page forever if an endpoint keeps returning full pages — 500 pages is
953
+ * 500 000 ids, far beyond any real pool or DRep set.
954
+ */
955
+ static LIST_MAX_PAGES = 500;
956
+ /**
957
+ * Page through a PostgREST list endpoint and collect one id column. Stops on the first
958
+ * short page, so a complete set costs exactly ceil(n / 1000) + 1 requests.
959
+ */
960
+ async listAllIds(path, column, label) {
961
+ const ids = [];
962
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
963
+ const offset = page * KoiosBackend.LIST_PAGE_SIZE;
964
+ const { data } = await this.getWithRetryOn42804(`${path}?select=${column}&limit=${KoiosBackend.LIST_PAGE_SIZE}&offset=${offset}`, {}, label);
965
+ if (!Array.isArray(data) || data.length === 0)
966
+ return ids;
967
+ for (const row of data) {
968
+ const id = row[column];
969
+ if (typeof id === 'string' && id)
970
+ ids.push(id);
971
+ }
972
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
973
+ return ids;
974
+ }
975
+ logger.warn(`${label}: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages — the list may be truncated`);
976
+ return ids;
977
+ }
978
+ /**
979
+ * All stake-pool ids known to Koios (bech32), including retired ones — a snapshot that
980
+ * silently dropped retiring pools would misreport the epoch's pool set.
981
+ */
982
+ async getPoolIds() {
983
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
984
+ }
985
+ /**
986
+ * Resolve pool ids in batches. Ids Koios does not return are omitted rather than
987
+ * substituted with empty rows — a missing pool is better than an invented one.
988
+ */
989
+ async getPools(poolIds) {
990
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
991
+ const out = [];
992
+ for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
993
+ const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
994
+ const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
995
+ if (!Array.isArray(data))
996
+ continue;
997
+ for (const row of data)
998
+ out.push(this._mapKoiosPool(row, ''));
999
+ }
1000
+ return out;
1001
+ }, this.name);
1002
+ }
1003
+ /** All DRep ids known to Koios (bech32). */
1004
+ async getDrepIds() {
1005
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/drep_list', 'drep_id', 'getDrepIds'), this.name);
1006
+ }
1007
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
1008
+ async getDreps(drepIds) {
1009
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
1010
+ const out = [];
1011
+ for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
1012
+ const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
1013
+ const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
1014
+ if (!Array.isArray(data))
1015
+ continue;
1016
+ for (const row of data)
1017
+ out.push(this._mapKoiosDrep(row));
1018
+ }
1019
+ return out;
1020
+ }, this.name);
1021
+ }
938
1022
  /**
939
1023
  * Get the full transaction list of a block in block order via /block_txs → /tx_info
940
1024
  * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
@@ -990,6 +1074,16 @@ class KoiosBackend {
990
1074
  index: tx.tx_block_index ?? 0,
991
1075
  fee: tx.fee || '0',
992
1076
  deposit: tx.deposit || '0',
1077
+ // undefined (not []) when Koios does not report the field at all — the indexer then
1078
+ // falls back to the input/output delta instead of reading "no mint" into a gap.
1079
+ mint: Array.isArray(tx.assets_minted)
1080
+ ? tx.assets_minted
1081
+ .filter((a) => a?.policy_id && a.quantity != null)
1082
+ .map((a) => ({
1083
+ unit: `${a.policy_id}${a.asset_name ?? ''}`,
1084
+ quantity: String(a.quantity),
1085
+ }))
1086
+ : undefined,
993
1087
  size: tx.tx_size,
994
1088
  inputs: tx.inputs.map((input) => {
995
1089
  const amount = [
@@ -253,6 +253,10 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
253
253
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
254
254
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
255
255
  * the network's Shelley anchor (same config the tx-builder uses).
256
+ *
257
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
258
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
259
+ * corrects both the transaction and this sum in applyCollateralFees().
256
260
  */
257
261
  private mapOgmiosBlock;
258
262
  /**
@@ -260,7 +264,8 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
260
264
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
261
265
  * resolved downstream by the indexer). `spends` selects the ledger-applied
262
266
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
263
- * its collateral-return output, never its declared regular inputs/outputs.
267
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
268
+ * follows that partition too — see the `spendsCollaterals` branch below.
264
269
  */
265
270
  private mapOgmiosTx;
266
271
  }
@@ -13,6 +13,7 @@ const client_1 = require("@cardano-ogmios/client");
13
13
  const bech32_1 = require("bech32");
14
14
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
15
15
  const errors_1 = require("../../utils/errors");
16
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
16
17
  const mappers_1 = require("../../utils/mappers");
17
18
  const const_1 = require("../../utils/const");
18
19
  const logger = cds_1.default.log('OgmiosBackend');
@@ -798,6 +799,14 @@ class OgmiosBackend {
798
799
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
799
800
  }
800
801
  };
802
+ // A frame the client's own parser cannot handle never reaches this class: it throws
803
+ // inside the library's socket handler, where nothing awaits it, and ends the process.
804
+ // The guard intercepts that and routes the unusable frame here instead, as an ordinary
805
+ // stream error naming the block. Installed per open (one stream at a time) and
806
+ // idempotent, so reopening only swaps the callback.
807
+ (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
808
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
809
+ });
801
810
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
802
811
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
803
812
  void reportStreamError(err);
@@ -904,6 +913,10 @@ class OgmiosBackend {
904
913
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
905
914
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
906
915
  * the network's Shelley anchor (same config the tx-builder uses).
916
+ *
917
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
918
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
919
+ * corrects both the transaction and this sum in applyCollateralFees().
907
920
  */
908
921
  mapOgmiosBlock(block) {
909
922
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
@@ -932,7 +945,8 @@ class OgmiosBackend {
932
945
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
933
946
  * resolved downstream by the indexer). `spends` selects the ledger-applied
934
947
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
935
- * its collateral-return output, never its declared regular inputs/outputs.
948
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
949
+ * follows that partition too — see the `spendsCollaterals` branch below.
936
950
  */
937
951
  mapOgmiosTx(tx, block, index) {
938
952
  const mapInput = (input, flags = {}) => ({
@@ -972,14 +986,25 @@ class OgmiosBackend {
972
986
  json: v.json,
973
987
  }))
974
988
  : [];
989
+ // A phase-2 failure does not pay the fee declared in the body — the ledger consumes
990
+ // the collateral instead. `total_collateral` is that amount and the ledger enforces
991
+ // the equality, so prefer it; the body omits it often enough that the indexer derives
992
+ // the rest from the resolved collateral inputs once it has them.
993
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
994
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
975
995
  return {
976
996
  hash: tx.id,
977
997
  blockHash: block.id,
978
998
  blockHeight: block.height,
979
999
  slot: block.slot,
980
1000
  index,
981
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
1001
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1002
+ spendsCollaterals,
1003
+ totalCollateral,
982
1004
  deposit: '0',
1005
+ // The ledger applies no mint when the script phase failed: the body's mint field is
1006
+ // declared but never enacted, so a phase-2 failure must report none at all.
1007
+ mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
983
1008
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
984
1009
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
985
1010
  size: null,
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
3
+ *
4
+ * `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
5
+ * `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
6
+ * `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
7
+ * walks the parsed tree recursively. A native script nests one JSON object per clause, and
8
+ * nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
9
+ * expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
10
+ *
11
+ * That is not a theoretical shape. Preprod block 5183974 carries a native script nested
12
+ * 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
13
+ * The block is 43 kB on chain and 205 kB as a chain-sync frame.
14
+ *
15
+ * The crash is fatal rather than merely annoying, because of where the parse happens
16
+ * (`ChainSynchronization/Client.js`):
17
+ *
18
+ * socket.on('message', async (message) => {
19
+ * await responseHandler(util_1.safeJSON.parse(message));
20
+ * });
21
+ *
22
+ * `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
23
+ * the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
24
+ * crawler's poison-block latch cannot help: it guards the persist path, and the server is
25
+ * gone long before a block reaches it. Docker restarts, the crawler resumes at the same
26
+ * block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
27
+ *
28
+ * This guard wraps `safeJSON.parse` (a public export of the client package) so that the
29
+ * fast path is untouched and only an overflowing frame takes the recovery route:
30
+ *
31
+ * 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
32
+ * 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
33
+ * hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
34
+ * is no longer a limit. `sanitize` is skipped, because it would overflow on the very
35
+ * same structure;
36
+ * 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
37
+ * The guard never throws, because throwing here is what kills the process.
38
+ *
39
+ * Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
40
+ * `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
41
+ * `JSON.parse` completes in 17 ms.
42
+ *
43
+ * Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
44
+ * consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
45
+ */
46
+ import { safeJSON } from '@cardano-ogmios/client';
47
+ /** A frame the guard could not turn into an object at all. */
48
+ export interface UnparseableFrame {
49
+ /** Block height, when it could be read off the raw text; null when even that failed. */
50
+ height: number | null;
51
+ /** Block id (hash), when readable. */
52
+ id: string | null;
53
+ reason: string;
54
+ bytes: number;
55
+ }
56
+ /**
57
+ * Integers outside the safe double range, written into JSON strings so that plain
58
+ * `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
59
+ * never recursing, so it is immune to the nesting that sent us here in the first place.
60
+ *
61
+ * Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
62
+ * names) are skipped, and so are floats and exponents, which are doubles by nature and have
63
+ * no exact integer to preserve.
64
+ */
65
+ export declare function widenBigIntegers(text: string): string;
66
+ /**
67
+ * Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
68
+ * report callback, so reopening the chain-sync stream never stacks wrappers.
69
+ *
70
+ * @param onUnparseableFrame called when a frame survives neither parser. The guard returns
71
+ * a sentinel instead of throwing, so the caller owns what happens next — the stream
72
+ * itself stalls, because the client drops anything that is not a nextBlock response.
73
+ */
74
+ export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): void;
75
+ /** Tests only — drop the wrapper so each case starts from the untouched client. */
76
+ export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
77
+ //# sourceMappingURL=ogmios-frame-guard.d.ts.map