@odatano/core 2.0.0-rc.49 → 2.0.0-rc.50
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.
- package/@cds-models/CardanoAgentService/index.d.ts +6 -12
- package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
- package/@cds-models/CardanoIndexerService/index.js +24 -0
- package/@cds-models/CardanoODataService/index.d.ts +49 -6
- package/@cds-models/CardanoODataService/index.js +4 -0
- package/@cds-models/CardanoSignService/index.d.ts +3 -3
- package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
- package/@cds-models/index.d.ts +9 -1
- package/@cds-models/index.js +2 -1
- package/@cds-models/odatano/cardano/index.d.ts +59 -5
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +29 -17
- package/db/schema.cds +117 -24
- package/db/types.cds +8 -0
- package/package.json +17 -15
- package/scripts/migrate-schema.mjs +334 -0
- package/src/index.d.ts +7 -5
- package/src/index.js +12 -10
- package/src/plugin.js +6 -7
- package/srv/blockchain/backends/blockfrost-backend.js +9 -1
- package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
- package/srv/blockchain/backends/cardano-backend.js +5 -0
- package/srv/blockchain/backends/koios-backend.js +16 -10
- package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
- package/srv/blockchain/backends/ogmios-backend.js +60 -18
- package/srv/blockchain/cardano-client.d.ts +5 -4
- package/srv/blockchain/cardano-client.js +46 -13
- package/srv/blockchain/cardano-indexer.d.ts +116 -9
- package/srv/blockchain/cardano-indexer.js +436 -189
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
- package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
- package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/certificate-backfill.js +10 -3
- package/srv/blockchain/crawler/crawler.d.ts +15 -0
- package/srv/blockchain/crawler/crawler.js +68 -3
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/transaction-backfill.js +12 -8
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
- package/srv/blockchain/signing/cose-verifier.js +144 -56
- package/srv/blockchain/signing/hsm-signer.js +2 -1
- package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
- package/srv/blockchain/signing/submission-finalizer.js +201 -69
- package/srv/blockchain/stored-chain.js +1 -1
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.js +1 -1
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
- package/srv/blockchain/wallet-worker/build-request.js +25 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
- package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
- package/srv/cardano-agent-service.cds +11 -12
- package/srv/cardano-agent-service.js +2 -0
- package/srv/cardano-backend-service.cds +34 -1
- package/srv/cardano-backend-service.js +20 -17
- package/srv/cardano-indexer-service.cds +153 -12
- package/srv/cardano-indexer-service.js +175 -29
- package/srv/cardano-service.cds +67 -3
- package/srv/cardano-service.js +132 -67
- package/srv/cardano-sign-service.cds +30 -20
- package/srv/cardano-sign-service.js +13 -10
- package/srv/cardano-tx-service.cds +15 -1
- package/srv/cardano-tx-service.js +4 -1
- package/srv/cardano-worker-service.cds +16 -7
- package/srv/cardano-worker-service.js +31 -22
- package/srv/cbor/parse.js +11 -34
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +9 -14
- package/srv/server.js +32 -316
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -17
- package/srv/utils/agent-grants-config.js +6 -81
- package/srv/utils/agent-grants.d.ts +6 -19
- package/srv/utils/agent-grants.js +69 -130
- package/srv/utils/const.d.ts +4 -0
- package/srv/utils/const.js +5 -1
- package/srv/utils/db-indexes.js +11 -3
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/errors.d.ts +6 -0
- package/srv/utils/errors.js +23 -1
- package/srv/utils/liveness.js +2 -5
- package/srv/utils/mappers.d.ts +5 -7
- package/srv/utils/mappers.js +22 -9
- package/srv/utils/pg-order-nulls.js +4 -3
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/tx-request-parsers.d.ts +1 -1
- package/srv/utils/tx-request-parsers.js +3 -3
- package/srv/utils/tx-utils.d.ts +3 -0
- package/srv/utils/tx-utils.js +17 -3
- package/srv/utils/types.d.ts +16 -3
- package/scripts/migrate-txseq.mjs +0 -138
- package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
- package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
- package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
- package/srv/blockchain/transaction-building/caller-datums.js +0 -133
- package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
- package/srv/cbor/redeemer-tag-patch.js +0 -61
- package/srv/utils/legacy-service-paths.d.ts +0 -11
- package/srv/utils/legacy-service-paths.js +0 -58
|
@@ -15,19 +15,21 @@ const mappers_1 = require("../utils/mappers");
|
|
|
15
15
|
const errors_1 = require("../utils/errors");
|
|
16
16
|
const collections_1 = require("../utils/collections");
|
|
17
17
|
const deep_json_1 = require("../utils/deep-json");
|
|
18
|
+
const tx_utils_1 = require("../utils/tx-utils");
|
|
18
19
|
const transaction_rows_1 = require("./transaction-rows");
|
|
19
20
|
const ledger_state_1 = require("./ledger-state");
|
|
20
21
|
const sync_state_1 = require("./crawler/sync-state");
|
|
21
22
|
const asset_decimals_1 = require("./asset-decimals");
|
|
23
|
+
const pool_metadata_1 = require("./pool-metadata");
|
|
22
24
|
const epoch_slots_1 = require("../utils/epoch-slots");
|
|
23
25
|
const const_1 = require("../utils/const");
|
|
24
26
|
const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
|
|
25
27
|
const logger = cds_1.default.log('CardanoIndexer');
|
|
26
|
-
/** Datum hash, inline datum and reference script of the spent output onto its input. */
|
|
27
28
|
/** Newest first; the tx hash breaks ties inside one block. */
|
|
28
29
|
function sortAddressTransactions(rows) {
|
|
29
30
|
return rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0) || String(b.tx_hash).localeCompare(String(a.tx_hash)));
|
|
30
31
|
}
|
|
32
|
+
/** Datum hash, inline datum and reference script of the spent output onto its input. */
|
|
31
33
|
function copyUtxoData(input, out) {
|
|
32
34
|
input.dataHash = input.dataHash ?? out.utxo_dataHash ?? null;
|
|
33
35
|
input.inlineDatum = input.inlineDatum ?? out.utxo_inlineDatum ?? null;
|
|
@@ -82,6 +84,8 @@ class CardanoIndexer {
|
|
|
82
84
|
crawlUtxoSet = false;
|
|
83
85
|
/** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
|
|
84
86
|
crawlAuthoritative = false;
|
|
87
|
+
/** crawler.inputAssetCopies: every crawled input keeps a copy of its assets and points at no output. */
|
|
88
|
+
crawlInputAssetCopies = false;
|
|
85
89
|
utxoAnchor = null;
|
|
86
90
|
/** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
|
|
87
91
|
credentialsReady = false;
|
|
@@ -91,6 +95,10 @@ class CardanoIndexer {
|
|
|
91
95
|
utxoAnchorVerified = false;
|
|
92
96
|
/** Kept until the crawler confirms the block commit, so a rolled-back attempt changes nothing. */
|
|
93
97
|
ledgerInvalidation = null;
|
|
98
|
+
/** Load pool metadata files from their registered URL. Off unless configured. */
|
|
99
|
+
poolMetadataFetch = false;
|
|
100
|
+
poolMetadataByHash = new Map();
|
|
101
|
+
static POOL_METADATA_MEMO_CAP = 10_000;
|
|
94
102
|
/** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
|
|
95
103
|
static ASSET_MEMO_CAP = 200_000;
|
|
96
104
|
/** Output references per node lookup when checking crawled UTxOs. */
|
|
@@ -105,6 +113,7 @@ class CardanoIndexer {
|
|
|
105
113
|
/** Adopt the crawler's coverage settings; the lazy request path never touches these. */
|
|
106
114
|
configureCrawlCoverage(coverage) {
|
|
107
115
|
this.crawlAuthoritative = coverage.authoritative ?? false;
|
|
116
|
+
this.crawlInputAssetCopies = coverage.inputAssetCopies ?? false;
|
|
108
117
|
this.crawlAssetHistory = coverage.assetHistory;
|
|
109
118
|
this.crawlAssetCatalogue = coverage.assetCatalogue;
|
|
110
119
|
this.crawlCertificates = coverage.certificates ?? false;
|
|
@@ -212,22 +221,28 @@ class CardanoIndexer {
|
|
|
212
221
|
}
|
|
213
222
|
/** Asset from the crawled chain when it answers, else from the backend. */
|
|
214
223
|
async resolveAssetInfo(tx, unit) {
|
|
215
|
-
return (await this.localAssetInfo(
|
|
224
|
+
return (await (0, tx_utils_1.readOutside)(tx, (db) => this.localAssetInfo(db, unit))) ?? await this.client.getAssetInfo(unit);
|
|
225
|
+
}
|
|
226
|
+
/** Stored mint/burn rows, newest first. Null when the crawled chain does not answer for them. */
|
|
227
|
+
async crawledAssetHistory(tx, unit, limit) {
|
|
228
|
+
if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetHistory')))
|
|
229
|
+
return null;
|
|
230
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc', 'txHash desc').limit(limit));
|
|
231
|
+
return rows ?? [];
|
|
216
232
|
}
|
|
217
233
|
/** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
|
|
218
234
|
async resolveAssetHistory(tx, unit, limit) {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
return (
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
return this.client.getAssetHistory(unit, limit);
|
|
235
|
+
const rows = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
|
|
236
|
+
if (!rows)
|
|
237
|
+
return this.client.getAssetHistory(unit, limit);
|
|
238
|
+
return rows.map(r => ({
|
|
239
|
+
unit: String(r.unit),
|
|
240
|
+
txHash: String(r.txHash),
|
|
241
|
+
action: r.action === 'burn' ? 'burn' : 'mint',
|
|
242
|
+
quantity: String(r.quantity),
|
|
243
|
+
blockTime: r.blockTime == null ? null : Number(r.blockTime),
|
|
244
|
+
blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
|
|
245
|
+
}));
|
|
231
246
|
}
|
|
232
247
|
/** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
|
|
233
248
|
async resolveCredentialUtxos(tx, credHash) {
|
|
@@ -235,7 +250,7 @@ class CardanoIndexer {
|
|
|
235
250
|
}
|
|
236
251
|
/** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
|
|
237
252
|
async resolveAddressTransactionHashes(tx, addr, limit) {
|
|
238
|
-
const local = await this.localAddressTransactions(
|
|
253
|
+
const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
|
|
239
254
|
if (local && (local.complete || local.rows.length >= limit)) {
|
|
240
255
|
return local.rows.map(r => String(r.tx_hash));
|
|
241
256
|
}
|
|
@@ -256,20 +271,16 @@ class CardanoIndexer {
|
|
|
256
271
|
// Address from the crawled UTxO set. An address the set never saw is empty, not an error.
|
|
257
272
|
// Null when the set cannot answer.
|
|
258
273
|
async localAddress(tx, addr) {
|
|
259
|
-
|
|
274
|
+
const rows = await (0, tx_utils_1.readOutside)(tx, async (db) => (await this.localCoverage(db))?.ledger ? this.ledgerUtxosOf(db, [addr]) : null);
|
|
275
|
+
if (!rows)
|
|
260
276
|
return null;
|
|
261
|
-
return addressFromUtxos(addr, await this.
|
|
277
|
+
return addressFromUtxos(addr, await this.unspentAtNode(rows));
|
|
262
278
|
}
|
|
263
|
-
/** Addresses of a stake key
|
|
264
|
-
async
|
|
279
|
+
/** Addresses of a stake key in the crawled UTxO set, with their stored unspent outputs (one read for all). */
|
|
280
|
+
async ledgerAccountUtxos(tx, stakeAddress) {
|
|
265
281
|
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
|
|
266
282
|
const addresses = (rows ?? []).map(r => r.address);
|
|
267
|
-
|
|
268
|
-
return [];
|
|
269
|
-
const byAddress = new Map(addresses.map(a => [a, []]));
|
|
270
|
-
for (const u of await this.openLedgerUtxos(tx, addresses))
|
|
271
|
-
byAddress.get(u.address)?.push(u);
|
|
272
|
-
return addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
|
|
283
|
+
return { addresses, utxos: addresses.length ? await this.ledgerUtxosOf(tx, addresses) : [] };
|
|
273
284
|
}
|
|
274
285
|
// Transactions that paid to or spent from the address since the anchor. complete is true when the
|
|
275
286
|
// address first appeared after the anchor, so nothing older exists. Null when the set cannot answer.
|
|
@@ -480,16 +491,18 @@ class CardanoIndexer {
|
|
|
480
491
|
if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
|
|
481
492
|
return null;
|
|
482
493
|
const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
|
|
483
|
-
.columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(
|
|
494
|
+
.columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(slot) as firstSlot', 'max(slot) as lastSlot')
|
|
484
495
|
.where({ epochNumber }));
|
|
485
496
|
if (!row || Number(row.blockCount ?? 0) === 0)
|
|
486
497
|
return null;
|
|
498
|
+
// The slot gives the block time exactly; a time aggregate comes back in the database's own form.
|
|
499
|
+
const timeOf = (slot) => slot == null ? null : (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, Number(slot));
|
|
487
500
|
return {
|
|
488
501
|
blockCount: Number(row.blockCount),
|
|
489
502
|
txCount: Number(row.txCount ?? 0),
|
|
490
503
|
fees: lovelaceSum(row.fees),
|
|
491
|
-
firstBlockTime:
|
|
492
|
-
lastBlockTime:
|
|
504
|
+
firstBlockTime: timeOf(row.firstSlot),
|
|
505
|
+
lastBlockTime: timeOf(row.lastSlot),
|
|
493
506
|
};
|
|
494
507
|
}
|
|
495
508
|
catch (err) {
|
|
@@ -509,6 +522,37 @@ class CardanoIndexer {
|
|
|
509
522
|
activeStake: null,
|
|
510
523
|
};
|
|
511
524
|
}
|
|
525
|
+
// Writes block count, transaction count, fees and first and last block time of every epoch the
|
|
526
|
+
// crawl covers in full, from the stored blocks. An epoch without a row gets one. No backend.
|
|
527
|
+
async backfillEpochs(onProgress) {
|
|
528
|
+
const progress = { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
|
|
529
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
530
|
+
if (cursor?.startSlot == null)
|
|
531
|
+
return progress;
|
|
532
|
+
const network = this.client.network;
|
|
533
|
+
progress.toEpoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.lastSlot);
|
|
534
|
+
for (let epoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.startSlot); epoch <= progress.toEpoch; epoch++) {
|
|
535
|
+
const totals = await this.crawledEpochTotals(epoch);
|
|
536
|
+
if (totals) {
|
|
537
|
+
const created = await cds_1.default.tx(async (tx) => {
|
|
538
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Epoch).columns('epoch').where({ epoch }));
|
|
539
|
+
if (stored)
|
|
540
|
+
await tx.run(UPDATE.entity(CardanoODataService_1.Epoch).set(totals).where({ epoch }));
|
|
541
|
+
else
|
|
542
|
+
await tx.run(INSERT.into(CardanoODataService_1.Epoch).entries({ ...this.bareEpochRow(epoch), ...totals }));
|
|
543
|
+
return !stored;
|
|
544
|
+
});
|
|
545
|
+
if (created)
|
|
546
|
+
progress.created++;
|
|
547
|
+
else
|
|
548
|
+
progress.updated++;
|
|
549
|
+
}
|
|
550
|
+
progress.atEpoch = epoch;
|
|
551
|
+
onProgress?.({ ...progress });
|
|
552
|
+
}
|
|
553
|
+
logger.info(`epochs rebuilt from crawled blocks: ${progress.updated} updated, ${progress.created} created, up to epoch ${progress.toEpoch}`);
|
|
554
|
+
return progress;
|
|
555
|
+
}
|
|
512
556
|
constructor(client, txBuilder) {
|
|
513
557
|
this.client = client;
|
|
514
558
|
this.txBuilder = txBuilder;
|
|
@@ -516,22 +560,30 @@ class CardanoIndexer {
|
|
|
516
560
|
logger.info('CardanoIndexer instance created');
|
|
517
561
|
}
|
|
518
562
|
// Unspent outputs for the transaction builder. Null when the set cannot answer.
|
|
519
|
-
//
|
|
563
|
+
// Reads through the running request's transaction, which stays idle unless it already holds its connection.
|
|
520
564
|
async localAddressUtxos(address) {
|
|
521
565
|
if (!cds_1.default.db)
|
|
522
566
|
return null;
|
|
523
|
-
|
|
567
|
+
const tx = (cds_1.default.context ? cds_1.default.tx(cds_1.default.context) : cds_1.default.db);
|
|
568
|
+
return (await this.localAddress(tx, address))?.utxos ?? null;
|
|
569
|
+
}
|
|
570
|
+
/** A transaction from the backend. 404 when the crawled chain answers for it alone. */
|
|
571
|
+
async fetchTransaction(tx, txHash) {
|
|
572
|
+
await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getTransaction', `Transaction ${txHash}`));
|
|
573
|
+
return this.client.getTransaction(txHash);
|
|
524
574
|
}
|
|
525
575
|
/** All UPSERTs run in the caller's transaction, so everything persists or nothing does. */
|
|
526
|
-
async
|
|
527
|
-
await this.refuseOutsideCrawl(tx, 'getTransaction', `Transaction ${txHash}`);
|
|
528
|
-
const providerTx = await this.client.getTransaction(txHash);
|
|
576
|
+
async storeTransaction(tx, providerTx) {
|
|
529
577
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
530
578
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
531
|
-
logger.debug(`indexTransaction: upserted transaction ${
|
|
579
|
+
logger.debug(`indexTransaction: upserted transaction ${providerTx.hash}`);
|
|
532
580
|
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
533
581
|
return txRow;
|
|
534
582
|
}
|
|
583
|
+
/** Reads a transaction from the backend and stores it. */
|
|
584
|
+
async indexTransaction(tx, txHash) {
|
|
585
|
+
return this.storeTransaction(tx, await this.fetchTransaction(tx, txHash));
|
|
586
|
+
}
|
|
535
587
|
/** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
|
|
536
588
|
async writeTransactionChildren(tx, providerTx, txSeq) {
|
|
537
589
|
if (providerTx.inputs) {
|
|
@@ -540,7 +592,7 @@ class CardanoIndexer {
|
|
|
540
592
|
if (inputRows.length)
|
|
541
593
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
542
594
|
if (inputAssetRows.length)
|
|
543
|
-
await tx.run(UPSERT.into(
|
|
595
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
|
|
544
596
|
}
|
|
545
597
|
// outputs must not depend on the inputs branch
|
|
546
598
|
if (providerTx.outputs) {
|
|
@@ -551,15 +603,31 @@ class CardanoIndexer {
|
|
|
551
603
|
if (outputAssetRows.length)
|
|
552
604
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
553
605
|
}
|
|
554
|
-
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
|
|
606
|
+
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || [], txSeq);
|
|
555
607
|
if (metadataRows.length)
|
|
556
608
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
557
609
|
}
|
|
558
|
-
//
|
|
610
|
+
// An address and its ten newest transactions, read but not stored.
|
|
559
611
|
// prefetched is address data the caller already fetched in a batch.
|
|
612
|
+
async fetchAddress(tx, addr, prefetched) {
|
|
613
|
+
const data = prefetched ?? await this.resolveAddress(tx, addr);
|
|
614
|
+
logger.debug(`indexAddress: provider response for ${addr}: ${data.amount?.length ?? 0} amounts, ${data.utxos?.length ?? 0} utxos`);
|
|
615
|
+
let transactions = null;
|
|
616
|
+
try {
|
|
617
|
+
transactions = await this.fetchAddressTransactions(tx, addr, 10);
|
|
618
|
+
}
|
|
619
|
+
catch (err) {
|
|
620
|
+
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
621
|
+
}
|
|
622
|
+
return { address: addr, data, transactions };
|
|
623
|
+
}
|
|
624
|
+
/** Reads an address and its newest transactions, then stores them. */
|
|
560
625
|
async indexAddress(tx, addr, prefetched) {
|
|
561
|
-
|
|
562
|
-
|
|
626
|
+
return this.storeAddress(tx, await this.fetchAddress(tx, addr, prefetched));
|
|
627
|
+
}
|
|
628
|
+
/** Stores what fetchAddress read: the address, its assets, UTxOs and newest transactions. */
|
|
629
|
+
async storeAddress(tx, fetched) {
|
|
630
|
+
const { address: addr, data: addrData } = fetched;
|
|
563
631
|
const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
|
|
564
632
|
const now = new Date().toISOString();
|
|
565
633
|
const validFrom = AddrEntity.validFrom ?? now;
|
|
@@ -601,24 +669,34 @@ class CardanoIndexer {
|
|
|
601
669
|
logger.debug(`indexAddress: ${utxoAssetEntities.length} assets, ${uniqueAssets.length} unique (removed ${utxoAssetEntities.length - uniqueAssets.length} duplicates)`);
|
|
602
670
|
await tx.run(UPSERT.into(CardanoODataService_1.UTxOAssets).entries(uniqueAssets));
|
|
603
671
|
}
|
|
604
|
-
//
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
672
|
+
// Recent transactions are always stored with the address (regardless of asset presence)
|
|
673
|
+
if (fetched.transactions) {
|
|
674
|
+
try {
|
|
675
|
+
const txEntities = await this.storeAddressTransactions(tx, fetched.transactions);
|
|
676
|
+
if (txEntities.length > 0) {
|
|
677
|
+
await tx.run(UPDATE.entity(CardanoODataService_1.Addresses).set({ hasTransactions: true }).where({ address: addr }));
|
|
678
|
+
AddrEntity.hasTransactions = true;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
catch (err) {
|
|
682
|
+
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
610
683
|
}
|
|
611
|
-
}
|
|
612
|
-
catch (err) {
|
|
613
|
-
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
614
684
|
}
|
|
615
685
|
return AddrEntity;
|
|
616
686
|
}
|
|
617
|
-
/**
|
|
618
|
-
async
|
|
687
|
+
/** UTxOs of a payment credential, always fresh: the crawled set when it answers, else the backend. */
|
|
688
|
+
async fetchCredentialUtxos(tx, credHash) {
|
|
619
689
|
const local = await this.localCredentialUtxos(tx, credHash);
|
|
620
690
|
const utxos = local ?? await this.client.getCredentialUtxos(credHash);
|
|
621
691
|
logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
|
|
692
|
+
return utxos;
|
|
693
|
+
}
|
|
694
|
+
/** Reads the UTxOs of a payment credential and stores them. */
|
|
695
|
+
async indexCredentialUtxos(tx, credHash) {
|
|
696
|
+
return this.storeCredentialUtxos(tx, await this.fetchCredentialUtxos(tx, credHash));
|
|
697
|
+
}
|
|
698
|
+
/** Stores credential UTxOs. Rows are written without a parent Addresses row. */
|
|
699
|
+
async storeCredentialUtxos(tx, utxos) {
|
|
622
700
|
if (utxos.length === 0)
|
|
623
701
|
return [];
|
|
624
702
|
// Koios returns UTxOs of every address form sharing the credential.
|
|
@@ -657,18 +735,20 @@ class CardanoIndexer {
|
|
|
657
735
|
// Credential UTxOs from the crawled set. Null when the set cannot answer yet.
|
|
658
736
|
// An address first used in the last confirmationDepth blocks is not in the set yet.
|
|
659
737
|
async localCredentialUtxos(tx, credHash) {
|
|
660
|
-
|
|
738
|
+
const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
739
|
+
if (!(await this.localCoverage(db))?.ledger || !(await this.paymentCredentialsReady()))
|
|
740
|
+
return null;
|
|
741
|
+
const rows = await db.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
|
|
742
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
743
|
+
return addresses.length ? this.ledgerUtxosOf(db, addresses) : [];
|
|
744
|
+
});
|
|
745
|
+
if (!stored)
|
|
661
746
|
return null;
|
|
662
|
-
|
|
663
|
-
const addresses = (rows ?? []).map(r => r.address);
|
|
664
|
-
if (addresses.length === 0)
|
|
665
|
-
return [];
|
|
666
|
-
return this.openLedgerUtxos(tx, addresses);
|
|
747
|
+
return this.unspentAtNode(stored);
|
|
667
748
|
}
|
|
668
749
|
// Crawled outputs checked against the node by output reference, to drop what was spent after
|
|
669
750
|
// the cursor. The node's address query would scan its whole UTxO set. Falls back to the set as is.
|
|
670
|
-
async
|
|
671
|
-
const rows = await this.ledgerUtxosOf(tx, addresses);
|
|
751
|
+
async unspentAtNode(rows) {
|
|
672
752
|
if (rows.length === 0)
|
|
673
753
|
return rows;
|
|
674
754
|
try {
|
|
@@ -744,9 +824,15 @@ class CardanoIndexer {
|
|
|
744
824
|
this.credentialsReady = false;
|
|
745
825
|
}
|
|
746
826
|
// Skips getAddress, so it works on backends without address aggregation such as Ogmios.
|
|
747
|
-
// Writes no parent Addresses row.
|
|
748
827
|
async indexAddressUtxos(tx, addr) {
|
|
749
|
-
|
|
828
|
+
return this.storeAddressUtxos(tx, addr, await this.fetchAddressUtxos(addr));
|
|
829
|
+
}
|
|
830
|
+
/** The UTxOs of an address from the backend. */
|
|
831
|
+
async fetchAddressUtxos(addr) {
|
|
832
|
+
return this.client.getAddressUtxos(addr);
|
|
833
|
+
}
|
|
834
|
+
/** Stores the UTxOs of an address. Writes no parent Addresses row. */
|
|
835
|
+
async storeAddressUtxos(tx, addr, utxos) {
|
|
750
836
|
logger.debug(`indexAddressUtxos: provider returned ${utxos.length} utxos for ${addr}`);
|
|
751
837
|
const validFrom = new Date().toISOString();
|
|
752
838
|
const validTo = new Date(Date.now() + this.client.max_age_ms).toISOString();
|
|
@@ -788,13 +874,14 @@ class CardanoIndexer {
|
|
|
788
874
|
}
|
|
789
875
|
/** Index address transactions (separate from indexAddress for lazy loading). */
|
|
790
876
|
async indexAddressTransactions(tx, addr, limit) {
|
|
877
|
+
return this.storeAddressTransactions(tx, await this.fetchAddressTransactions(tx, addr, limit));
|
|
878
|
+
}
|
|
879
|
+
// The newest transactions of an address, read but not stored.
|
|
880
|
+
// Rows this address already has stay as stored; only new hashes are fetched.
|
|
881
|
+
async fetchAddressTransactions(tx, addr, limit) {
|
|
791
882
|
logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
|
|
792
|
-
const local = await this.localAddressTransactions(
|
|
793
|
-
const keepLocal =
|
|
794
|
-
if (local.rows.length)
|
|
795
|
-
await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(local.rows));
|
|
796
|
-
return local.rows;
|
|
797
|
-
};
|
|
883
|
+
const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
|
|
884
|
+
const keepLocal = () => ({ rows: local.rows, newRows: local.rows, transactions: new Map() });
|
|
798
885
|
if (local && (local.complete || local.rows.length >= limit))
|
|
799
886
|
return keepLocal();
|
|
800
887
|
// Hash-only listing (one API call)
|
|
@@ -810,21 +897,25 @@ class CardanoIndexer {
|
|
|
810
897
|
}
|
|
811
898
|
logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
|
|
812
899
|
if (txHashes.length === 0)
|
|
813
|
-
return [];
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
900
|
+
return { rows: [], newRows: [], transactions: new Map() };
|
|
901
|
+
const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
902
|
+
const known = await db.run(SELECT.from(CardanoODataService_1.AddressTransactions).where({ address_address: addr, tx_hash: { in: txHashes } })) ?? [];
|
|
903
|
+
const knownHashes = new Set(known.map(r => r.tx_hash));
|
|
904
|
+
const newHashes = txHashes.filter(h => !knownHashes.has(h));
|
|
905
|
+
return { known, newHashes, unstored: newHashes.length ? await this.unstoredTransactionHashes(db, newHashes) : [] };
|
|
906
|
+
});
|
|
907
|
+
const { known, newHashes } = stored;
|
|
818
908
|
if (!newHashes.length)
|
|
819
|
-
return sortAddressTransactions(known
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
//
|
|
909
|
+
return { rows: sortAddressTransactions(known), newRows: [], transactions: new Map() };
|
|
910
|
+
const transactions = stored.unstored.length
|
|
911
|
+
? await this.client.getTransactionsBatch(stored.unstored)
|
|
912
|
+
: new Map();
|
|
913
|
+
// The net amounts need the inputs and outputs of every new transaction.
|
|
914
|
+
// A transaction that is stored already is read again, but not written.
|
|
824
915
|
const allTxData = [];
|
|
825
916
|
const missingFromBatch = [];
|
|
826
917
|
for (const hash of newHashes) {
|
|
827
|
-
const fromBatch =
|
|
918
|
+
const fromBatch = transactions.get(hash);
|
|
828
919
|
if (fromBatch) {
|
|
829
920
|
allTxData.push(fromBatch);
|
|
830
921
|
}
|
|
@@ -840,13 +931,17 @@ class CardanoIndexer {
|
|
|
840
931
|
allTxData.push(providerTx);
|
|
841
932
|
}
|
|
842
933
|
}
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
934
|
+
const newRows = (0, mappers_1.mapAddressTransactions)(addr, allTxData);
|
|
935
|
+
logger.debug({ count: newRows.length }, 'indexAddressTransactions: transaction entities');
|
|
936
|
+
return { rows: sortAddressTransactions([...known, ...newRows]), newRows, transactions };
|
|
937
|
+
}
|
|
938
|
+
// Stores what fetchAddressTransactions read and returns the rows to answer with.
|
|
939
|
+
// No TTL, because a row per address and confirmed tx never changes.
|
|
940
|
+
async storeAddressTransactions(tx, fetched) {
|
|
941
|
+
await this.storeTransactions(tx, fetched.transactions);
|
|
942
|
+
if (fetched.newRows.length)
|
|
943
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(fetched.newRows));
|
|
944
|
+
return fetched.rows;
|
|
850
945
|
}
|
|
851
946
|
/** Link an address to a signing request for address-based queries. */
|
|
852
947
|
async indexAddressSigningRequests(tx, addr, signingRequestId) {
|
|
@@ -864,24 +959,38 @@ class CardanoIndexer {
|
|
|
864
959
|
}
|
|
865
960
|
/** Index the metadata rows of a transaction. */
|
|
866
961
|
async indexTransactionMetadata(tx, tx_hash) {
|
|
962
|
+
return this.storeTransactionMetadata(tx, await this.fetchTransactionMetadata(tx, tx_hash));
|
|
963
|
+
}
|
|
964
|
+
/** Metadata of a transaction from the backend. Null when the transaction is known to have none. */
|
|
965
|
+
async fetchTransactionMetadata(tx, tx_hash) {
|
|
966
|
+
const isStored = (db) => db.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
|
|
867
967
|
// A crawled transaction without metadata rows has no metadata.
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
968
|
+
const crawledWithout = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
969
|
+
if (!(await this.crawlAnswers(db, 'getTransactionMetadata')))
|
|
970
|
+
return false;
|
|
971
|
+
if (await isStored(db))
|
|
972
|
+
return true;
|
|
973
|
+
await this.refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${tx_hash}`);
|
|
974
|
+
return false;
|
|
975
|
+
});
|
|
976
|
+
if (crawledWithout)
|
|
977
|
+
return null;
|
|
875
978
|
try {
|
|
876
|
-
metadata
|
|
979
|
+
return { txHash: tx_hash, metadata: await this.client.getTransactionMetadata(tx_hash) };
|
|
877
980
|
}
|
|
878
981
|
catch (err) {
|
|
879
982
|
// providers answer "not found" for a transaction without metadata; a stored transaction has none
|
|
880
|
-
if ((0, errors_1.isNotFoundOnAllBackends)(err) && await
|
|
881
|
-
return
|
|
983
|
+
if ((0, errors_1.isNotFoundOnAllBackends)(err) && await (0, tx_utils_1.readOutside)(tx, isStored))
|
|
984
|
+
return null;
|
|
882
985
|
throw err;
|
|
883
986
|
}
|
|
884
|
-
|
|
987
|
+
}
|
|
988
|
+
/** Stores the metadata rows of a transaction and returns them. */
|
|
989
|
+
async storeTransactionMetadata(tx, fetched) {
|
|
990
|
+
if (!fetched)
|
|
991
|
+
return [];
|
|
992
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('txSeq').where({ hash: fetched.txHash }));
|
|
993
|
+
const rows = (0, mappers_1.mapTransactionMetadata)(fetched.metadata, stored?.txSeq == null ? null : Number(stored.txSeq));
|
|
885
994
|
if (rows.length) {
|
|
886
995
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(rows));
|
|
887
996
|
}
|
|
@@ -889,7 +998,13 @@ class CardanoIndexer {
|
|
|
889
998
|
}
|
|
890
999
|
/** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
|
|
891
1000
|
async indexNetworkInformation(tx) {
|
|
892
|
-
|
|
1001
|
+
return this.storeNetworkInformation(tx, await this.fetchNetworkInformation(tx));
|
|
1002
|
+
}
|
|
1003
|
+
/** The network information row, read but not stored. */
|
|
1004
|
+
async fetchNetworkInformation(tx) {
|
|
1005
|
+
return (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
|
|
1006
|
+
}
|
|
1007
|
+
async storeNetworkInformation(tx, netEntity) {
|
|
893
1008
|
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
894
1009
|
return netEntity;
|
|
895
1010
|
}
|
|
@@ -903,16 +1018,27 @@ class CardanoIndexer {
|
|
|
903
1018
|
}
|
|
904
1019
|
/** Index a block by hash, with best-effort epoch enrichment. */
|
|
905
1020
|
async indexBlock(tx, blockHash) {
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
1021
|
+
return this.storeBlock(tx, await this.fetchBlock(tx, blockHash));
|
|
1022
|
+
}
|
|
1023
|
+
/** A block and its epoch from the backend. 404 when the crawled chain answers for it alone. */
|
|
1024
|
+
async fetchBlock(tx, blockHash) {
|
|
1025
|
+
await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getBlock', `Block ${blockHash}`));
|
|
1026
|
+
return this.withEpoch(await this.client.getBlock(blockHash));
|
|
1027
|
+
}
|
|
1028
|
+
async withEpoch(block) {
|
|
909
1029
|
try {
|
|
910
|
-
epoch
|
|
1030
|
+
return { block, epoch: (0, mappers_1.mapEpoch)(await this.client.getEpoch(block.epoch)) };
|
|
911
1031
|
}
|
|
912
1032
|
catch {
|
|
913
1033
|
// Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
|
|
1034
|
+
return { block };
|
|
914
1035
|
}
|
|
915
|
-
|
|
1036
|
+
}
|
|
1037
|
+
/** Stores a block and, when it was read, its epoch. */
|
|
1038
|
+
async storeBlock(tx, fetched) {
|
|
1039
|
+
if (fetched.epoch)
|
|
1040
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([fetched.epoch]));
|
|
1041
|
+
const blockEntity = (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
|
|
916
1042
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
|
|
917
1043
|
return blockEntity;
|
|
918
1044
|
}
|
|
@@ -959,17 +1085,22 @@ class CardanoIndexer {
|
|
|
959
1085
|
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
960
1086
|
// corrected fee changes the block's fee total.
|
|
961
1087
|
await this.resolveInputs(tx, txs, ledgerLookup);
|
|
1088
|
+
// an input without a copy reads its assets from its output, so every stored output must be found
|
|
1089
|
+
const byReference = !this.crawlInputAssetCopies;
|
|
1090
|
+
if (byReference)
|
|
1091
|
+
await this.referenceStoredOutputs(tx, txs);
|
|
962
1092
|
this.applyCollateralFees(blockData, txs);
|
|
1093
|
+
this.applyDeposits(txs);
|
|
963
1094
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
964
1095
|
await this.removeStaleTxSeqs(tx, txs);
|
|
965
1096
|
// One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
|
|
966
1097
|
// srv/utils/db-sanitize.ts, not per call site.
|
|
967
1098
|
const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
|
|
968
|
-
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
969
|
-
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
1099
|
+
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
|
|
1100
|
+
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
|
|
970
1101
|
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
971
1102
|
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
972
|
-
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
|
|
1103
|
+
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? [], (0, mappers_1.txSeqOf)(t.slot, t.index)));
|
|
973
1104
|
// Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
|
|
974
1105
|
// re-crawl is idempotent and a reorg removes them with their tx.
|
|
975
1106
|
const certificateRows = this.crawlCertificates
|
|
@@ -991,7 +1122,7 @@ class CardanoIndexer {
|
|
|
991
1122
|
if (inputRows.length)
|
|
992
1123
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
993
1124
|
if (inputAssetRows.length)
|
|
994
|
-
await tx.run(UPSERT.into(
|
|
1125
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
|
|
995
1126
|
if (outputRows.length)
|
|
996
1127
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
997
1128
|
if (outputAssetRows.length)
|
|
@@ -1083,7 +1214,9 @@ class CardanoIndexer {
|
|
|
1083
1214
|
async resolveInputs(tx, txs, ledger) {
|
|
1084
1215
|
// 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
|
|
1085
1216
|
const blockOutputs = new Map();
|
|
1217
|
+
const blockSeqs = new Map();
|
|
1086
1218
|
for (const t of txs) {
|
|
1219
|
+
blockSeqs.set(t.hash, (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
1087
1220
|
for (const o of t.outputs ?? [])
|
|
1088
1221
|
blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
|
|
1089
1222
|
}
|
|
@@ -1091,10 +1224,13 @@ class CardanoIndexer {
|
|
|
1091
1224
|
const unresolved = [];
|
|
1092
1225
|
for (const t of txs) {
|
|
1093
1226
|
for (const input of t.inputs ?? []) {
|
|
1094
|
-
if (input.address)
|
|
1095
|
-
continue; // already resolved by the backend (Blockfrost/Koios)
|
|
1096
1227
|
const key = `${input.txHash}#${input.outputIndex}`;
|
|
1097
1228
|
const local = blockOutputs.get(key);
|
|
1229
|
+
// an output of this block is stored with it
|
|
1230
|
+
if (local)
|
|
1231
|
+
input.spentTxSeq = blockSeqs.get(input.txHash) ?? null;
|
|
1232
|
+
if (input.address)
|
|
1233
|
+
continue; // already resolved by the backend (Blockfrost/Koios)
|
|
1098
1234
|
if (local) {
|
|
1099
1235
|
input.address = local.address;
|
|
1100
1236
|
input.amount = local.amount ?? [];
|
|
@@ -1152,13 +1288,54 @@ class CardanoIndexer {
|
|
|
1152
1288
|
const out = outByKey.get(key);
|
|
1153
1289
|
if (out?.address_address != null)
|
|
1154
1290
|
input.address = out.address_address;
|
|
1155
|
-
if (out)
|
|
1291
|
+
if (out) {
|
|
1156
1292
|
copyUtxoData(input, out);
|
|
1293
|
+
input.spentTxSeq = Number(out.txSeq);
|
|
1294
|
+
}
|
|
1157
1295
|
const amt = amtByKey.get(key);
|
|
1158
1296
|
if (amt)
|
|
1159
1297
|
input.amount = amt;
|
|
1160
1298
|
}
|
|
1161
1299
|
}
|
|
1300
|
+
// Marks the inputs whose spent output is stored from an earlier block, so they can point at it.
|
|
1301
|
+
async referenceStoredOutputs(tx, txs) {
|
|
1302
|
+
const open = txs.flatMap(t => t.inputs ?? []).filter(i => i.spentTxSeq == null && i.txHash);
|
|
1303
|
+
if (!open.length)
|
|
1304
|
+
return;
|
|
1305
|
+
const seqByHash = new Map();
|
|
1306
|
+
for (const k of await (0, transaction_rows_1.readTxKeys)(tx, [...new Set(open.map(i => i.txHash))])) {
|
|
1307
|
+
if (k.txSeq != null)
|
|
1308
|
+
seqByHash.set(k.hash, Number(k.txSeq));
|
|
1309
|
+
}
|
|
1310
|
+
const stored = new Set();
|
|
1311
|
+
for (const seqChunk of (0, collections_1.chunk)([...new Set(seqByHash.values())], collections_1.IN_CHUNK)) {
|
|
1312
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } }));
|
|
1313
|
+
for (const r of rows ?? [])
|
|
1314
|
+
stored.add(`${(0, transaction_rows_1.seqKey)(r.txSeq)}#${Number(r.outputIndex)}`);
|
|
1315
|
+
}
|
|
1316
|
+
for (const input of open) {
|
|
1317
|
+
const seq = seqByHash.get(input.txHash);
|
|
1318
|
+
if (seq != null && stored.has(`${(0, transaction_rows_1.seqKey)(seq)}#${input.outputIndex}`))
|
|
1319
|
+
input.spentTxSeq = seq;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
// Deposit of a transaction whose source left it open, from the ledger's balance: spent inputs
|
|
1323
|
+
// plus withdrawals, minus outputs, fee and treasury donation. Stays null while an input is not indexed.
|
|
1324
|
+
applyDeposits(txs) {
|
|
1325
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
1326
|
+
for (const t of txs) {
|
|
1327
|
+
if (t.deposit != null)
|
|
1328
|
+
continue;
|
|
1329
|
+
const spent = (t.inputs ?? []).filter(i => !i.isCollateral && !i.isReference);
|
|
1330
|
+
if (spent.some(i => !i.address))
|
|
1331
|
+
continue;
|
|
1332
|
+
const consumed = spent.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n)
|
|
1333
|
+
+ (t.withdrawals ?? []).reduce((sum, w) => sum + BigInt(w.amount), 0n);
|
|
1334
|
+
const produced = (t.outputs ?? []).filter(o => !o.isCollateral).reduce((sum, o) => sum + lovelaceOf(o.amount), 0n)
|
|
1335
|
+
+ BigInt(t.fee) + BigInt(t.treasuryDonation ?? '0');
|
|
1336
|
+
t.deposit = (consumed - produced).toString();
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1162
1339
|
// Fee of a phase-2 failure is collateral inputs minus collateral return. The declared fee
|
|
1163
1340
|
// stays when total_collateral set it or a collateral input is not indexed.
|
|
1164
1341
|
applyCollateralFees(blockData, txs) {
|
|
@@ -1433,63 +1610,125 @@ class CardanoIndexer {
|
|
|
1433
1610
|
}
|
|
1434
1611
|
/** Index an epoch by number. */
|
|
1435
1612
|
async indexEpoch(tx, epochNumber) {
|
|
1436
|
-
|
|
1437
|
-
|
|
1613
|
+
return this.storeEpoch(tx, await this.fetchEpoch(epochNumber));
|
|
1614
|
+
}
|
|
1615
|
+
/** An epoch row from the backend. */
|
|
1616
|
+
async fetchEpoch(epochNumber) {
|
|
1617
|
+
return (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
|
|
1618
|
+
}
|
|
1619
|
+
async storeEpoch(tx, epochEntity) {
|
|
1438
1620
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
1439
1621
|
return epochEntity;
|
|
1440
1622
|
}
|
|
1441
1623
|
/** Index an account by stake address, plus its addresses when it has any. */
|
|
1442
1624
|
async indexAccount(tx, stakeAddress) {
|
|
1443
|
-
|
|
1444
|
-
|
|
1625
|
+
return this.storeAccount(tx, await this.fetchAccount(tx, stakeAddress));
|
|
1626
|
+
}
|
|
1627
|
+
/** An account and the addresses it controls, read but not stored. */
|
|
1628
|
+
async fetchAccount(tx, stakeAddress) {
|
|
1629
|
+
const account = await this.resolveAccount(tx, stakeAddress);
|
|
1630
|
+
return { account, addresses: await this.fetchAddresses(tx, account.addresses) };
|
|
1631
|
+
}
|
|
1632
|
+
/** Stores what fetchAccount read. */
|
|
1633
|
+
async storeAccount(tx, fetched) {
|
|
1634
|
+
const accountEntity = (0, mappers_1.mapAccount)(fetched.account, this.client.max_age_ms);
|
|
1445
1635
|
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
1446
|
-
|
|
1447
|
-
await this.
|
|
1448
|
-
}
|
|
1636
|
+
for (const address of fetched.addresses)
|
|
1637
|
+
await this.storeAddress(tx, address);
|
|
1449
1638
|
return accountEntity;
|
|
1450
1639
|
}
|
|
1451
1640
|
/** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
|
|
1452
1641
|
async resolveAccount(tx, stakeAddress) {
|
|
1453
1642
|
const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
|
|
1643
|
+
const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
1644
|
+
const ledger = Boolean((await this.localCoverage(db))?.ledger);
|
|
1645
|
+
const row = ledger
|
|
1646
|
+
? await db.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }))
|
|
1647
|
+
: undefined;
|
|
1648
|
+
return {
|
|
1649
|
+
ledger,
|
|
1650
|
+
controlledAmount: row?.controlledAmount,
|
|
1651
|
+
held: ledger ? await this.ledgerAccountUtxos(db, stakeAddress) : { addresses: [], utxos: [] },
|
|
1652
|
+
withdrawalsSum: accountInfo.withdrawalsSum === '0' ? await this.localWithdrawalsSum(db, stakeAddress) : null,
|
|
1653
|
+
};
|
|
1654
|
+
});
|
|
1454
1655
|
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
|
|
1455
1656
|
// the addresses come from the set too (the node has no stake-key -> address index)
|
|
1456
|
-
if (
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
}
|
|
1657
|
+
if (local.ledger) {
|
|
1658
|
+
accountInfo.controlledAmount = (BigInt(lovelaceSum(local.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
|
|
1659
|
+
const byAddress = new Map(local.held.addresses.map(a => [a, []]));
|
|
1660
|
+
for (const u of await this.unspentAtNode(local.held.utxos))
|
|
1661
|
+
byAddress.get(u.address)?.push(u);
|
|
1662
|
+
accountInfo.addresses = local.held.addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
|
|
1663
|
+
}
|
|
1664
|
+
if (local.withdrawalsSum != null)
|
|
1665
|
+
accountInfo.withdrawalsSum = local.withdrawalsSum;
|
|
1466
1666
|
return accountInfo;
|
|
1467
1667
|
}
|
|
1468
1668
|
/** Index a DRep by bech32 id. */
|
|
1469
1669
|
async indexDrep(tx, drepId) {
|
|
1470
|
-
|
|
1471
|
-
|
|
1670
|
+
return this.storeDrep(tx, await this.fetchDrep(drepId));
|
|
1671
|
+
}
|
|
1672
|
+
/** A DRep row from the backend. */
|
|
1673
|
+
async fetchDrep(drepId) {
|
|
1674
|
+
return (0, mappers_1.mapDrep)(await this.client.getDrep(drepId), this.client.max_age_ms);
|
|
1675
|
+
}
|
|
1676
|
+
async storeDrep(tx, drepEntity) {
|
|
1472
1677
|
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
|
|
1473
1678
|
return drepEntity;
|
|
1474
1679
|
}
|
|
1475
1680
|
/** Index a pool by id. */
|
|
1476
1681
|
async indexPool(tx, poolId) {
|
|
1477
|
-
|
|
1682
|
+
return this.storePool(tx, await this.fetchPool(tx, poolId));
|
|
1683
|
+
}
|
|
1684
|
+
/** A pool row, read but not stored. */
|
|
1685
|
+
async fetchPool(tx, poolId) {
|
|
1686
|
+
return (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
|
|
1687
|
+
}
|
|
1688
|
+
async storePool(tx, poolEntity) {
|
|
1478
1689
|
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
1479
1690
|
return poolEntity;
|
|
1480
1691
|
}
|
|
1481
|
-
/** Pool from the backend with crawled block counts
|
|
1692
|
+
/** Pool from the backend with crawled block counts, the snapshot's active stake and its metadata file. */
|
|
1482
1693
|
async resolvePool(tx, poolId) {
|
|
1483
|
-
const
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1694
|
+
const backend = await this.client.getPool(poolId);
|
|
1695
|
+
const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
1696
|
+
const blocks = await this.localPoolBlocks(db, poolId);
|
|
1697
|
+
// The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
|
|
1698
|
+
return backend.activeStake === '0' ? { ...blocks, ...(await this.snapshotActiveStake(db, poolId)) } : blocks;
|
|
1699
|
+
});
|
|
1700
|
+
const poolInfo = { ...backend, ...local };
|
|
1701
|
+
Object.assign(poolInfo, await this.poolMetadataOf(poolInfo));
|
|
1487
1702
|
return poolInfo;
|
|
1488
1703
|
}
|
|
1704
|
+
// Name, ticker, homepage and description of a pool whose backend gave only the file's URL and hash.
|
|
1705
|
+
// Loads the file when `poolMetadataFetch` is on. A file is memoized by its hash.
|
|
1706
|
+
async poolMetadataOf(pool) {
|
|
1707
|
+
if (!this.poolMetadataFetch || pool.name != null || !pool.metadataUrl || !pool.metadataHash)
|
|
1708
|
+
return undefined;
|
|
1709
|
+
const known = this.poolMetadataByHash.get(pool.metadataHash);
|
|
1710
|
+
if (known)
|
|
1711
|
+
return known;
|
|
1712
|
+
const metadata = await (0, pool_metadata_1.fetchPoolMetadata)(pool.metadataUrl, pool.metadataHash);
|
|
1713
|
+
if (!metadata)
|
|
1714
|
+
return undefined;
|
|
1715
|
+
if (this.poolMetadataByHash.size >= CardanoIndexer.POOL_METADATA_MEMO_CAP)
|
|
1716
|
+
this.poolMetadataByHash.clear();
|
|
1717
|
+
this.poolMetadataByHash.set(pool.metadataHash, metadata);
|
|
1718
|
+
return metadata;
|
|
1719
|
+
}
|
|
1720
|
+
/** Turns the loading of pool metadata files on or off (`poolMetadataFetch`). */
|
|
1721
|
+
setPoolMetadataFetch(enabled) {
|
|
1722
|
+
this.poolMetadataFetch = enabled;
|
|
1723
|
+
}
|
|
1489
1724
|
/** Index an asset by unit (policyId + assetNameHex). */
|
|
1490
1725
|
async indexAsset(tx, unit) {
|
|
1491
1726
|
return this.writeAsset(tx, unit, await this.resolveAssetInfo(tx, unit));
|
|
1492
1727
|
}
|
|
1728
|
+
/** Stores an asset read with resolveAssetInfo. */
|
|
1729
|
+
async storeAsset(tx, assetInfo) {
|
|
1730
|
+
return this.writeAsset(tx, assetInfo.unit, assetInfo);
|
|
1731
|
+
}
|
|
1493
1732
|
/** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
|
|
1494
1733
|
async indexAssetFromBackend(tx, unit) {
|
|
1495
1734
|
return this.writeAsset(tx, unit, await this.client.getAssetInfo(unit));
|
|
@@ -1502,9 +1741,9 @@ class CardanoIndexer {
|
|
|
1502
1741
|
}
|
|
1503
1742
|
/** Always fresh. Rows are keyed by unit and tx, so older cached entries persist. */
|
|
1504
1743
|
async indexAssetHistory(tx, unit, limit = 100) {
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1744
|
+
const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
|
|
1745
|
+
if (crawled)
|
|
1746
|
+
return crawled;
|
|
1508
1747
|
const events = await this.client.getAssetHistory(unit, limit);
|
|
1509
1748
|
if (events.length === 0)
|
|
1510
1749
|
return [];
|
|
@@ -1515,9 +1754,11 @@ class CardanoIndexer {
|
|
|
1515
1754
|
}
|
|
1516
1755
|
/** Build a transaction and persist the build result with inputs/outputs/address association. */
|
|
1517
1756
|
async _indexBuildResult(tx, buildreq, buildFn) {
|
|
1518
|
-
|
|
1519
|
-
const
|
|
1757
|
+
// The build talks to the backend: nothing is written before it returns.
|
|
1758
|
+
const protocolParams = await this.fetchProtocolParameters(tx);
|
|
1759
|
+
const txbuildResult = await buildFn(buildreq, protocolParams.row);
|
|
1520
1760
|
const buildResult = (0, mappers_1.mapBuildResult)(txbuildResult, this.client.max_age_ms);
|
|
1761
|
+
await this.storeProtocolParameters(tx, protocolParams);
|
|
1521
1762
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuild).entries(buildResult));
|
|
1522
1763
|
if (buildResult.id && txbuildResult.inputs && txbuildResult.inputs.length > 0) {
|
|
1523
1764
|
const inputRows = (0, mappers_1.mapBuildInputs)(buildResult.id, txbuildResult.inputs);
|
|
@@ -1557,20 +1798,26 @@ class CardanoIndexer {
|
|
|
1557
1798
|
}
|
|
1558
1799
|
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
1559
1800
|
async indexProtocolParameters(tx) {
|
|
1801
|
+
return this.storeProtocolParameters(tx, await this.fetchProtocolParameters(tx));
|
|
1802
|
+
}
|
|
1803
|
+
/** The stored row within its TTL, else the parameters from the backend. Nothing is written. */
|
|
1804
|
+
async fetchProtocolParameters(tx) {
|
|
1560
1805
|
const network = this.client.network;
|
|
1561
|
-
|
|
1562
|
-
const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // matches the client cache TTL
|
|
1563
|
-
if (now - this.lastParamsFetchTime < PROTOCOL_PARAMS_TTL_MS) {
|
|
1806
|
+
if (Date.now() - this.lastParamsFetchTime < const_1.PROTOCOL_PARAMS_TTL_MS) {
|
|
1564
1807
|
// (network, epoch) is the key; order by epoch desc to get the latest row
|
|
1565
|
-
const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
|
|
1808
|
+
const existing = await (0, tx_utils_1.readOutside)(tx, (db) => db.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc')));
|
|
1566
1809
|
if (existing)
|
|
1567
|
-
return existing;
|
|
1810
|
+
return { row: existing, fresh: false };
|
|
1811
|
+
}
|
|
1812
|
+
return { row: (0, mappers_1.mapProtocolParameters)(await this.client.getProtocolParameters()), fresh: true };
|
|
1813
|
+
}
|
|
1814
|
+
/** Stores parameters that came from the backend and restarts their TTL. */
|
|
1815
|
+
async storeProtocolParameters(tx, fetched) {
|
|
1816
|
+
if (fetched.fresh) {
|
|
1817
|
+
await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(fetched.row));
|
|
1818
|
+
this.lastParamsFetchTime = Date.now();
|
|
1568
1819
|
}
|
|
1569
|
-
|
|
1570
|
-
const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
|
|
1571
|
-
await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
|
|
1572
|
-
this.lastParamsFetchTime = now;
|
|
1573
|
-
return protocolParams;
|
|
1820
|
+
return fetched.row;
|
|
1574
1821
|
}
|
|
1575
1822
|
/** Persist a transaction submission and flag the build as submitted when linked. */
|
|
1576
1823
|
async persistTransactionSubmission(tx, params) {
|
|
@@ -1592,15 +1839,15 @@ class CardanoIndexer {
|
|
|
1592
1839
|
}
|
|
1593
1840
|
return submissionRecord;
|
|
1594
1841
|
}
|
|
1595
|
-
/** Update a submission's status
|
|
1596
|
-
async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
|
|
1842
|
+
/** Update a submission's status. With onlyFrom the row changes only while it has that status. */
|
|
1843
|
+
async updateSubmissionStatus(tx, submissionId, status, errorMessage, onlyFrom) {
|
|
1597
1844
|
const updateData = { status };
|
|
1598
1845
|
if (errorMessage) {
|
|
1599
1846
|
updateData.errorMessage = errorMessage;
|
|
1600
1847
|
}
|
|
1601
1848
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionSubmissions)
|
|
1602
1849
|
.set(updateData)
|
|
1603
|
-
.where({ id: submissionId }));
|
|
1850
|
+
.where(onlyFrom ? { id: submissionId, status: onlyFrom } : { id: submissionId }));
|
|
1604
1851
|
logger.debug({ submissionId, status }, 'Updated submission status');
|
|
1605
1852
|
}
|
|
1606
1853
|
/** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
|
|
@@ -1712,30 +1959,20 @@ class CardanoIndexer {
|
|
|
1712
1959
|
}
|
|
1713
1960
|
/** Index the latest epoch. */
|
|
1714
1961
|
async indexLatestEpoch(tx) {
|
|
1715
|
-
|
|
1716
|
-
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
1717
|
-
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
1718
|
-
return epochEntity;
|
|
1962
|
+
return this.storeEpoch(tx, (0, mappers_1.mapEpoch)(await this.client.getLatestEpoch()));
|
|
1719
1963
|
}
|
|
1720
1964
|
/** Index the latest block, with best-effort epoch enrichment. */
|
|
1721
1965
|
async indexLatestBlock(tx) {
|
|
1722
|
-
const
|
|
1723
|
-
let epoch;
|
|
1724
|
-
try {
|
|
1725
|
-
epoch = await this.indexEpoch(tx, blockInfo.epoch);
|
|
1726
|
-
}
|
|
1727
|
-
catch {
|
|
1728
|
-
// Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
|
|
1729
|
-
}
|
|
1730
|
-
const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
|
|
1966
|
+
const fetched = await this.withEpoch(await this.client.getLatestBlock());
|
|
1731
1967
|
// A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
|
|
1732
1968
|
// crawled row of the same hash, or outlive the block when the tip is rolled back.
|
|
1733
|
-
if (
|
|
1734
|
-
|
|
1735
|
-
|
|
1969
|
+
if (fetched.block.headerOnly) {
|
|
1970
|
+
if (fetched.epoch)
|
|
1971
|
+
await this.storeEpoch(tx, fetched.epoch);
|
|
1972
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: fetched.block.hash }));
|
|
1973
|
+
return stored ?? (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
|
|
1736
1974
|
}
|
|
1737
|
-
|
|
1738
|
-
return blockEntity;
|
|
1975
|
+
return this.storeBlock(tx, fetched);
|
|
1739
1976
|
}
|
|
1740
1977
|
//-----------------------------------------------------------------------------
|
|
1741
1978
|
// Batch Methods (N+1 Optimization)
|
|
@@ -1750,22 +1987,24 @@ class CardanoIndexer {
|
|
|
1750
1987
|
// Confirmations including the tx's own block, 0 while not on chain. A stored row counts only inside
|
|
1751
1988
|
// the crawled chain, because the crawler removes those rows on a rollback.
|
|
1752
1989
|
async resolveTransactionConfirmations(tx, txHash) {
|
|
1753
|
-
const crawled = await this.crawledTransactionDepth(
|
|
1990
|
+
const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledTransactionDepth(db, txHash));
|
|
1754
1991
|
if (crawled)
|
|
1755
1992
|
return { txHash, ...crawled, confirmations: crawled.tipHeight - crawled.blockHeight + 1 };
|
|
1756
|
-
let
|
|
1993
|
+
let providerTx = null;
|
|
1757
1994
|
try {
|
|
1758
|
-
|
|
1759
|
-
blockHeight = indexed.blockHeight == null ? null : Number(indexed.blockHeight);
|
|
1995
|
+
providerTx = await this.fetchTransaction(tx, txHash);
|
|
1760
1996
|
}
|
|
1761
1997
|
catch (err) {
|
|
1762
1998
|
if (!(0, errors_1.isNotFoundOnAllBackends)(err))
|
|
1763
1999
|
throw err;
|
|
1764
|
-
blockHeight = null;
|
|
1765
2000
|
}
|
|
1766
|
-
|
|
2001
|
+
const blockHeight = providerTx?.blockHeight == null ? null : Number(providerTx.blockHeight);
|
|
2002
|
+
// The tip is read before the transaction is stored, so no write is open during that call.
|
|
2003
|
+
const tip = blockHeight == null ? null : await this.client.getLatestBlock();
|
|
2004
|
+
if (providerTx)
|
|
2005
|
+
await this.storeTransaction(tx, providerTx);
|
|
2006
|
+
if (blockHeight == null || !tip)
|
|
1767
2007
|
return { txHash, blockHeight: null, tipHeight: null, confirmations: 0 };
|
|
1768
|
-
const tip = await this.client.getLatestBlock();
|
|
1769
2008
|
if (tip.height == null)
|
|
1770
2009
|
throw new errors_1.ProviderUnavailableError('Chain tip height unknown');
|
|
1771
2010
|
// a tip from a backend that lags the one that found the tx counts the tx block only
|
|
@@ -1789,37 +2028,45 @@ class CardanoIndexer {
|
|
|
1789
2028
|
const blockHeight = Number(stored.blockHeight);
|
|
1790
2029
|
return { blockHeight, tipHeight: Math.max(coverage.tipHeight, blockHeight) };
|
|
1791
2030
|
}
|
|
1792
|
-
/** Batch-fetches the missing ones and returns only those. */
|
|
2031
|
+
/** Batch-fetches the missing ones, stores them and returns only those. */
|
|
1793
2032
|
async ensureTransactionsIndexed(tx, txHashes) {
|
|
2033
|
+
const missing = await (0, tx_utils_1.readOutside)(tx, (db) => this.unstoredTransactionHashes(db, txHashes));
|
|
2034
|
+
const fetched = missing.length ? await this.client.getTransactionsBatch(missing) : new Map();
|
|
2035
|
+
await this.storeTransactions(tx, fetched);
|
|
2036
|
+
return fetched;
|
|
2037
|
+
}
|
|
2038
|
+
/** The hashes among the given ones that have no stored transaction. */
|
|
2039
|
+
async unstoredTransactionHashes(tx, txHashes) {
|
|
1794
2040
|
const unique = [...new Set(txHashes)];
|
|
1795
2041
|
if (unique.length === 0)
|
|
1796
|
-
return
|
|
2042
|
+
return [];
|
|
1797
2043
|
const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
|
|
1798
2044
|
const existingSet = new Set(existingRows.map((r) => r.hash));
|
|
1799
2045
|
const missing = unique.filter(h => !existingSet.has(h));
|
|
1800
2046
|
logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
2047
|
+
return missing;
|
|
2048
|
+
}
|
|
2049
|
+
/** Stores transactions read from a backend, each with its inputs, outputs and metadata. */
|
|
2050
|
+
async storeTransactions(tx, fetched) {
|
|
2051
|
+
for (const [, providerTx] of fetched) {
|
|
2052
|
+
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
2053
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
2054
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
1809
2055
|
}
|
|
1810
|
-
return fetched;
|
|
1811
2056
|
}
|
|
1812
2057
|
//-----------------------------------------------------------------------------
|
|
1813
2058
|
// Private Helpers
|
|
1814
2059
|
//-----------------------------------------------------------------------------
|
|
1815
2060
|
// Uses the address data the account carries, so no request per address.
|
|
1816
2061
|
// Only an entry without UTxOs is fetched.
|
|
1817
|
-
async
|
|
2062
|
+
async fetchAddresses(tx, accountAddresses) {
|
|
2063
|
+
const fetched = [];
|
|
1818
2064
|
const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
|
|
1819
2065
|
for (let i = 0; i < accountAddresses.length; i += concurrency) {
|
|
1820
2066
|
const chunk = accountAddresses.slice(i, i + concurrency);
|
|
1821
|
-
await Promise.all(chunk.map(a => this.
|
|
2067
|
+
fetched.push(...await Promise.all(chunk.map(a => this.fetchAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined))));
|
|
1822
2068
|
}
|
|
2069
|
+
return fetched;
|
|
1823
2070
|
}
|
|
1824
2071
|
}
|
|
1825
2072
|
exports.CardanoIndexer = CardanoIndexer;
|