@odatano/core 2.0.0-rc.23 → 2.0.0-rc.24

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.
@@ -2,7 +2,7 @@ import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBac
2
2
  import { type CircuitBreakerConfig } from './circuit-breaker';
3
3
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
4
4
  export type Network = 'mainnet' | 'preview' | 'preprod';
5
- export type BackendName = 'blockfrost' | 'koios' | 'ogmios';
5
+ export type BackendName = 'blockfrost' | 'koios' | 'ogmios' | 'odatano';
6
6
  export type TransactionBuilderName = 'buildooor';
7
7
  export type CardanoClientConfig = {
8
8
  network: Network;
@@ -11,6 +11,10 @@ export type CardanoClientConfig = {
11
11
  blockfrostCustomBackend?: string;
12
12
  koiosApiKey: string;
13
13
  ogmiosUrl: string;
14
+ /** Remote ODATANO for the `odatano` backend; defaults to the public API of the network. */
15
+ odatanoUrl?: string;
16
+ /** Key for the remote ODATANO (a gateway `oda_…` key or an agent grant token). */
17
+ odatanoApiKey?: string;
14
18
  transactionBuilders: TransactionBuilderName[];
15
19
  primaryTimeoutMs: number;
16
20
  fallbackTimeoutMs: number;
@@ -88,7 +92,7 @@ export declare class CardanoClient {
88
92
  getAddressUtxos(address: string): Promise<UTxO[]>;
89
93
  /**
90
94
  * UTxOs by 28-byte payment credential (56-char hex), across all bech32 forms sharing it.
91
- * Koios-only: no other backend has a credential-keyed endpoint, so this throws without Koios.
95
+ * Needs a credential-keyed backend (Koios, or another ODATANO); Blockfrost has none.
92
96
  */
93
97
  getCredentialUtxos(credHash: string): Promise<UTxO[]>;
94
98
  getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
@@ -165,9 +169,13 @@ export declare class CardanoClient {
165
169
  * the next backend may answer 409 "already submitted" — callers treat that as success.
166
170
  */
167
171
  submitTransaction(signedTxCbor: string): Promise<string>;
168
- /** True when Ogmios is the live backend (script evaluation available). */
172
+ /** True when Ogmios is the live backend. */
169
173
  hasOgmiosBackend(): boolean;
170
- /** Evaluate script execution units of an unsigned transaction (Ogmios only). */
174
+ /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
175
+ private evaluatingBackend;
176
+ /** True when some backend can evaluate script execution units. */
177
+ hasEvaluatingBackend(): boolean;
178
+ /** Evaluate script execution units of an unsigned transaction. */
171
179
  evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
172
180
  }
173
181
  //# sourceMappingURL=cardano-client.d.ts.map
@@ -12,6 +12,7 @@ const request_coalescer_1 = require("./request-coalescer");
12
12
  const ogmios_backend_1 = require("./backends/ogmios-backend");
13
13
  const blockfrost_backend_1 = require("./backends/blockfrost-backend");
14
14
  const koios_backend_1 = require("./backends/koios-backend");
15
+ const odatano_backend_1 = require("./backends/odatano-backend");
15
16
  const logger = cds_1.default.log('CardanoClient');
16
17
  /** Which backend type to prefer per method. */
17
18
  const METHOD_ROUTING = {
@@ -72,6 +73,9 @@ class CardanoClient {
72
73
  if (backends.includes('koios')) {
73
74
  this.historicalBackends.push(new koios_backend_1.KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
74
75
  }
76
+ if (backends.includes('odatano')) {
77
+ this.historicalBackends.push(new odatano_backend_1.OdatanoBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
78
+ }
75
79
  if (!this.liveBackend && this.historicalBackends.length === 0) {
76
80
  throw new errors_1.ConfigError('No valid backends configured for CardanoClient');
77
81
  }
@@ -310,15 +314,16 @@ class CardanoClient {
310
314
  }
311
315
  /**
312
316
  * UTxOs by 28-byte payment credential (56-char hex), across all bech32 forms sharing it.
313
- * Koios-only: no other backend has a credential-keyed endpoint, so this throws without Koios.
317
+ * Needs a credential-keyed backend (Koios, or another ODATANO); Blockfrost has none.
314
318
  */
315
319
  getCredentialUtxos(credHash) {
316
320
  const candidates = [this.liveBackend, ...this.historicalBackends];
317
- const koios = candidates.find(b => b?.name === 'koios' && typeof b.getCredentialUtxos === 'function');
318
- if (!koios) {
319
- throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires Koios backend. Configure 'koios' in cds.requires.odatano-core.backends.", 'koios');
321
+ const capable = candidates.filter((b) => typeof b?.getCredentialUtxos === 'function');
322
+ const backend = capable.find(b => b.name === 'koios') ?? capable[0];
323
+ if (!backend) {
324
+ throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires a Koios or odatano backend. Configure one in cds.requires.odatano-core.backends.", 'koios');
320
325
  }
321
- return this.credCoalescer.get(credHash, () => this.callWithResilience(koios, () => koios.getCredentialUtxos(credHash)));
326
+ return this.credCoalescer.get(credHash, () => this.callWithResilience(backend, () => backend.getCredentialUtxos(credHash)));
322
327
  }
323
328
  getAddressTransactions(address, limit) {
324
329
  return this.route('getAddressTransactions', b => b.getAddressTransactions(address, limit));
@@ -572,18 +577,30 @@ class CardanoClient {
572
577
  submitTransaction(signedTxCbor) {
573
578
  return this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
574
579
  }
575
- /** True when Ogmios is the live backend (script evaluation available). */
580
+ /** True when Ogmios is the live backend. */
576
581
  hasOgmiosBackend() {
577
582
  return this.liveBackend?.name === 'ogmios';
578
583
  }
579
- /** Evaluate script execution units of an unsigned transaction (Ogmios only). */
584
+ /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
585
+ evaluatingBackend() {
586
+ const candidates = [this.liveBackend, ...this.historicalBackends];
587
+ for (const b of candidates)
588
+ if (b && (0, cardano_backend_1.isEvaluatingBackend)(b))
589
+ return b;
590
+ return null;
591
+ }
592
+ /** True when some backend can evaluate script execution units. */
593
+ hasEvaluatingBackend() {
594
+ return this.evaluatingBackend() != null;
595
+ }
596
+ /** Evaluate script execution units of an unsigned transaction. */
580
597
  async evaluateTransaction(unsignedTxCbor) {
581
598
  await this.ensureInitialized();
582
- if (!this.liveBackend || !(0, cardano_backend_1.isEvaluatingBackend)(this.liveBackend)) {
583
- throw new errors_1.ProviderUnavailableError('Transaction evaluation requires an evaluating backend (e.g., Ogmios)');
599
+ const backend = this.evaluatingBackend();
600
+ if (!backend) {
601
+ throw new errors_1.ProviderUnavailableError('Transaction evaluation requires an evaluating backend (Ogmios or odatano)');
584
602
  }
585
603
  // timeout + breaker, so a hanging socket cannot block Plutus builds
586
- const backend = this.liveBackend;
587
604
  return this.callWithResilience(backend, () => backend.evaluateTransaction(unsignedTxCbor));
588
605
  }
589
606
  }
@@ -3,7 +3,7 @@ import type { CardanoClient } from './cardano-client';
3
3
  import type { CardanoTransactionBuilder } from './cardano-tx-builder';
4
4
  import { Transaction as CardanoTransaction, AddressUTxOs, TransactionMetadata, NetworkInformation, Block, Epoch, AssetHistory, Account, Drep, Pool, Asset, Address, LedgerProtocolParameter, AddressTransactions } from '#cds-models/CardanoODataService';
5
5
  import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTransactionService';
6
- import { TxBuildRequest, Transaction as ProviderTransaction, BlockData } from '../utils/types';
6
+ import { TxBuildRequest, AssetInfo, AccountData, PoolData, NetworkInformation as ProviderNetworkInformation, Address as ProviderAddress, Transaction as ProviderTransaction, UTxO as OdatanoUtxo, BlockData, AssetHistoryEntry as AssetHistoryEntryProviderData } from '../utils/types';
7
7
  import { type LedgerAnchor } from './ledger-state';
8
8
  import type { TxCacheTargets } from '../utils/tx-build-helper';
9
9
  /**
@@ -86,12 +86,24 @@ export declare class CardanoIndexer {
86
86
  */
87
87
  private crawlAnswers;
88
88
  /** 404 for a lookup the crawled chain answers on its own (the caller already missed in the DB). */
89
- private refuseOutsideCrawl;
89
+ refuseOutsideCrawl(tx: CapTransaction, method: string, what: string): Promise<void>;
90
90
  /**
91
91
  * Asset from crawled mint/burn rows: supply = mints − burns, first mint, CIP-25 payload (label 721)
92
92
  * of the latest mint. Registry fields stay null. null = the crawled chain does not answer.
93
93
  */
94
94
  private localAssetInfo;
95
+ /** Address from the crawled UTxO set when it answers, else from the backend. */
96
+ resolveAddress(tx: CapTransaction, addr: string): Promise<ProviderAddress>;
97
+ /** UTxOs of an address: the crawled set (outputs from the node at the tip) when it answers, else the backend. */
98
+ resolveAddressUtxos(tx: CapTransaction, addr: string): Promise<OdatanoUtxo[]>;
99
+ /** Asset from the crawled chain when it answers, else from the backend. */
100
+ resolveAssetInfo(tx: CapTransaction, unit: string): Promise<AssetInfo>;
101
+ /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
102
+ resolveAssetHistory(tx: CapTransaction, unit: string, limit: number): Promise<AssetHistoryEntryProviderData[]>;
103
+ /** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
104
+ resolveCredentialUtxos(tx: CapTransaction, credHash: string): Promise<OdatanoUtxo[]>;
105
+ /** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
106
+ resolveAddressTransactionHashes(tx: CapTransaction, addr: string, limit: number): Promise<string[]>;
95
107
  /** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
96
108
  ledgerCoverageActive(tx: CapTransaction): Promise<boolean>;
97
109
  /**
@@ -205,6 +217,8 @@ export declare class CardanoIndexer {
205
217
  indexTransactionMetadata(tx: CapTransaction, tx_hash: string): Promise<TransactionMetadata[]>;
206
218
  /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
207
219
  indexNetworkInformation(tx: CapTransaction): Promise<NetworkInformation>;
220
+ /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
221
+ resolveNetworkInformation(tx: CapTransaction): Promise<ProviderNetworkInformation>;
208
222
  /** Index a block by hash, with best-effort epoch enrichment. */
209
223
  indexBlock(tx: CapTransaction, blockHash: string): Promise<Block>;
210
224
  /**
@@ -292,10 +306,14 @@ export declare class CardanoIndexer {
292
306
  indexEpoch(tx: CapTransaction, epochNumber: number): Promise<Epoch>;
293
307
  /** Index an account by stake address, plus its addresses when it has any. */
294
308
  indexAccount(tx: CapTransaction, stakeAddress: string): Promise<Account>;
309
+ /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
310
+ resolveAccount(tx: CapTransaction, stakeAddress: string): Promise<AccountData>;
295
311
  /** Index a DRep by bech32 id. */
296
312
  indexDrep(tx: CapTransaction, drepId: string): Promise<Drep>;
297
313
  /** Index a pool by id. */
298
314
  indexPool(tx: CapTransaction, poolId: string): Promise<Pool>;
315
+ /** Pool from the backend with crawled block counts and the snapshot's active stake. */
316
+ resolvePool(tx: CapTransaction, poolId: string): Promise<PoolData>;
299
317
  /** Index an asset by unit (policyId + assetNameHex). */
300
318
  indexAsset(tx: CapTransaction, unit: string): Promise<Asset>;
301
319
  /**
@@ -190,6 +190,53 @@ class CardanoIndexer {
190
190
  registryLogo: null,
191
191
  };
192
192
  }
193
+ /** Address from the crawled UTxO set when it answers, else from the backend. */
194
+ async resolveAddress(tx, addr) {
195
+ return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
196
+ }
197
+ /** UTxOs of an address: the crawled set (outputs from the node at the tip) when it answers, else the backend. */
198
+ async resolveAddressUtxos(tx, addr) {
199
+ return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
200
+ }
201
+ /** Asset from the crawled chain when it answers, else from the backend. */
202
+ async resolveAssetInfo(tx, unit) {
203
+ return (await this.localAssetInfo(tx, unit)) ?? await this.client.getAssetInfo(unit);
204
+ }
205
+ /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
206
+ async resolveAssetHistory(tx, unit, limit) {
207
+ if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
208
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
209
+ return (rows ?? []).map(r => ({
210
+ unit: String(r.unit),
211
+ txHash: String(r.txHash),
212
+ action: r.action === 'burn' ? 'burn' : 'mint',
213
+ quantity: String(r.quantity),
214
+ blockTime: r.blockTime == null ? null : Number(r.blockTime),
215
+ blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
216
+ }));
217
+ }
218
+ return this.client.getAssetHistory(unit, limit);
219
+ }
220
+ /** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
221
+ async resolveCredentialUtxos(tx, credHash) {
222
+ return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
223
+ }
224
+ /** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
225
+ async resolveAddressTransactionHashes(tx, addr, limit) {
226
+ const local = await this.localAddressTransactions(tx, addr, limit);
227
+ if (local && (local.complete || local.rows.length >= limit)) {
228
+ return local.rows.map(r => String(r.tx_hash));
229
+ }
230
+ try {
231
+ return await this.client.getAddressTransactionHashes(addr, limit);
232
+ }
233
+ catch (err) {
234
+ if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
235
+ return local.rows.map(r => String(r.tx_hash));
236
+ }
237
+ throw err;
238
+ }
239
+ }
193
240
  /** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
194
241
  async ledgerCoverageActive(tx) {
195
242
  return Boolean((await this.localCoverage(tx))?.ledger);
@@ -514,7 +561,7 @@ class CardanoIndexer {
514
561
  * indexAddressTransactions().
515
562
  */
516
563
  async indexAddress(tx, addr) {
517
- const addrData = (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
564
+ const addrData = await this.resolveAddress(tx, addr);
518
565
  logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
519
566
  const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
520
567
  const now = new Date().toISOString();
@@ -825,13 +872,17 @@ class CardanoIndexer {
825
872
  }
826
873
  /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
827
874
  async indexNetworkInformation(tx) {
875
+ const netEntity = (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
876
+ await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
877
+ return netEntity;
878
+ }
879
+ /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
880
+ async resolveNetworkInformation(tx) {
828
881
  const netInfo = await this.client.getNetworkInformation();
829
882
  const circulating = (await this.localCoverage(tx))?.ledger
830
883
  ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
831
884
  : null;
832
- const netEntity = (0, mappers_1.mapNetworkInfo)(circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } }, this.client.max_age_ms, this.client.network);
833
- await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
834
- return netEntity;
885
+ return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
835
886
  }
836
887
  /** Index a block by hash, with best-effort epoch enrichment. */
837
888
  async indexBlock(tx, blockHash) {
@@ -1352,6 +1403,17 @@ class CardanoIndexer {
1352
1403
  }
1353
1404
  /** Index an account by stake address, plus its addresses when it has any. */
1354
1405
  async indexAccount(tx, stakeAddress) {
1406
+ const accountInfo = await this.resolveAccount(tx, stakeAddress);
1407
+ const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
1408
+ await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
1409
+ const addresses = accountInfo.addresses.map(a => a.address);
1410
+ if (accountEntity.hasAddresses) {
1411
+ await this._ensureAddresses(tx, addresses);
1412
+ }
1413
+ return accountEntity;
1414
+ }
1415
+ /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
1416
+ async resolveAccount(tx, stakeAddress) {
1355
1417
  const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
1356
1418
  // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
1357
1419
  if ((await this.localCoverage(tx))?.ledger) {
@@ -1363,13 +1425,7 @@ class CardanoIndexer {
1363
1425
  if (local != null)
1364
1426
  accountInfo.withdrawalsSum = local;
1365
1427
  }
1366
- const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
1367
- await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
1368
- const addresses = accountInfo.addresses.map(a => a.address);
1369
- if (accountEntity.hasAddresses) {
1370
- await this._ensureAddresses(tx, addresses);
1371
- }
1372
- return accountEntity;
1428
+ return accountInfo;
1373
1429
  }
1374
1430
  /** Index a DRep by bech32 id. */
1375
1431
  async indexDrep(tx, drepId) {
@@ -1380,17 +1436,21 @@ class CardanoIndexer {
1380
1436
  }
1381
1437
  /** Index a pool by id. */
1382
1438
  async indexPool(tx, poolId) {
1439
+ const poolEntity = (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
1440
+ await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
1441
+ return poolEntity;
1442
+ }
1443
+ /** Pool from the backend with crawled block counts and the snapshot's active stake. */
1444
+ async resolvePool(tx, poolId) {
1383
1445
  const poolInfo = { ...(await this.client.getPool(poolId)), ...(await this.localPoolBlocks(tx, poolId)) };
1384
1446
  // The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
1385
1447
  if (poolInfo.activeStake === '0')
1386
1448
  Object.assign(poolInfo, await this.snapshotActiveStake(tx, poolId));
1387
- const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
1388
- await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
1389
- return poolEntity;
1449
+ return poolInfo;
1390
1450
  }
1391
1451
  /** Index an asset by unit (policyId + assetNameHex). */
1392
1452
  async indexAsset(tx, unit) {
1393
- const assetInfo = (await this.localAssetInfo(tx, unit)) ?? await this.client.getAssetInfo(unit);
1453
+ const assetInfo = await this.resolveAssetInfo(tx, unit);
1394
1454
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1395
1455
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
1396
1456
  return assetEntity;
@@ -110,7 +110,7 @@ class CardanoTransactionBuilder {
110
110
  utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
111
111
  protocolParameters: protocolParameters,
112
112
  // Pass evaluator if Ogmios is available for dynamic execution unit calculation
113
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
113
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
114
114
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
115
115
  : undefined,
116
116
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -152,7 +152,7 @@ class CardanoTransactionBuilder {
152
152
  const txContext = {
153
153
  utxos: mergedUtxos,
154
154
  protocolParameters: protocolParameters,
155
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
155
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
156
156
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
157
157
  : undefined,
158
158
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -0,0 +1,30 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
+ /**
4
+ * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
+ * serving other ODATANO instances from what this one has indexed. Not stored, so absent: the
6
+ * phase-2 flag (`spendsCollaterals`), `totalCollateral` and `outputAmount`.
7
+ */
8
+ type Row = Record<string, unknown>;
9
+ /** `Blocks` row -> BlockData. */
10
+ export declare function blockRowToData(row: Row): BlockData;
11
+ /** A stored block by hash; null when not indexed. */
12
+ export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
13
+ /** A stored block by height; null when not indexed. */
14
+ export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
15
+ /**
16
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
17
+ * the first missing height, so a caller never walks over a gap.
18
+ */
19
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
20
+ /** Stored transactions by hash (missing hashes are absent from the map). */
21
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
22
+ /**
23
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
24
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
25
+ */
26
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
27
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
28
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
29
+ export {};
30
+ //# sourceMappingURL=stored-chain.d.ts.map
@@ -0,0 +1,208 @@
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.blockRowToData = blockRowToData;
7
+ exports.readBlock = readBlock;
8
+ exports.readBlockByHeight = readBlockByHeight;
9
+ exports.readNextBlocks = readNextBlocks;
10
+ exports.readTransactionsByHash = readTransactionsByHash;
11
+ exports.readBlockTransactions = readBlockTransactions;
12
+ exports.readTransactionMetadata = readTransactionMetadata;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const client_1 = require("@cardano-ogmios/client");
15
+ const cardano_1 = require("#cds-models/odatano/cardano");
16
+ const collections_1 = require("../utils/collections");
17
+ const { SELECT } = cds_1.default.ql;
18
+ const num = (v) => Number(v ?? 0);
19
+ const numOrNull = (v) => (v == null ? null : Number(v));
20
+ const str = (v) => (v == null ? '' : String(v));
21
+ /** `Blocks` row -> BlockData. */
22
+ function blockRowToData(row) {
23
+ return {
24
+ time: Math.floor(Date.parse(str(row.time)) / 1000),
25
+ height: numOrNull(row.height),
26
+ hash: str(row.hash),
27
+ slot: numOrNull(row.slot),
28
+ slotLeader: str(row.slotLeader),
29
+ epoch: numOrNull(row.epochNumber),
30
+ epochSlot: numOrNull(row.epochSlot),
31
+ size: num(row.size),
32
+ txCount: num(row.txCount),
33
+ fees: row.fees == null ? null : String(row.fees),
34
+ };
35
+ }
36
+ /** A stored block by hash; null when not indexed. */
37
+ async function readBlock(db, hash) {
38
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ hash }));
39
+ return row ? blockRowToData(row) : null;
40
+ }
41
+ /** A stored block by height; null when not indexed. */
42
+ async function readBlockByHeight(db, height) {
43
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
44
+ return row ? blockRowToData(row) : null;
45
+ }
46
+ /**
47
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
48
+ * the first missing height, so a caller never walks over a gap.
49
+ */
50
+ async function readNextBlocks(db, afterHeight, count) {
51
+ const rows = await db.run(SELECT.from(cardano_1.Blocks).where({ height: { '>': afterHeight, '<=': afterHeight + count } }).orderBy('height asc'));
52
+ const out = [];
53
+ let expected = afterHeight + 1;
54
+ for (const row of rows ?? []) {
55
+ if (num(row.height) !== expected)
56
+ break;
57
+ out.push(blockRowToData(row));
58
+ expected++;
59
+ }
60
+ return out;
61
+ }
62
+ /** Stored transactions by hash (missing hashes are absent from the map). */
63
+ async function readTransactionsByHash(db, hashes) {
64
+ const rows = [];
65
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
66
+ rows.push(...((await db.run(SELECT.from(cardano_1.Transactions).where({ hash: { in: hashChunk } }))) ?? []));
67
+ }
68
+ const txs = await assembleTransactions(db, rows);
69
+ return new Map(txs.map(t => [t.hash, t]));
70
+ }
71
+ /**
72
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
73
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
74
+ */
75
+ async function readBlockTransactions(db, blockHash) {
76
+ const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
77
+ if (!block)
78
+ return null;
79
+ const rows = await db.run(SELECT.from(cardano_1.Transactions).where({ blockHash }).orderBy('txIndex asc'));
80
+ if ((rows ?? []).length !== num(block.txCount))
81
+ return null;
82
+ return assembleTransactions(db, rows ?? []);
83
+ }
84
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
85
+ async function readTransactionMetadata(db, txHash) {
86
+ const known = await db.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ hash: txHash }));
87
+ if (!known)
88
+ return null;
89
+ const rows = await db.run(SELECT.from(cardano_1.TransactionMetadata_).where({ tx_hash: txHash }));
90
+ return (rows ?? []).map(metadataRow);
91
+ }
92
+ function metadataRow(r) {
93
+ return {
94
+ txHash: str(r.tx_hash),
95
+ label: str(r.label),
96
+ json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
97
+ };
98
+ }
99
+ /** Amount list with lovelace first, as the providers deliver it. */
100
+ function amounts(assets) {
101
+ const list = assets.map(a => ({ unit: str(a.unit), quantity: str(a.asset_quantity) }));
102
+ return [...list.filter(a => a.unit === 'lovelace'), ...list.filter(a => a.unit !== 'lovelace')];
103
+ }
104
+ function groupBy(rows, key) {
105
+ const out = new Map();
106
+ for (const r of rows) {
107
+ const k = key(r);
108
+ const list = out.get(k);
109
+ if (list)
110
+ list.push(r);
111
+ else
112
+ out.set(k, [r]);
113
+ }
114
+ return out;
115
+ }
116
+ /** Transactions rows + their child tables -> provider transactions, in the order of `rows`. */
117
+ async function assembleTransactions(db, rows) {
118
+ if (rows.length === 0)
119
+ return [];
120
+ const seqs = rows.map(r => r.txSeq);
121
+ const hashes = rows.map(r => str(r.hash));
122
+ const fetchIn = async (entity, column, keys) => {
123
+ const out = [];
124
+ for (const c of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
125
+ out.push(...((await db.run(SELECT.from(entity).where({ [column]: { in: c } }))) ?? []));
126
+ }
127
+ return out;
128
+ };
129
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints] = await Promise.all([
130
+ fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
131
+ fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
132
+ fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
133
+ fetchIn(cardano_1.TransactionOutputAssets, 'output_txSeq', seqs),
134
+ fetchIn(cardano_1.TransactionMetadata_, 'tx_hash', hashes),
135
+ fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
136
+ fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
137
+ fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
138
+ ]);
139
+ const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
140
+ const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
141
+ const outputsBySeq = groupBy(outputs, r => str(r.txSeq));
142
+ const outputAssetsByKey = groupBy(outputAssets, r => `${r.output_txSeq}#${r.output_outputIndex}`);
143
+ const metadataByHash = groupBy(metadata, r => str(r.tx_hash));
144
+ const certsByHash = groupBy(certificates, r => str(r.tx_hash));
145
+ const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
146
+ const mintsByHash = groupBy(mints, r => str(r.txHash));
147
+ return rows.map((t) => {
148
+ const seq = str(t.txSeq);
149
+ const hash = str(t.hash);
150
+ const txInputs = (inputsBySeq.get(seq) ?? [])
151
+ .sort((a, b) => num(a.inputIndex) - num(b.inputIndex))
152
+ .map(i => ({
153
+ address: str(i.address_address),
154
+ amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
155
+ txHash: str(i.spentTxHash),
156
+ outputIndex: num(i.spentOutputIndex),
157
+ dataHash: i.utxoData_dataHash ?? null,
158
+ inlineDatum: i.utxoData_inlineDatum ?? null,
159
+ referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
160
+ isCollateral: Boolean(i.isCollateral),
161
+ isReference: Boolean(i.isReference),
162
+ }));
163
+ const txOutputs = (outputsBySeq.get(seq) ?? [])
164
+ .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
165
+ .map(o => ({
166
+ address: str(o.address_address),
167
+ amount: amounts(outputAssetsByKey.get(`${seq}#${o.outputIndex}`) ?? []),
168
+ txHash: hash,
169
+ outputIndex: num(o.outputIndex),
170
+ dataHash: o.utxo_dataHash ?? null,
171
+ inlineDatum: o.utxo_inlineDatum ?? null,
172
+ isCollateral: false,
173
+ referenceScriptHash: o.utxo_referenceScriptHash ?? null,
174
+ }));
175
+ const certs = certsByHash.get(hash);
176
+ const withdrawn = withdrawalsByHash.get(hash);
177
+ const minted = mintsByHash.get(hash);
178
+ return {
179
+ hash,
180
+ blockHash: str(t.blockHash),
181
+ blockHeight: num(t.blockHeight),
182
+ slot: num(t.slot),
183
+ index: num(t.txIndex),
184
+ fee: str(t.fee ?? '0'),
185
+ deposit: str(t.deposit ?? '0'),
186
+ size: numOrNull(t.size),
187
+ blockTime: num(t.blockTime),
188
+ mint: minted?.map(m => ({
189
+ unit: str(m.unit),
190
+ quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
191
+ })),
192
+ inputs: txInputs,
193
+ outputs: txOutputs,
194
+ metadata: (metadataByHash.get(hash) ?? []).map(metadataRow),
195
+ certificates: certs?.map((c) => ({
196
+ certIndex: num(c.certIndex),
197
+ kind: str(c.kind),
198
+ stakeAddress: c.stakeAddress ?? null,
199
+ poolId: c.poolId ?? null,
200
+ drepId: c.drepId ?? null,
201
+ deposit: c.deposit == null ? null : String(c.deposit),
202
+ epoch: numOrNull(c.epoch),
203
+ })),
204
+ withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
205
+ };
206
+ });
207
+ }
208
+ //# sourceMappingURL=stored-chain.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Cardano Backend Service
3
+ *
4
+ * The data a CardanoBackend needs, for another ODATANO instance that uses this one as its
5
+ * backend (`backends: ["odatano"]`). Every operation answers the provider shape as a JSON
6
+ * string (`value`), so the caller maps it exactly like a Koios or Blockfrost answer.
7
+ * Stored blocks and transactions come from this instance's index; everything else goes
8
+ * through its own backends and crawled data, as the read service does. Nothing is persisted
9
+ * for the caller.
10
+ */
11
+ @requires: 'authenticated-user'
12
+ service CardanoBackendService @(impl: './cardano-backend-service') {
13
+
14
+ // --- blocks and transactions -------------------------------------------------------------
15
+ action GetTransaction(hash: String) returns LargeString;
16
+ action GetTransactionsBatch(hashes: LargeString) returns LargeString;
17
+ action GetTransactionMetadata(hash: String) returns LargeString;
18
+ action GetBlock(hash: String) returns LargeString;
19
+ action GetBlockByHeight(height: Integer64) returns LargeString;
20
+ action GetNextBlocks(afterHash: String, count: Integer, afterHeight: Integer64) returns LargeString;
21
+ action GetBlockTransactions(blockHash: String) returns LargeString;
22
+ action GetLatestBlock() returns LargeString;
23
+ action GetCurrentSlot() returns LargeString;
24
+ action GetEpoch(epoch: Integer) returns LargeString;
25
+ action GetLatestEpoch() returns LargeString;
26
+
27
+ // --- addresses and UTxOs ------------------------------------------------------------------
28
+ action GetAddress(address: String) returns LargeString;
29
+ action GetAddressUtxos(address: String) returns LargeString;
30
+ action GetAddressTransactions(address: String, limit: Integer) returns LargeString;
31
+ action GetAddressTransactionHashes(address: String, limit: Integer) returns LargeString;
32
+ action GetCredentialUtxos(credential: String) returns LargeString;
33
+ action IsUtxoUnspent(txHash: String, outputIndex: Integer) returns LargeString;
34
+ action GetUnspentOutputs(refs: LargeString) returns LargeString;
35
+
36
+ // --- stake, governance, assets, network ------------------------------------------------
37
+ action GetAccount(stakeAddress: String) returns LargeString;
38
+ action GetPool(poolId: String) returns LargeString;
39
+ action GetPoolIds() returns LargeString;
40
+ action GetPools(ids: LargeString) returns LargeString;
41
+ action GetDrep(drepId: String) returns LargeString;
42
+ action GetDrepIds() returns LargeString;
43
+ action GetDreps(ids: LargeString) returns LargeString;
44
+ action GetAssetInfo(unit: String) returns LargeString;
45
+ action GetAssetHistory(unit: String, limit: Integer) returns LargeString;
46
+ action GetNetworkInformation() returns LargeString;
47
+ action GetProtocolParameters() returns LargeString;
48
+
49
+ // --- transactions in flight ------------------------------------------------------------
50
+ action EvaluateTransaction(cbor: LargeString) returns LargeString;
51
+ action SubmitTransaction(cbor: LargeString) returns LargeString;
52
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-backend-service.d.ts.map