@odatano/core 2.0.0-rc.4 → 2.0.0-rc.41
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 +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
- package/@cds-models/CardanoIndexerService/index.js +25 -0
- package/@cds-models/CardanoODataService/index.d.ts +305 -7
- package/@cds-models/CardanoODataService/index.js +34 -0
- package/@cds-models/CardanoSignService/index.d.ts +28 -3
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +72 -0
- package/@cds-models/index.js +12 -0
- package/@cds-models/odatano/cardano/index.d.ts +408 -7
- package/@cds-models/odatano/cardano/index.js +42 -0
- package/README.md +64 -5
- package/db/schema.cds +2297 -1633
- package/db/types.cds +114 -0
- package/package.json +27 -6
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +18 -11
- package/src/index.js +44 -14
- package/src/plugin.js +42 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +53 -162
- package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
- package/srv/blockchain/backends/cardano-backend.js +19 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +376 -235
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +170 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
- package/srv/blockchain/backends/ogmios-backend.js +556 -201
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +87 -202
- package/srv/blockchain/cardano-client.js +210 -240
- package/srv/blockchain/cardano-indexer.d.ts +311 -242
- package/srv/blockchain/cardano-indexer.js +1238 -362
- package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
- package/srv/blockchain/cardano-tx-builder.js +173 -132
- package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
- package/srv/blockchain/crawler/certificate-backfill.js +169 -0
- package/srv/blockchain/crawler/crawler.d.ts +139 -54
- package/srv/blockchain/crawler/crawler.js +478 -96
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +46 -28
- package/srv/blockchain/crawler/sync-state.js +128 -43
- package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/transaction-backfill.js +283 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
- package/srv/blockchain/crawler/utxo-set-import.js +363 -0
- package/srv/blockchain/ledger-state.d.ts +101 -0
- package/srv/blockchain/ledger-state.js +432 -0
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
- package/srv/blockchain/signing/signature-verifier.js +73 -76
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -49
- package/srv/blockchain/stored-chain.d.ts +33 -0
- package/srv/blockchain/stored-chain.js +234 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
- package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
- package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
- package/srv/blockchain/transaction-building/caller-datums.js +139 -0
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +43 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +18 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- package/srv/cardano-backend-service.cds +52 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +244 -0
- package/srv/cardano-indexer-service.cds +201 -73
- package/srv/cardano-indexer-service.js +280 -11
- package/srv/cardano-service.cds +65 -2
- package/srv/cardano-service.js +170 -129
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +57 -184
- package/srv/cardano-tx-service.cds +439 -370
- package/srv/cardano-tx-service.js +231 -190
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.js +7 -15
- package/srv/cbor/index.d.ts +1 -1
- package/srv/cbor/parse.d.ts +27 -0
- package/srv/cbor/parse.js +63 -2
- package/srv/server.d.ts +28 -86
- package/srv/server.js +132 -135
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +922 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +30 -67
- package/srv/utils/const.js +32 -72
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +94 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/epoch-slots.d.ts +20 -0
- package/srv/utils/epoch-slots.js +43 -0
- package/srv/utils/error-codes.d.ts +20 -73
- package/srv/utils/error-codes.js +19 -70
- package/srv/utils/errors.d.ts +50 -177
- package/srv/utils/errors.js +94 -218
- package/srv/utils/legacy-service-paths.d.ts +11 -0
- package/srv/utils/legacy-service-paths.js +58 -0
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +40 -0
- package/srv/utils/mappers.d.ts +128 -214
- package/srv/utils/mappers.js +354 -299
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +62 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +56 -0
- package/srv/utils/plutus-placeholders.d.ts +23 -16
- package/srv/utils/plutus-placeholders.js +63 -27
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +6 -16
- package/srv/utils/signing-helper.js +36 -60
- package/srv/utils/tx-build-helper.d.ts +28 -93
- package/srv/utils/tx-build-helper.js +75 -124
- package/srv/utils/tx-request-parsers.d.ts +101 -28
- package/srv/utils/tx-request-parsers.js +410 -43
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +252 -179
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +24 -90
- package/srv/utils/validators.js +50 -147
|
@@ -8,22 +8,38 @@ const cds_1 = __importDefault(require("@sap/cds"));
|
|
|
8
8
|
const CardanoODataService_1 = require("#cds-models/CardanoODataService");
|
|
9
9
|
const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
|
|
10
10
|
const CardanoSignService_1 = require("#cds-models/CardanoSignService");
|
|
11
|
+
// DB-level entity: the catalogue's existence check must bypass the temporal filter that the
|
|
12
|
+
// service projection carries (see ensureAssetRows).
|
|
13
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
11
14
|
const mappers_1 = require("../utils/mappers");
|
|
15
|
+
const errors_1 = require("../utils/errors");
|
|
12
16
|
const collections_1 = require("../utils/collections");
|
|
17
|
+
const transaction_rows_1 = require("./transaction-rows");
|
|
18
|
+
const ledger_state_1 = require("./ledger-state");
|
|
19
|
+
const sync_state_1 = require("./crawler/sync-state");
|
|
20
|
+
const epoch_slots_1 = require("../utils/epoch-slots");
|
|
21
|
+
const const_1 = require("../utils/const");
|
|
13
22
|
const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
|
|
14
23
|
const logger = cds_1.default.log('CardanoIndexer');
|
|
24
|
+
/** Datum hash, inline datum and reference-script hash of the spent output onto its input. */
|
|
25
|
+
function copyUtxoData(input, dataHash, inlineDatum, referenceScriptHash) {
|
|
26
|
+
input.dataHash = input.dataHash ?? dataHash ?? null;
|
|
27
|
+
input.inlineDatum = input.inlineDatum ?? inlineDatum ?? null;
|
|
28
|
+
input.referenceScriptHash = input.referenceScriptHash ?? referenceScriptHash ?? null;
|
|
29
|
+
}
|
|
30
|
+
function lovelaceSum(value) {
|
|
31
|
+
if (value === null || value === undefined || value === '')
|
|
32
|
+
return '0';
|
|
33
|
+
return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
|
|
34
|
+
}
|
|
35
|
+
/** Provider-shaped address from its unspent outputs: type and stake address decoded from the address. */
|
|
36
|
+
function addressFromUtxos(address, utxos) {
|
|
37
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
38
|
+
return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
|
|
39
|
+
}
|
|
15
40
|
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* Provides methods to index & manage db consistency for various Cardano blockchain data (transactions, addresses, blocks, epochs, accounts, pools, dreps)
|
|
19
|
-
* 1. Fetches data from the configured Cardano data provider via the CardanoClient
|
|
20
|
-
* 2. Maps the provider data into corresponding OData entity rows
|
|
21
|
-
* 3. Upserts the data rows into the database via CAP transactions
|
|
22
|
-
* 4. Ensures referential integrity and consistency across related entities (e.g., addresses in transactions, UTxOs in addresses)
|
|
23
|
-
* 5. Returns the indexed entity data for further processing
|
|
24
|
-
*
|
|
25
|
-
* Each method corresponds to a specific Cardano Entity type and handles the necessary mapping and persistence
|
|
26
|
-
* into the corresponding OData entities defined in the CardanoODataService(M1) and CardanoTransactionService(M2) models.
|
|
41
|
+
* Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
|
|
42
|
+
* to entity rows and UPSERTs them inside the caller's CAP transaction.
|
|
27
43
|
*/
|
|
28
44
|
class CardanoIndexer {
|
|
29
45
|
client;
|
|
@@ -32,22 +48,399 @@ class CardanoIndexer {
|
|
|
32
48
|
static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
|
|
33
49
|
static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
|
|
34
50
|
/**
|
|
35
|
-
* Crawler epoch memo
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* At most the current and immediately previous epoch are retained. The rows are
|
|
40
|
-
* intentionally UPSERTed in every block transaction: the caller owns that
|
|
41
|
-
* transaction, so an in-memory "persisted" bit cannot know whether its commit later
|
|
42
|
-
* succeeded. Repeating one local UPSERT is cheap and remains correct after rollback.
|
|
51
|
+
* Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
|
|
52
|
+
* next one starts; holds at most the current and previous epoch. A row is UPSERTed until a
|
|
53
|
+
* block transaction that wrote it has committed (`confirmBlockCommit`).
|
|
43
54
|
*/
|
|
44
55
|
crawlEpochCache = new Map();
|
|
45
56
|
crawlEpochCurrent = null;
|
|
57
|
+
/** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
|
|
58
|
+
crawlEpochWritten = new WeakSet();
|
|
59
|
+
/** Memo updates of the running block transaction, applied only after its commit. */
|
|
60
|
+
pendingCommit = [];
|
|
46
61
|
crawlEpochPrevious = null;
|
|
62
|
+
/** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
|
|
63
|
+
crawlAssetHistory = true;
|
|
64
|
+
crawlAssetCatalogue = 'bare';
|
|
65
|
+
/** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
|
|
66
|
+
crawlCertificates = false;
|
|
67
|
+
/** Logged once per process: the active source reports no certificates (Blockfrost). */
|
|
68
|
+
certificatesUnreportedWarned = false;
|
|
69
|
+
/**
|
|
70
|
+
* Crawler-fed ledger state (`crawler.utxoSet`): blocks after `utxoAnchor` are applied to the
|
|
71
|
+
* Ledger* tables; no anchor means configured but inactive.
|
|
72
|
+
*/
|
|
73
|
+
crawlUtxoSet = false;
|
|
74
|
+
/** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
|
|
75
|
+
crawlAuthoritative = false;
|
|
76
|
+
utxoAnchor = null;
|
|
77
|
+
/** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
|
|
78
|
+
credentialsReady = false;
|
|
79
|
+
credentialFill = null;
|
|
80
|
+
credentialGeneration = 0;
|
|
81
|
+
/** The anchor block was found in the crawled chain (checked once, before the first apply). */
|
|
82
|
+
utxoAnchorVerified = false;
|
|
83
|
+
/**
|
|
84
|
+
* Invalidation decided inside a block transaction; the anchor stays until the crawler confirms
|
|
85
|
+
* the commit (`takeLedgerInvalidation`), so a rolled-back attempt changes nothing.
|
|
86
|
+
*/
|
|
87
|
+
ledgerInvalidation = null;
|
|
88
|
+
/** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
|
|
89
|
+
static ASSET_MEMO_CAP = 200_000;
|
|
90
|
+
/** Output references per node lookup when checking crawled UTxOs. */
|
|
91
|
+
static OUTREF_CHUNK = 500;
|
|
92
|
+
assetMemo = new Set();
|
|
93
|
+
/**
|
|
94
|
+
* Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
|
|
95
|
+
* outside the block transaction. Above the cap the oldest units are dropped (bare row stays).
|
|
96
|
+
*/
|
|
97
|
+
static ENRICH_QUEUE_CAP = 50_000;
|
|
98
|
+
enrichQueue = [];
|
|
99
|
+
enrichTimer = null;
|
|
100
|
+
enrichRate = 2;
|
|
101
|
+
/** Adopt the crawler's coverage settings; the lazy request path never touches these. */
|
|
102
|
+
configureCrawlCoverage(coverage) {
|
|
103
|
+
this.crawlAuthoritative = coverage.authoritative ?? false;
|
|
104
|
+
this.crawlAssetHistory = coverage.assetHistory;
|
|
105
|
+
this.crawlAssetCatalogue = coverage.assetCatalogue;
|
|
106
|
+
this.crawlCertificates = coverage.certificates ?? false;
|
|
107
|
+
this.crawlUtxoSet = coverage.utxoSet ?? false;
|
|
108
|
+
this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
|
|
109
|
+
if (coverage.assetCatalogue !== 'enrich')
|
|
110
|
+
this.stopAssetEnrichment();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* What the crawled data answers authoritatively: only while a live crawler is at the tip.
|
|
114
|
+
* Every block after `fromSlot` is held; `ledger` = the crawled UTxO set is active.
|
|
115
|
+
*/
|
|
116
|
+
async localCoverage(tx) {
|
|
117
|
+
const cursor = await (0, sync_state_1.readCursor)(tx);
|
|
118
|
+
if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
|
|
119
|
+
return null;
|
|
120
|
+
return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Block counts of a pool from crawled blocks (`slotLeader` = pool id): the current epoch when the
|
|
124
|
+
* crawl covers it from its first slot, the lifetime total when it covers the chain since Shelley.
|
|
125
|
+
*/
|
|
126
|
+
async localPoolBlocks(tx, poolId) {
|
|
127
|
+
const coverage = await this.localCoverage(tx);
|
|
128
|
+
if (!coverage)
|
|
129
|
+
return {};
|
|
130
|
+
const network = this.client.network;
|
|
131
|
+
const countSince = async (fromSlot) => {
|
|
132
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('count(*) as n').where({ slotLeader: poolId, slot: { '>=': fromSlot } }));
|
|
133
|
+
return Number(row?.n ?? 0);
|
|
134
|
+
};
|
|
135
|
+
const counts = {};
|
|
136
|
+
const epochStart = (0, epoch_slots_1.epochStartSlot)(network, (0, epoch_slots_1.epochOfSlot)(network, coverage.lastSlot));
|
|
137
|
+
if (coverage.fromSlot < epochStart)
|
|
138
|
+
counts.blocksEpoch = await countSince(epochStart);
|
|
139
|
+
if (coverage.fromSlot <= const_1.EPOCH_CONFIG_BY_NETWORK[network].shelleyStartSlot)
|
|
140
|
+
counts.blocksMinted = await countSince(0);
|
|
141
|
+
return counts;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The crawled chain answers `method` on its own: live crawler at the tip, crawl from the Shelley
|
|
145
|
+
* start, and either crawler.authoritative or no configured backend can serve the method.
|
|
146
|
+
*/
|
|
147
|
+
async crawlAnswers(tx, method) {
|
|
148
|
+
const coverage = await this.localCoverage(tx);
|
|
149
|
+
if (!coverage || coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
|
|
150
|
+
return null;
|
|
151
|
+
if (!this.crawlAuthoritative && this.client.hasBackendFor(method))
|
|
152
|
+
return null;
|
|
153
|
+
return { lastSlot: coverage.lastSlot };
|
|
154
|
+
}
|
|
155
|
+
/** 404 for a lookup the crawled chain answers on its own (the caller already missed in the DB). */
|
|
156
|
+
async refuseOutsideCrawl(tx, method, what) {
|
|
157
|
+
const coverage = await this.crawlAnswers(tx, method);
|
|
158
|
+
if (coverage)
|
|
159
|
+
throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
|
|
160
|
+
}
|
|
47
161
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
|
|
162
|
+
* Asset from crawled mint/burn rows: supply = mints − burns, first mint, CIP-25 payload (label 721)
|
|
163
|
+
* of the latest mint. Registry fields stay null. null = the crawled chain does not answer.
|
|
164
|
+
*/
|
|
165
|
+
async localAssetInfo(tx, unit) {
|
|
166
|
+
if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
|
|
167
|
+
return null;
|
|
168
|
+
const events = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).columns('txHash', 'action', 'quantity', 'blockTime', 'blockHeight').where({ unit }));
|
|
169
|
+
if (!events?.length)
|
|
170
|
+
throw new errors_1.NotFoundError(`Asset ${unit} (never minted in the crawled chain)`);
|
|
171
|
+
const ordered = [...events].sort((a, b) => Number(a.blockHeight ?? 0) - Number(b.blockHeight ?? 0));
|
|
172
|
+
let supply = 0n;
|
|
173
|
+
for (const e of ordered)
|
|
174
|
+
supply += (e.action === 'burn' ? -1n : 1n) * BigInt(String(e.quantity ?? '0'));
|
|
175
|
+
const mints = ordered.filter(e => e.action !== 'burn');
|
|
176
|
+
const first = mints[0];
|
|
177
|
+
const latest = mints[mints.length - 1];
|
|
178
|
+
let onchainMetadata = null;
|
|
179
|
+
if (latest) {
|
|
180
|
+
const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
|
|
181
|
+
if (meta?.payload) {
|
|
182
|
+
try {
|
|
183
|
+
onchainMetadata = JSON.parse(meta.payload);
|
|
184
|
+
}
|
|
185
|
+
catch { /* unparseable payload: leave empty */ }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const policyId = unit.slice(0, 56);
|
|
189
|
+
const assetNameHex = unit.slice(56);
|
|
190
|
+
return {
|
|
191
|
+
unit,
|
|
192
|
+
policyId,
|
|
193
|
+
assetNameHex,
|
|
194
|
+
assetName: assetNameHex ? (0, mappers_1.decodeAssetName)(assetNameHex) : null,
|
|
195
|
+
fingerprint: (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex),
|
|
196
|
+
totalSupply: supply.toString(),
|
|
197
|
+
mintOrBurnCount: ordered.length,
|
|
198
|
+
initialMintTxHash: first?.txHash ?? null,
|
|
199
|
+
initialMintTime: first?.blockTime == null ? null : Number(first.blockTime),
|
|
200
|
+
onchainMetadata,
|
|
201
|
+
registryName: null,
|
|
202
|
+
registryTicker: null,
|
|
203
|
+
registryDecimals: null,
|
|
204
|
+
registryDescription: null,
|
|
205
|
+
registryUrl: null,
|
|
206
|
+
registryLogo: null,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** Address from the crawled UTxO set when it answers, else from the backend. */
|
|
210
|
+
async resolveAddress(tx, addr) {
|
|
211
|
+
return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
|
|
212
|
+
}
|
|
213
|
+
/** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
|
|
214
|
+
async resolveAddressUtxos(tx, addr) {
|
|
215
|
+
return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
|
|
216
|
+
}
|
|
217
|
+
/** Asset from the crawled chain when it answers, else from the backend. */
|
|
218
|
+
async resolveAssetInfo(tx, unit) {
|
|
219
|
+
return (await this.localAssetInfo(tx, unit)) ?? await this.client.getAssetInfo(unit);
|
|
220
|
+
}
|
|
221
|
+
/** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
|
|
222
|
+
async resolveAssetHistory(tx, unit, limit) {
|
|
223
|
+
if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
|
|
224
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
|
|
225
|
+
return (rows ?? []).map(r => ({
|
|
226
|
+
unit: String(r.unit),
|
|
227
|
+
txHash: String(r.txHash),
|
|
228
|
+
action: r.action === 'burn' ? 'burn' : 'mint',
|
|
229
|
+
quantity: String(r.quantity),
|
|
230
|
+
blockTime: r.blockTime == null ? null : Number(r.blockTime),
|
|
231
|
+
blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
|
|
232
|
+
}));
|
|
233
|
+
}
|
|
234
|
+
return this.client.getAssetHistory(unit, limit);
|
|
235
|
+
}
|
|
236
|
+
/** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
|
|
237
|
+
async resolveCredentialUtxos(tx, credHash) {
|
|
238
|
+
return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
|
|
239
|
+
}
|
|
240
|
+
/** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
|
|
241
|
+
async resolveAddressTransactionHashes(tx, addr, limit) {
|
|
242
|
+
const local = await this.localAddressTransactions(tx, addr, limit);
|
|
243
|
+
if (local && (local.complete || local.rows.length >= limit)) {
|
|
244
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
return await this.client.getAddressTransactionHashes(addr, limit);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
|
|
251
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
252
|
+
}
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
|
|
257
|
+
async ledgerCoverageActive(tx) {
|
|
258
|
+
return Boolean((await this.localCoverage(tx))?.ledger);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Address from the crawled UTxO set: the unspent `LedgerUTxOs` (see openLedgerUtxos), type and
|
|
262
|
+
* stake address decoded from the address. An address the set has never
|
|
263
|
+
* seen is an empty address, not an error. null = the set cannot answer.
|
|
264
|
+
*/
|
|
265
|
+
async localAddress(tx, addr) {
|
|
266
|
+
if (!(await this.localCoverage(tx))?.ledger)
|
|
267
|
+
return null;
|
|
268
|
+
return addressFromUtxos(addr, await this.openLedgerUtxos(tx, [addr]));
|
|
269
|
+
}
|
|
270
|
+
/** Addresses of a stake key from the crawled UTxO set, with their unspent outputs (one read for all). */
|
|
271
|
+
async localAccountAddresses(tx, stakeAddress) {
|
|
272
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
|
|
273
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
274
|
+
if (addresses.length === 0)
|
|
275
|
+
return [];
|
|
276
|
+
const byAddress = new Map(addresses.map(a => [a, []]));
|
|
277
|
+
for (const u of await this.openLedgerUtxos(tx, addresses))
|
|
278
|
+
byAddress.get(u.address)?.push(u);
|
|
279
|
+
return addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Latest transactions of an address from the crawled UTxO set: the outputs it received
|
|
283
|
+
* (`LedgerUTxOs.txHash`) and spent (`spentTxHash`) since the anchor. `complete` = the address was
|
|
284
|
+
* first seen after the anchor, so nothing older exists. null = the set cannot answer.
|
|
285
|
+
*/
|
|
286
|
+
async localAddressTransactions(tx, addr, limit) {
|
|
287
|
+
if (!(await this.localCoverage(tx))?.ledger)
|
|
288
|
+
return null;
|
|
289
|
+
const known = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('firstSeenSlot').where({ address: addr }));
|
|
290
|
+
if (!known)
|
|
291
|
+
return { rows: [], complete: false };
|
|
292
|
+
const complete = known.firstSeenSlot != null;
|
|
293
|
+
// Candidate transactions by slot; a transaction can touch the address with several outputs.
|
|
294
|
+
const scan = Math.min(limit * 20, 2000);
|
|
295
|
+
const [created, spent] = await Promise.all([
|
|
296
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'createdSlot')
|
|
297
|
+
.where({ address: addr, createdSlot: { '>=': 0 } }).orderBy('createdSlot desc').limit(scan)),
|
|
298
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('spentTxHash', 'spentSlot')
|
|
299
|
+
.where({ address: addr, spentSlot: { '>=': 0 } }).orderBy('spentSlot desc').limit(scan)),
|
|
300
|
+
]);
|
|
301
|
+
const slotOf = new Map();
|
|
302
|
+
for (const r of created ?? [])
|
|
303
|
+
slotOf.set(r.txHash, Number(r.createdSlot));
|
|
304
|
+
for (const r of spent ?? [])
|
|
305
|
+
slotOf.set(r.spentTxHash, Number(r.spentSlot));
|
|
306
|
+
const selected = [...slotOf].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([hash]) => hash);
|
|
307
|
+
if (selected.length === 0)
|
|
308
|
+
return { rows: [], complete };
|
|
309
|
+
const [outRows, inRows] = await Promise.all([
|
|
310
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, txHash: { in: selected } })),
|
|
311
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, spentTxHash: { in: selected } })),
|
|
312
|
+
]);
|
|
313
|
+
const amounts = await this.ledgerAmounts(tx, [...(outRows ?? []), ...(inRows ?? [])]);
|
|
314
|
+
const amountOf = (r) => amounts.get(`${r.txHash}#${Number(r.outputIndex)}`) ?? [];
|
|
315
|
+
const txs = selected.map((hash) => ({
|
|
316
|
+
hash,
|
|
317
|
+
blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, slotOf.get(hash)),
|
|
318
|
+
inputs: (inRows ?? []).filter(r => r.spentTxHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
|
|
319
|
+
outputs: (outRows ?? []).filter(r => r.txHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
|
|
320
|
+
}));
|
|
321
|
+
const rows = (0, mappers_1.mapAddressTransactions)(addr, txs);
|
|
322
|
+
rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0));
|
|
323
|
+
return { rows: rows, complete };
|
|
324
|
+
}
|
|
325
|
+
/** Amount lists (lovelace + assets) of `LedgerUTxOs` rows, keyed `txHash#outputIndex`. */
|
|
326
|
+
async ledgerAmounts(tx, rows) {
|
|
327
|
+
const out = new Map();
|
|
328
|
+
for (const r of rows)
|
|
329
|
+
out.set(`${r.txHash}#${Number(r.outputIndex)}`, [{ unit: 'lovelace', quantity: String(r.lovelace ?? '0') }]);
|
|
330
|
+
const withAssets = [...new Set(rows.filter(r => r.hasAssets).map(r => String(r.txHash)))];
|
|
331
|
+
for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
|
|
332
|
+
const assetRows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).columns('utxo_txHash', 'utxo_outputIndex', 'unit', 'asset_quantity')
|
|
333
|
+
.where({ utxo_txHash: { in: hashChunk } }));
|
|
334
|
+
for (const a of assetRows ?? []) {
|
|
335
|
+
out.get(`${a.utxo_txHash}#${Number(a.utxo_outputIndex)}`)?.push({ unit: a.unit, quantity: String(a.asset_quantity) });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Active stake of a pool from the Ogmios epoch snapshot of the running epoch (constant within
|
|
342
|
+
* an epoch). Empty when the crawler is not at the tip or the epoch has no such snapshot.
|
|
343
|
+
*/
|
|
344
|
+
async snapshotActiveStake(tx, poolId) {
|
|
345
|
+
const coverage = await this.localCoverage(tx);
|
|
346
|
+
if (!coverage)
|
|
347
|
+
return {};
|
|
348
|
+
const epoch = (0, epoch_slots_1.epochOfSlot)(this.client.network, coverage.lastSlot);
|
|
349
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.PoolEpochSnapshots).columns('activeStake', 'activeSize').where({ poolId, epoch, source: 'ogmios' }));
|
|
350
|
+
if (!row || row.activeStake == null)
|
|
351
|
+
return {};
|
|
352
|
+
return { activeStake: lovelaceSum(row.activeStake), activeSize: Number(row.activeSize ?? 0) };
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Lifetime withdrawals of a stake key from crawled withdrawals — only when certificates are
|
|
356
|
+
* crawled and the crawl covers the chain since Shelley; null otherwise.
|
|
357
|
+
*/
|
|
358
|
+
async localWithdrawalsSum(tx, stakeAddress) {
|
|
359
|
+
const coverage = await this.localCoverage(tx);
|
|
360
|
+
if (!coverage || !this.crawlCertificates)
|
|
361
|
+
return null;
|
|
362
|
+
if (coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
|
|
363
|
+
return null;
|
|
364
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionWithdrawals).columns('sum(lovelace) as total').where({ stakeAddress }));
|
|
365
|
+
return lovelaceSum(row?.total);
|
|
366
|
+
}
|
|
367
|
+
/** The anchor the imported UTxO set describes (null = ledger mode inactive). */
|
|
368
|
+
setUtxoAnchor(anchor) {
|
|
369
|
+
this.utxoAnchor = anchor;
|
|
370
|
+
this.utxoAnchorVerified = false;
|
|
371
|
+
this.ledgerInvalidation = null;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* The imported set describes the chain AT the anchor block, so before the first block past it
|
|
375
|
+
* is applied the cursor (not yet advanced in this transaction) must equal the anchor exactly;
|
|
376
|
+
* otherwise the snapshot was taken on a fork. Skipped once `utxoAppliedSlot` is set.
|
|
377
|
+
*/
|
|
378
|
+
async verifyUtxoAnchor(tx, anchor) {
|
|
379
|
+
const cursor = await (0, sync_state_1.readCursor)(tx);
|
|
380
|
+
if (cursor?.utxoSet.appliedSlot != null)
|
|
381
|
+
return true;
|
|
382
|
+
if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
|
|
383
|
+
return true;
|
|
384
|
+
const reason = cursor
|
|
385
|
+
? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
|
|
386
|
+
: `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
|
|
387
|
+
logger.error(`UTxO set invalidated: ${reason} — the snapshot describes a fork; re-import at the crawler cursor`);
|
|
388
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
|
|
389
|
+
this.ledgerInvalidation = reason;
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
/** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
|
|
393
|
+
getUtxoAnchor() {
|
|
394
|
+
return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
|
|
395
|
+
}
|
|
396
|
+
/** Apply the memo updates of the block transaction that just committed. */
|
|
397
|
+
confirmBlockCommit() {
|
|
398
|
+
const pending = this.pendingCommit;
|
|
399
|
+
this.pendingCommit = [];
|
|
400
|
+
for (const apply of pending)
|
|
401
|
+
apply();
|
|
402
|
+
}
|
|
403
|
+
/** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
|
|
404
|
+
takeLedgerInvalidation() {
|
|
405
|
+
const reason = this.ledgerInvalidation;
|
|
406
|
+
if (reason) {
|
|
407
|
+
this.ledgerInvalidation = null;
|
|
408
|
+
this.utxoAnchor = null;
|
|
409
|
+
this.utxoAnchorVerified = false;
|
|
410
|
+
}
|
|
411
|
+
return reason;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
|
|
415
|
+
* its own transaction. A failing unit is dropped; its bare row stays for the lazy path.
|
|
416
|
+
*/
|
|
417
|
+
startAssetEnrichment() {
|
|
418
|
+
if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
|
|
419
|
+
return;
|
|
420
|
+
const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
|
|
421
|
+
this.enrichTimer = setInterval(() => {
|
|
422
|
+
const unit = this.enrichQueue.shift();
|
|
423
|
+
if (unit === undefined) {
|
|
424
|
+
this.stopAssetEnrichment();
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
|
|
428
|
+
logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
|
|
429
|
+
});
|
|
430
|
+
}, intervalMs);
|
|
431
|
+
this.enrichTimer.unref?.();
|
|
432
|
+
}
|
|
433
|
+
/** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
|
|
434
|
+
stopAssetEnrichment() {
|
|
435
|
+
if (this.enrichTimer) {
|
|
436
|
+
clearInterval(this.enrichTimer);
|
|
437
|
+
this.enrichTimer = null;
|
|
438
|
+
}
|
|
439
|
+
this.enrichQueue = [];
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block write
|
|
443
|
+
* transaction so no backend round-trip runs under the DB write lock. Never throws.
|
|
51
444
|
*/
|
|
52
445
|
async prefetchCrawlEpoch(epochNumber) {
|
|
53
446
|
const previousEpoch = this.crawlEpochCurrent;
|
|
@@ -81,96 +474,129 @@ class CardanoIndexer {
|
|
|
81
474
|
return;
|
|
82
475
|
if (!force && existing && now < existing.nextRefreshAt)
|
|
83
476
|
return;
|
|
477
|
+
const crawled = await this.crawledEpochTotals(epochNumber);
|
|
84
478
|
try {
|
|
85
|
-
const
|
|
479
|
+
const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
|
|
86
480
|
this.crawlEpochCache.set(epochNumber, {
|
|
87
|
-
row,
|
|
481
|
+
row: crawled ? { ...provided, ...crawled } : provided,
|
|
88
482
|
nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
|
|
89
483
|
finalized,
|
|
90
484
|
});
|
|
91
485
|
}
|
|
92
486
|
catch {
|
|
93
|
-
// Keep the last good snapshot, but retry transient/negative
|
|
94
|
-
// than suppressing enrichment for the rest of the five-day epoch.
|
|
487
|
+
// Keep the last good snapshot (or the crawled totals alone), but retry transient/negative
|
|
488
|
+
// results soon rather than suppressing enrichment for the rest of the five-day epoch.
|
|
489
|
+
const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
|
|
95
490
|
this.crawlEpochCache.set(epochNumber, {
|
|
96
|
-
row:
|
|
491
|
+
row: base && crawled ? { ...base, ...crawled } : base,
|
|
97
492
|
nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
|
|
98
493
|
finalized: false,
|
|
99
494
|
});
|
|
100
495
|
}
|
|
101
496
|
}
|
|
102
497
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
* @param txBuilder - The CardanoTransactionBuilder instance for transaction building
|
|
498
|
+
* Block, transaction and fee totals of an epoch summed over the crawled blocks, when the crawl
|
|
499
|
+
* covers the epoch from its first slot; null otherwise. Output and active stake stay with the backend.
|
|
106
500
|
*/
|
|
501
|
+
async crawledEpochTotals(epochNumber) {
|
|
502
|
+
try {
|
|
503
|
+
const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
|
|
504
|
+
if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
|
|
505
|
+
return null;
|
|
506
|
+
const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
|
|
507
|
+
.columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(time) as firstBlockTime', 'max(time) as lastBlockTime')
|
|
508
|
+
.where({ epochNumber }));
|
|
509
|
+
if (!row || Number(row.blockCount ?? 0) === 0)
|
|
510
|
+
return null;
|
|
511
|
+
return {
|
|
512
|
+
blockCount: Number(row.blockCount),
|
|
513
|
+
txCount: Number(row.txCount ?? 0),
|
|
514
|
+
fees: lovelaceSum(row.fees),
|
|
515
|
+
firstBlockTime: row.firstBlockTime != null ? Number(row.firstBlockTime) : null,
|
|
516
|
+
lastBlockTime: row.lastBlockTime != null ? Number(row.lastBlockTime) : null,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
logger.debug(`Crawled totals for epoch ${epochNumber} unavailable:`, err);
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
/** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
|
|
525
|
+
bareEpochRow(epochNumber) {
|
|
526
|
+
const network = this.client.network;
|
|
527
|
+
const start = (0, epoch_slots_1.epochStartSlot)(network, epochNumber);
|
|
528
|
+
return {
|
|
529
|
+
epoch: epochNumber,
|
|
530
|
+
startTime: (0, epoch_slots_1.slotToPosixSeconds)(network, start),
|
|
531
|
+
endTime: (0, epoch_slots_1.slotToPosixSeconds)(network, (0, epoch_slots_1.epochStartSlot)(network, epochNumber + 1)),
|
|
532
|
+
output: null,
|
|
533
|
+
activeStake: null,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
107
536
|
constructor(client, txBuilder) {
|
|
108
537
|
this.client = client;
|
|
109
538
|
this.txBuilder = txBuilder;
|
|
539
|
+
txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
|
|
110
540
|
logger.info('CardanoIndexer instance created');
|
|
111
541
|
}
|
|
112
542
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
543
|
+
* Unspent outputs of an address from the crawled set for the transaction builder; null = the set
|
|
544
|
+
* cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
|
|
545
|
+
*/
|
|
546
|
+
async localAddressUtxos(address) {
|
|
547
|
+
if (!cds_1.default.db)
|
|
548
|
+
return null;
|
|
549
|
+
return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
|
|
553
|
+
* transaction, so either everything persists or nothing does.
|
|
119
554
|
*/
|
|
120
555
|
async indexTransaction(tx, txHash) {
|
|
121
|
-
|
|
556
|
+
await this.refuseOutsideCrawl(tx, 'getTransaction', `Transaction ${txHash}`);
|
|
122
557
|
const providerTx = await this.client.getTransaction(txHash);
|
|
123
558
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
124
559
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
125
560
|
logger.debug(`indexTransaction: upserted transaction ${txHash}`);
|
|
561
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
562
|
+
return txRow;
|
|
563
|
+
}
|
|
564
|
+
/** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
|
|
565
|
+
async writeTransactionChildren(tx, providerTx, txSeq) {
|
|
126
566
|
if (providerTx.inputs) {
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
if (inputRows.length) {
|
|
567
|
+
const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
|
|
568
|
+
const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
|
|
569
|
+
if (inputRows.length)
|
|
131
570
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
if (inputAssetRows.length) {
|
|
571
|
+
if (inputAssetRows.length)
|
|
135
572
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
|
|
136
|
-
logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
|
|
137
|
-
}
|
|
138
573
|
}
|
|
139
|
-
//
|
|
140
|
-
// `inputs` previously skipped its outputs entirely)
|
|
574
|
+
// outputs must not depend on the inputs branch
|
|
141
575
|
if (providerTx.outputs) {
|
|
142
|
-
const outputRows = (0, mappers_1.mapTransactionOutputs)(
|
|
143
|
-
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(
|
|
144
|
-
if (outputRows.length)
|
|
576
|
+
const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
|
|
577
|
+
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
|
|
578
|
+
if (outputRows.length)
|
|
145
579
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
146
|
-
|
|
147
|
-
if (outputAssetRows.length) {
|
|
580
|
+
if (outputAssetRows.length)
|
|
148
581
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
149
|
-
}
|
|
150
582
|
}
|
|
151
583
|
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
|
|
152
|
-
if (metadataRows.length)
|
|
584
|
+
if (metadataRows.length)
|
|
153
585
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
154
|
-
}
|
|
155
|
-
return txRow;
|
|
156
586
|
}
|
|
157
587
|
/**
|
|
158
|
-
* Index
|
|
159
|
-
*
|
|
160
|
-
* @param tx CAP transaction
|
|
161
|
-
* @param addr bech32 address
|
|
162
|
-
* @return {Promise<Address>} address entity data
|
|
588
|
+
* Index address data with assets and UTxOs; transactions are loaded separately via
|
|
589
|
+
* indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
|
|
163
590
|
*/
|
|
164
|
-
async indexAddress(tx, addr) {
|
|
165
|
-
const addrData = await this.
|
|
591
|
+
async indexAddress(tx, addr, prefetched) {
|
|
592
|
+
const addrData = prefetched ?? await this.resolveAddress(tx, addr);
|
|
166
593
|
logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
|
|
167
594
|
const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
|
|
168
595
|
const now = new Date().toISOString();
|
|
169
596
|
const validFrom = AddrEntity.validFrom ?? now;
|
|
170
597
|
const validTo = AddrEntity.validTo ?? now;
|
|
171
598
|
await tx.run(UPSERT.into(CardanoODataService_1.Addresses).entries(AddrEntity));
|
|
172
|
-
//
|
|
173
|
-
// Supplement address-level amounts with assets found in UTxOs but missing from addresses endpoint
|
|
599
|
+
// Supplement address-level amounts with assets only present in UTxOs
|
|
174
600
|
const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
|
|
175
601
|
for (const utxo of addrData.utxos) {
|
|
176
602
|
for (const amt of utxo.amount) {
|
|
@@ -220,21 +646,13 @@ class CardanoIndexer {
|
|
|
220
646
|
return AddrEntity;
|
|
221
647
|
}
|
|
222
648
|
/**
|
|
223
|
-
* Index UTxOs by 28-byte payment credential
|
|
224
|
-
*
|
|
225
|
-
* current data. Underlying AddressUTxOs/UTxOAssets rows are UPSERTed and stay
|
|
226
|
-
* available for follow-up address-keyed queries within the TTL.
|
|
227
|
-
*
|
|
228
|
-
* Does NOT upsert parent Addresses rows; child rows reference bech32 addresses
|
|
229
|
-
* that may not yet have a parent stub. Same pattern as TransactionInputs.
|
|
230
|
-
*
|
|
231
|
-
* @param tx CAP transaction
|
|
232
|
-
* @param credHash 28-byte payment credential as 56-char lowercase hex
|
|
233
|
-
* @return UTxO entity rows across all bech32 addresses sharing the credential
|
|
649
|
+
* Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
|
|
650
|
+
* rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
|
|
234
651
|
*/
|
|
235
652
|
async indexCredentialUtxos(tx, credHash) {
|
|
236
|
-
const
|
|
237
|
-
|
|
653
|
+
const local = await this.localCredentialUtxos(tx, credHash);
|
|
654
|
+
const utxos = local ?? await this.client.getCredentialUtxos(credHash);
|
|
655
|
+
logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
|
|
238
656
|
if (utxos.length === 0)
|
|
239
657
|
return [];
|
|
240
658
|
// Group by bech32 address — Koios returns UTxOs across all bech32 forms
|
|
@@ -271,17 +689,104 @@ class CardanoIndexer {
|
|
|
271
689
|
return allRows;
|
|
272
690
|
}
|
|
273
691
|
/**
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
* the
|
|
277
|
-
*
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
692
|
+
* UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
|
|
693
|
+
* UTxO set (see openLedgerUtxos).
|
|
694
|
+
* null = the crawled set cannot answer (not synced, no set, credential column still filling).
|
|
695
|
+
* An address first used in the last `confirmationDepth` blocks is not in the set yet.
|
|
696
|
+
*/
|
|
697
|
+
async localCredentialUtxos(tx, credHash) {
|
|
698
|
+
if (!(await this.localCoverage(tx))?.ledger || !(await this.paymentCredentialsReady()))
|
|
699
|
+
return null;
|
|
700
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
|
|
701
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
702
|
+
if (addresses.length === 0)
|
|
703
|
+
return [];
|
|
704
|
+
return this.openLedgerUtxos(tx, addresses);
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Unspent outputs of addresses from the crawled set, checked against the node by output reference
|
|
708
|
+
* (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
|
|
709
|
+
* the cursor. Without a usable node, or when the check fails, the set as of the cursor.
|
|
710
|
+
*/
|
|
711
|
+
async openLedgerUtxos(tx, addresses) {
|
|
712
|
+
const rows = await this.ledgerUtxosOf(tx, addresses);
|
|
713
|
+
if (rows.length === 0)
|
|
714
|
+
return rows;
|
|
715
|
+
try {
|
|
716
|
+
const unspent = new Map();
|
|
717
|
+
for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
|
|
718
|
+
const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
|
|
719
|
+
if (live === null)
|
|
720
|
+
return rows;
|
|
721
|
+
for (const u of live)
|
|
722
|
+
unspent.set(`${u.txHash}#${u.outputIndex}`, u);
|
|
723
|
+
}
|
|
724
|
+
// The node's answer names the reference script, which a snapshot row from a file import lacks
|
|
725
|
+
return rows.flatMap(u => {
|
|
726
|
+
const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
|
|
727
|
+
if (!live)
|
|
728
|
+
return [];
|
|
729
|
+
return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
catch (err) {
|
|
733
|
+
logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
|
|
734
|
+
return rows;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
/** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
|
|
738
|
+
async ledgerUtxosOf(tx, addresses) {
|
|
739
|
+
const out = [];
|
|
740
|
+
for (const addrChunk of (0, collections_1.chunk)(addresses, collections_1.IN_CHUNK)) {
|
|
741
|
+
const utxos = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: { in: addrChunk }, spentTxHash: null }));
|
|
742
|
+
const amounts = await this.ledgerAmounts(tx, utxos ?? []);
|
|
743
|
+
for (const u of utxos ?? []) {
|
|
744
|
+
const txHash = String(u.txHash);
|
|
745
|
+
const outputIndex = Number(u.outputIndex);
|
|
746
|
+
out.push({
|
|
747
|
+
txHash,
|
|
748
|
+
outputIndex,
|
|
749
|
+
address: String(u.address),
|
|
750
|
+
amount: amounts.get(`${txHash}#${outputIndex}`) ?? [],
|
|
751
|
+
blockHash: '',
|
|
752
|
+
datumHash: u.utxo_dataHash ?? undefined,
|
|
753
|
+
inlineDatum: u.utxo_inlineDatum ?? null,
|
|
754
|
+
scriptRef: u.utxo_referenceScriptHash ?? undefined,
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return out;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* True once every Shelley-type `LedgerAddresses` row carries its payment credential. Until then
|
|
762
|
+
* the fill runs in the background (started once per process) and callers use the provider.
|
|
763
|
+
*/
|
|
764
|
+
async paymentCredentialsReady() {
|
|
765
|
+
if (this.credentialsReady)
|
|
766
|
+
return true;
|
|
767
|
+
if (!this.credentialFill) {
|
|
768
|
+
const generation = this.credentialGeneration;
|
|
769
|
+
this.credentialFill = (0, ledger_state_1.backfillPaymentCredentials)()
|
|
770
|
+
.then((n) => {
|
|
771
|
+
if (generation !== this.credentialGeneration)
|
|
772
|
+
return;
|
|
773
|
+
this.credentialsReady = true;
|
|
774
|
+
if (n > 0)
|
|
775
|
+
logger.info(`payment credentials filled for ${n} ledger addresses`);
|
|
776
|
+
})
|
|
777
|
+
.catch((err) => logger.error('payment credential fill failed (retried on the next lookup):', err))
|
|
778
|
+
.finally(() => { this.credentialFill = null; });
|
|
779
|
+
}
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
/** The ledger tables were replaced (re-import): the credential column has to be filled again. */
|
|
783
|
+
resetPaymentCredentials() {
|
|
784
|
+
this.credentialGeneration++;
|
|
785
|
+
this.credentialsReady = false;
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
|
|
789
|
+
* backends without address aggregation such as Ogmios. Writes no parent Addresses row.
|
|
285
790
|
*/
|
|
286
791
|
async indexAddressUtxos(tx, addr) {
|
|
287
792
|
const utxos = await this.client.getAddressUtxos(addr);
|
|
@@ -307,21 +812,9 @@ class CardanoIndexer {
|
|
|
307
812
|
return utxoEntities;
|
|
308
813
|
}
|
|
309
814
|
/**
|
|
310
|
-
* Evict cached rows a submitted transaction made stale
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
* - all address-level rows of the output addresses (their UTxO set gained
|
|
314
|
-
* the new outputs — sender change included) and of `extraAddresses`
|
|
315
|
-
* (e.g. the build's sender when the CBOR could not be parsed).
|
|
316
|
-
*
|
|
317
|
-
* Only the read cache is touched; submissions/builds stay untouched. Note the
|
|
318
|
-
* next refetch may STILL see pre-submit state on lagging backends
|
|
319
|
-
* (Blockfrost/Koios propagation) — that matches cache-less behaviour and is
|
|
320
|
-
* not recoverable server-side.
|
|
321
|
-
*
|
|
322
|
-
* @param tx CAP transaction
|
|
323
|
-
* @param targets input refs + output addresses from extractTxCacheTargets
|
|
324
|
-
* @param extraAddresses additional bech32 addresses to evict
|
|
815
|
+
* Evict cached rows a submitted transaction made stale: every consumed input ref (under any
|
|
816
|
+
* address) and all address-level rows of the output addresses plus `extraAddresses`. Only the
|
|
817
|
+
* read cache is touched; lagging backends may still serve pre-submit state on refetch.
|
|
325
818
|
*/
|
|
326
819
|
async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
|
|
327
820
|
const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
|
|
@@ -339,21 +832,32 @@ class CardanoIndexer {
|
|
|
339
832
|
logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
|
|
340
833
|
}
|
|
341
834
|
}
|
|
342
|
-
/**
|
|
343
|
-
* Index & return address transactions (separate from indexAddress for lazy loading)
|
|
344
|
-
* @param tx CAP transaction
|
|
345
|
-
* @param addr bech32 address
|
|
346
|
-
* @param limit maximum number of transactions to fetch
|
|
347
|
-
* @return {Promise<AddressTransactions[]>} address transaction entities
|
|
348
|
-
*/
|
|
835
|
+
/** Index address transactions (separate from indexAddress for lazy loading). */
|
|
349
836
|
async indexAddressTransactions(tx, addr, limit) {
|
|
350
837
|
logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
|
|
351
|
-
|
|
352
|
-
const
|
|
838
|
+
const local = await this.localAddressTransactions(tx, addr, limit);
|
|
839
|
+
const keepLocal = async () => {
|
|
840
|
+
if (local.rows.length)
|
|
841
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(local.rows));
|
|
842
|
+
return local.rows;
|
|
843
|
+
};
|
|
844
|
+
if (local && (local.complete || local.rows.length >= limit))
|
|
845
|
+
return keepLocal();
|
|
846
|
+
// Hash-only listing (one API call)
|
|
847
|
+
let txHashes;
|
|
848
|
+
try {
|
|
849
|
+
txHashes = await this.client.getAddressTransactionHashes(addr, limit);
|
|
850
|
+
}
|
|
851
|
+
catch (err) {
|
|
852
|
+
// No backend with address history: what the crawled set holds is the best answer there is.
|
|
853
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError))
|
|
854
|
+
return keepLocal();
|
|
855
|
+
throw err;
|
|
856
|
+
}
|
|
353
857
|
logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
|
|
354
858
|
if (txHashes.length === 0)
|
|
355
859
|
return [];
|
|
356
|
-
//
|
|
860
|
+
// DB-first dedup + batch fetch
|
|
357
861
|
const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
|
|
358
862
|
// For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
|
|
359
863
|
// Transactions already in DB were not re-fetched — batch-fetch those separately.
|
|
@@ -387,42 +891,29 @@ class CardanoIndexer {
|
|
|
387
891
|
transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
|
|
388
892
|
return transactionsEntities;
|
|
389
893
|
}
|
|
390
|
-
/**
|
|
391
|
-
* Index & return address signing request association
|
|
392
|
-
* Links an address to a signing request for address-based queries
|
|
393
|
-
* @param tx CAP transaction
|
|
394
|
-
* @param addr bech32 address
|
|
395
|
-
* @param signingRequestId signing request UUID
|
|
396
|
-
* @return {Promise<void>}
|
|
397
|
-
*/
|
|
894
|
+
/** Link an address to a signing request for address-based queries. */
|
|
398
895
|
async indexAddressSigningRequests(tx, addr, signingRequestId) {
|
|
399
896
|
logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
|
|
400
897
|
const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
|
|
401
898
|
await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
|
|
402
899
|
logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
|
|
403
900
|
}
|
|
404
|
-
/**
|
|
405
|
-
* Index & return address transaction build association
|
|
406
|
-
* Links an address to a transaction build for address-based queries
|
|
407
|
-
* @param tx CAP transaction
|
|
408
|
-
* @param addr bech32 address
|
|
409
|
-
* @param buildId transaction build UUID
|
|
410
|
-
* @return {Promise<void>}
|
|
411
|
-
*/
|
|
901
|
+
/** Link an address to a transaction build for address-based queries. */
|
|
412
902
|
async indexAddressTransactionBuilds(tx, addr, buildId) {
|
|
413
903
|
logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
|
|
414
904
|
const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
|
|
415
905
|
await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
|
|
416
906
|
logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
|
|
417
907
|
}
|
|
418
|
-
/**
|
|
419
|
-
* Index & return metadata for a single transaction (Metadata)
|
|
420
|
-
* @param tx CAP transaction
|
|
421
|
-
* @param txHash transaction hash
|
|
422
|
-
* @param metadata raw metadata object (label -> JSONValue)
|
|
423
|
-
* @return {Promise<TransactionMetadata[]>} array of transaction metadata rows
|
|
424
|
-
*/
|
|
908
|
+
/** Index the metadata rows of a transaction. */
|
|
425
909
|
async indexTransactionMetadata(tx, tx_hash) {
|
|
910
|
+
// A crawled transaction without metadata rows has no metadata.
|
|
911
|
+
if (await this.crawlAnswers(tx, 'getTransactionMetadata')) {
|
|
912
|
+
const known = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
|
|
913
|
+
if (known)
|
|
914
|
+
return [];
|
|
915
|
+
await this.refuseOutsideCrawl(tx, 'getTransactionMetadata', `Transaction ${tx_hash}`);
|
|
916
|
+
}
|
|
426
917
|
const metadata = await this.client.getTransactionMetadata(tx_hash);
|
|
427
918
|
const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
|
|
428
919
|
if (rows.length) {
|
|
@@ -430,24 +921,23 @@ class CardanoIndexer {
|
|
|
430
921
|
}
|
|
431
922
|
return rows;
|
|
432
923
|
}
|
|
433
|
-
/**
|
|
434
|
-
* Index & return the network information data
|
|
435
|
-
* @param tx CAP transaction object
|
|
436
|
-
* @returns {Promise<NetworkInformation>} network information entity data
|
|
437
|
-
*/
|
|
924
|
+
/** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
|
|
438
925
|
async indexNetworkInformation(tx) {
|
|
439
|
-
const
|
|
440
|
-
const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
|
|
926
|
+
const netEntity = (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
|
|
441
927
|
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
442
928
|
return netEntity;
|
|
443
929
|
}
|
|
444
|
-
/**
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
930
|
+
/** Network information from the backend; circulating supply from the crawled UTxO set when current. */
|
|
931
|
+
async resolveNetworkInformation(tx) {
|
|
932
|
+
const netInfo = await this.client.getNetworkInformation();
|
|
933
|
+
const circulating = (await this.localCoverage(tx))?.ledger
|
|
934
|
+
? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
|
|
935
|
+
: null;
|
|
936
|
+
return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
|
|
937
|
+
}
|
|
938
|
+
/** Index a block by hash, with best-effort epoch enrichment. */
|
|
450
939
|
async indexBlock(tx, blockHash) {
|
|
940
|
+
await this.refuseOutsideCrawl(tx, 'getBlock', `Block ${blockHash}`);
|
|
451
941
|
const blockInfo = await this.client.getBlock(blockHash);
|
|
452
942
|
let epoch;
|
|
453
943
|
try {
|
|
@@ -461,48 +951,78 @@ class CardanoIndexer {
|
|
|
461
951
|
return blockEntity;
|
|
462
952
|
}
|
|
463
953
|
/**
|
|
464
|
-
* Bulk-index a whole block and
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
* accumulated across the block's txs and UPSERTed once per table (few statements).
|
|
468
|
-
*
|
|
469
|
-
* All writes run inside the caller's CAP transaction (`tx`), so a block is persisted
|
|
470
|
-
* atomically — a failure mid-block rolls the whole block back, keeping the cursor and
|
|
471
|
-
* the data consistent.
|
|
472
|
-
*
|
|
473
|
-
* Inputs from the Ogmios chain-sync path arrive as bare references (no address/amount);
|
|
474
|
-
* resolveInputs() backfills them from this block's own outputs and previously-indexed
|
|
475
|
-
* outputs before mapping. Blockfrost/Koios inputs already carry address/amount and are
|
|
476
|
-
* left untouched.
|
|
477
|
-
*
|
|
478
|
-
* @param tx CAP transaction (one per block, committed by the crawler)
|
|
479
|
-
* @param blockData block header/summary from the crawler source
|
|
480
|
-
* @param txs the block's full transaction list (in block order)
|
|
954
|
+
* Bulk-index a whole block and its transactions in one pass for the crawler: no per-hash
|
|
955
|
+
* re-fetch, one UPSERT per table, all inside the caller's transaction so the block persists
|
|
956
|
+
* atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
|
|
481
957
|
*/
|
|
482
958
|
async indexBlockFull(tx, blockData, txs) {
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
// if the caller skipped
|
|
959
|
+
// Memo updates of a rolled-back attempt must not survive into this one.
|
|
960
|
+
this.pendingCommit = [];
|
|
961
|
+
// Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
|
|
962
|
+
// (memoized) and accept the in-tx fetch.
|
|
486
963
|
let epoch;
|
|
487
964
|
if (blockData.epoch != null) {
|
|
488
965
|
await this.prefetchCrawlEpoch(blockData.epoch);
|
|
489
966
|
epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
|
|
490
967
|
const epochRows = [...this.crawlEpochCache.values()]
|
|
491
968
|
.map((entry) => entry.row)
|
|
492
|
-
.filter((row) => row !== undefined);
|
|
493
|
-
if (epochRows.length)
|
|
969
|
+
.filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
|
|
970
|
+
if (epochRows.length) {
|
|
494
971
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
972
|
+
this.pendingCommit.push(() => { for (const row of epochRows)
|
|
973
|
+
this.crawlEpochWritten.add(row); });
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
// Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
|
|
977
|
+
// Decided up front so input resolution and the ledger apply share one read of the set.
|
|
978
|
+
const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
|
|
979
|
+
const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
|
|
980
|
+
let anchorVerified = false;
|
|
981
|
+
if (ledgerDue && !priorInvalidation) {
|
|
982
|
+
anchorVerified = this.utxoAnchorVerified;
|
|
983
|
+
if (!anchorVerified) {
|
|
984
|
+
const anchor = this.utxoAnchor;
|
|
985
|
+
anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
|
|
986
|
+
// Remembered only once this transaction commits, like the other crawl memos.
|
|
987
|
+
if (anchorVerified)
|
|
988
|
+
this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
|
|
989
|
+
this.utxoAnchorVerified = true; });
|
|
990
|
+
}
|
|
495
991
|
}
|
|
992
|
+
const ledgerLookup = anchorVerified
|
|
993
|
+
? { hashes: new Set(), rows: new Map(), assets: new Map() }
|
|
994
|
+
: undefined;
|
|
995
|
+
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
996
|
+
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
997
|
+
// corrected fee changes the block's fee total.
|
|
998
|
+
await this.resolveInputs(tx, txs, ledgerLookup);
|
|
999
|
+
this.applyCollateralFees(blockData, txs);
|
|
496
1000
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
497
|
-
|
|
498
|
-
await this.
|
|
499
|
-
//
|
|
1001
|
+
await this.removeSupersededBlocks(tx, blockData);
|
|
1002
|
+
await this.removeStaleTxSeqs(tx, txs);
|
|
1003
|
+
// One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
|
|
1004
|
+
// srv/utils/db-sanitize.ts, not per call site.
|
|
500
1005
|
const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
|
|
501
|
-
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.
|
|
502
|
-
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.
|
|
503
|
-
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.
|
|
504
|
-
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.
|
|
1006
|
+
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
1007
|
+
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
1008
|
+
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
1009
|
+
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
505
1010
|
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
|
|
1011
|
+
// Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
|
|
1012
|
+
// re-crawl is idempotent and a reorg removes them with their tx.
|
|
1013
|
+
const certificateRows = this.crawlCertificates
|
|
1014
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
|
|
1015
|
+
: [];
|
|
1016
|
+
const withdrawalRows = this.crawlCertificates
|
|
1017
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
|
|
1018
|
+
: [];
|
|
1019
|
+
if (this.crawlCertificates)
|
|
1020
|
+
this.warnIfCertificatesUnreported(txs);
|
|
1021
|
+
// Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
|
|
1022
|
+
const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
|
|
1023
|
+
// Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
|
|
1024
|
+
// idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
|
|
1025
|
+
const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
|
|
506
1026
|
if (txRows.length)
|
|
507
1027
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
|
|
508
1028
|
if (inputRows.length)
|
|
@@ -515,21 +1035,97 @@ class CardanoIndexer {
|
|
|
515
1035
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
516
1036
|
if (metadataRows.length)
|
|
517
1037
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
518
|
-
|
|
1038
|
+
if (certificateRows.length)
|
|
1039
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
|
|
1040
|
+
if (withdrawalRows.length)
|
|
1041
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
|
|
1042
|
+
if (redeemerRows.length)
|
|
1043
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
|
|
1044
|
+
// Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
|
|
1045
|
+
if (ledgerDue) {
|
|
1046
|
+
if (priorInvalidation) {
|
|
1047
|
+
// Decided in an earlier attempt of this block whose transaction rolled back: re-write
|
|
1048
|
+
// the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
|
|
1049
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
|
|
1050
|
+
}
|
|
1051
|
+
else if (ledgerLookup) {
|
|
1052
|
+
const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
|
|
1053
|
+
if (ledger.missing) {
|
|
1054
|
+
logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
|
|
1055
|
+
'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
if (assetHistoryRows.length)
|
|
1060
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
|
|
1061
|
+
// Catalogue last; collecting the units is skipped entirely when the catalogue is off.
|
|
1062
|
+
const newAssets = this.crawlAssetCatalogue === 'off'
|
|
1063
|
+
? 0
|
|
1064
|
+
: await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
|
|
1065
|
+
logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
|
|
1066
|
+
`${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Drop other Block rows at the crawled block's height that no transaction references: lazily
|
|
1070
|
+
* indexed tips that were rolled back, which no crawler reorg covers.
|
|
1071
|
+
*/
|
|
1072
|
+
async removeSupersededBlocks(tx, blockData) {
|
|
1073
|
+
if (blockData.height == null)
|
|
1074
|
+
return;
|
|
1075
|
+
const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
|
|
1076
|
+
if (!others?.length)
|
|
1077
|
+
return;
|
|
1078
|
+
const hashes = others.map(r => r.hash);
|
|
1079
|
+
const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
|
|
1080
|
+
const keep = new Set((referenced ?? []).map(r => r.blockHash));
|
|
1081
|
+
const stale = hashes.filter(h => !keep.has(h));
|
|
1082
|
+
if (!stale.length)
|
|
1083
|
+
return;
|
|
1084
|
+
await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
|
|
1085
|
+
logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
|
|
519
1086
|
}
|
|
520
1087
|
/**
|
|
521
|
-
*
|
|
522
|
-
*
|
|
523
|
-
* tx's output in the same block), then batch-reads previously-indexed outputs from the
|
|
524
|
-
* DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
|
|
1088
|
+
* Drop transactions of another fork that hold one of this block's txSeq keys (a lazily indexed
|
|
1089
|
+
* tx from a rolled-back block at the same slot); their input/output rows would mix with ours.
|
|
525
1090
|
*/
|
|
526
|
-
async
|
|
527
|
-
|
|
1091
|
+
async removeStaleTxSeqs(tx, txs) {
|
|
1092
|
+
if (!txs.length)
|
|
1093
|
+
return;
|
|
1094
|
+
const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
1095
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
|
|
1096
|
+
.where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
|
|
1097
|
+
const ours = new Set(txs.map(t => t.hash));
|
|
1098
|
+
const stale = (rows ?? []).filter(r => !ours.has(r.hash));
|
|
1099
|
+
if (!stale.length)
|
|
1100
|
+
return;
|
|
1101
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
|
|
1102
|
+
logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Warn once when `crawler.certificates` is on but the source reports none (`certificates`
|
|
1106
|
+
* undefined, as with Blockfrost). `[]` means "none" and is not a warning.
|
|
1107
|
+
*/
|
|
1108
|
+
warnIfCertificatesUnreported(txs) {
|
|
1109
|
+
if (this.certificatesUnreportedWarned || !txs.length)
|
|
1110
|
+
return;
|
|
1111
|
+
if (txs.some(t => t.certificates !== undefined))
|
|
1112
|
+
return;
|
|
1113
|
+
this.certificatesUnreportedWarned = true;
|
|
1114
|
+
logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
|
|
1115
|
+
'(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
|
|
1116
|
+
'the crawl runs on Ogmios chain-sync or Koios');
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
|
|
1120
|
+
* own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
|
|
1121
|
+
* already carry an address are skipped.
|
|
1122
|
+
*/
|
|
1123
|
+
async resolveInputs(tx, txs, ledger) {
|
|
1124
|
+
// 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
|
|
528
1125
|
const blockOutputs = new Map();
|
|
529
1126
|
for (const t of txs) {
|
|
530
|
-
for (const o of t.outputs ?? [])
|
|
531
|
-
blockOutputs.set(`${t.hash}#${o.outputIndex}`,
|
|
532
|
-
}
|
|
1127
|
+
for (const o of t.outputs ?? [])
|
|
1128
|
+
blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
|
|
533
1129
|
}
|
|
534
1130
|
// 2. Collect inputs still needing resolution after the same-block pass
|
|
535
1131
|
const unresolved = [];
|
|
@@ -541,7 +1137,8 @@ class CardanoIndexer {
|
|
|
541
1137
|
const local = blockOutputs.get(key);
|
|
542
1138
|
if (local) {
|
|
543
1139
|
input.address = local.address;
|
|
544
|
-
input.amount = local.amount;
|
|
1140
|
+
input.amount = local.amount ?? [];
|
|
1141
|
+
copyUtxoData(input, local.dataHash, local.inlineDatum, local.referenceScriptHash);
|
|
545
1142
|
}
|
|
546
1143
|
else {
|
|
547
1144
|
unresolved.push({ input, key });
|
|
@@ -550,111 +1147,421 @@ class CardanoIndexer {
|
|
|
550
1147
|
}
|
|
551
1148
|
if (!unresolved.length)
|
|
552
1149
|
return;
|
|
553
|
-
// 3.
|
|
554
|
-
//
|
|
555
|
-
|
|
1150
|
+
// 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
|
|
1151
|
+
// reuses the same lookup instead of reading these outpoints a second time.
|
|
1152
|
+
if (ledger) {
|
|
1153
|
+
await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
|
|
1154
|
+
for (let i = unresolved.length - 1; i >= 0; i--) {
|
|
1155
|
+
const row = ledger.rows.get(unresolved[i].key);
|
|
1156
|
+
if (!row)
|
|
1157
|
+
continue;
|
|
1158
|
+
unresolved[i].input.address = row.address;
|
|
1159
|
+
unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
|
|
1160
|
+
copyUtxoData(unresolved[i].input, row.utxo_dataHash, row.utxo_inlineDatum, row.utxo_referenceScriptHash);
|
|
1161
|
+
unresolved.splice(i, 1);
|
|
1162
|
+
}
|
|
1163
|
+
if (!unresolved.length)
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
// 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
|
|
1167
|
+
// never exceeds a driver's bind-variable cap
|
|
556
1168
|
const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
|
|
557
|
-
const
|
|
1169
|
+
const hashBySeq = new Map();
|
|
1170
|
+
for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
|
|
1171
|
+
if (k.txSeq != null)
|
|
1172
|
+
hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
|
|
1173
|
+
}
|
|
1174
|
+
const outByKey = new Map();
|
|
558
1175
|
const amtByKey = new Map();
|
|
559
|
-
for (const
|
|
1176
|
+
for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
|
|
560
1177
|
const [outRows, assetRows] = await Promise.all([
|
|
561
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({
|
|
562
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({
|
|
1178
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
|
|
1179
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
|
|
563
1180
|
]);
|
|
564
1181
|
for (const r of outRows) {
|
|
565
|
-
|
|
1182
|
+
outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
|
|
566
1183
|
}
|
|
567
1184
|
for (const r of assetRows) {
|
|
568
|
-
const k = `${r.
|
|
1185
|
+
const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
|
|
569
1186
|
const list = amtByKey.get(k) ?? [];
|
|
570
1187
|
list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
|
|
571
1188
|
amtByKey.set(k, list);
|
|
572
1189
|
}
|
|
573
1190
|
}
|
|
574
1191
|
for (const { input, key } of unresolved) {
|
|
575
|
-
const
|
|
576
|
-
if (
|
|
577
|
-
input.address =
|
|
1192
|
+
const out = outByKey.get(key);
|
|
1193
|
+
if (out?.address_address != null)
|
|
1194
|
+
input.address = out.address_address;
|
|
1195
|
+
if (out)
|
|
1196
|
+
copyUtxoData(input, out.utxo_dataHash, out.utxo_inlineDatum, out.utxo_referenceScriptHash);
|
|
578
1197
|
const amt = amtByKey.get(key);
|
|
579
1198
|
if (amt)
|
|
580
1199
|
input.amount = amt;
|
|
581
1200
|
}
|
|
582
1201
|
}
|
|
583
1202
|
/**
|
|
584
|
-
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
|
|
1203
|
+
* Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
|
|
1204
|
+
* and the block total. The declared fee is kept when the mapper already set it via
|
|
1205
|
+
* `total_collateral` or a collateral input is not indexed locally (the sum would be short).
|
|
1206
|
+
*/
|
|
1207
|
+
applyCollateralFees(blockData, txs) {
|
|
1208
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
1209
|
+
let corrected = false;
|
|
1210
|
+
for (const t of txs) {
|
|
1211
|
+
// totalCollateral set = the mapper already put the charged amount in `fee`
|
|
1212
|
+
if (!t.spendsCollaterals || t.totalCollateral != null)
|
|
1213
|
+
continue;
|
|
1214
|
+
const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
|
|
1215
|
+
if (!collateral.length)
|
|
1216
|
+
continue; // nothing to derive from — leave the declared fee
|
|
1217
|
+
const unresolved = collateral.find(i => !i.address);
|
|
1218
|
+
if (unresolved) {
|
|
1219
|
+
logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
1220
|
+
`— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
|
|
1224
|
+
const returned = (t.outputs ?? [])
|
|
1225
|
+
.filter(o => o.isCollateral)
|
|
1226
|
+
.reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
|
|
1227
|
+
const charged = consumed - returned;
|
|
1228
|
+
if (charged < 0n) {
|
|
1229
|
+
logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
|
|
1230
|
+
`— keeping the declared fee ${t.fee}`);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
t.fee = charged.toString();
|
|
1234
|
+
corrected = true;
|
|
1235
|
+
}
|
|
1236
|
+
if (corrected) {
|
|
1237
|
+
blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* Mint/burn rows for a block from data in hand: the ledger's mint field when the source
|
|
1242
|
+
* reports it (Ogmios, Koios), else Σ outputs − Σ inputs per unit, excluding reference and
|
|
1243
|
+
* collateral inputs. A tx with an unresolvable consumed input is skipped and logged.
|
|
588
1244
|
*/
|
|
1245
|
+
buildAssetHistoryRows(blockData, txs) {
|
|
1246
|
+
const entries = [];
|
|
1247
|
+
let skipped = 0;
|
|
1248
|
+
for (const t of txs) {
|
|
1249
|
+
let net;
|
|
1250
|
+
if (t.mint) {
|
|
1251
|
+
// A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
|
|
1252
|
+
net = new Map();
|
|
1253
|
+
for (const m of t.mint) {
|
|
1254
|
+
if (m.unit === 'lovelace')
|
|
1255
|
+
continue;
|
|
1256
|
+
net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
else {
|
|
1260
|
+
if (t.spendsCollaterals)
|
|
1261
|
+
continue; // no mint is applied when the script phase failed
|
|
1262
|
+
const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
|
|
1263
|
+
const unresolved = consumed.find(i => !i.address);
|
|
1264
|
+
if (unresolved) {
|
|
1265
|
+
logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
1266
|
+
`— skipping, mint/burn of this transaction is not recorded`);
|
|
1267
|
+
skipped++;
|
|
1268
|
+
continue;
|
|
1269
|
+
}
|
|
1270
|
+
net = new Map();
|
|
1271
|
+
const add = (amount, sign) => {
|
|
1272
|
+
for (const a of amount ?? []) {
|
|
1273
|
+
if (a.unit === 'lovelace')
|
|
1274
|
+
continue;
|
|
1275
|
+
net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
|
|
1279
|
+
add(o.amount, 1n);
|
|
1280
|
+
for (const i of consumed)
|
|
1281
|
+
add(i.amount, -1n);
|
|
1282
|
+
}
|
|
1283
|
+
for (const [unit, quantity] of net) {
|
|
1284
|
+
if (quantity === 0n)
|
|
1285
|
+
continue;
|
|
1286
|
+
entries.push({
|
|
1287
|
+
unit,
|
|
1288
|
+
txHash: t.hash,
|
|
1289
|
+
action: quantity > 0n ? 'mint' : 'burn',
|
|
1290
|
+
quantity: (quantity < 0n ? -quantity : quantity).toString(),
|
|
1291
|
+
blockTime: blockData.time ?? null,
|
|
1292
|
+
blockHeight: blockData.height ?? null,
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
if (skipped) {
|
|
1297
|
+
logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
|
|
1298
|
+
}
|
|
1299
|
+
return (0, mappers_1.mapAssetHistory)(entries);
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Keep the `Assets` catalogue complete for every unit the crawl meets, without provider calls.
|
|
1303
|
+
* `Assets` is temporal, key `(validFrom, unit)`: the bare row's fixed epoch-zero stamp never
|
|
1304
|
+
* aliases an enriched slice, so the UPSERT is safe inside the block transaction. The existence
|
|
1305
|
+
* check uses the DB-level entity: the service projection's temporal filter hides such rows.
|
|
1306
|
+
*/
|
|
1307
|
+
async ensureAssetRows(tx, units) {
|
|
1308
|
+
if (this.crawlAssetCatalogue === 'off' || !units.size)
|
|
1309
|
+
return 0;
|
|
1310
|
+
const unknown = [...units].filter(u => !this.assetMemo.has(u));
|
|
1311
|
+
if (!unknown.length)
|
|
1312
|
+
return 0;
|
|
1313
|
+
const missing = [];
|
|
1314
|
+
for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
|
|
1315
|
+
const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
|
|
1316
|
+
const known = new Set(rows.map(r => r.unit));
|
|
1317
|
+
for (const unit of unitChunk) {
|
|
1318
|
+
if (known.has(unit))
|
|
1319
|
+
this.noteAssetSeen(unit);
|
|
1320
|
+
else
|
|
1321
|
+
missing.push(unit);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
if (!missing.length)
|
|
1325
|
+
return 0;
|
|
1326
|
+
const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
|
|
1327
|
+
// Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
|
|
1328
|
+
for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
|
|
1329
|
+
await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
|
|
1330
|
+
}
|
|
1331
|
+
// Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
|
|
1332
|
+
// the commit: a rolled-back block must write its bare rows again.
|
|
1333
|
+
this.pendingCommit.push(() => { for (const unit of missing)
|
|
1334
|
+
this.noteAssetSeen(unit); });
|
|
1335
|
+
if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
|
|
1336
|
+
for (const row of rows) {
|
|
1337
|
+
if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
|
|
1338
|
+
this.enrichQueue.shift();
|
|
1339
|
+
this.enrichQueue.push(row.unit);
|
|
1340
|
+
}
|
|
1341
|
+
this.startAssetEnrichment();
|
|
1342
|
+
}
|
|
1343
|
+
return rows.length;
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Remember a unit as present in the catalogue. Insertion-ordered eviction keeps a long
|
|
1347
|
+
* backfill's memory flat; losing an entry costs one SELECT, never a wrong write.
|
|
1348
|
+
*/
|
|
1349
|
+
noteAssetSeen(unit) {
|
|
1350
|
+
if (this.assetMemo.has(unit))
|
|
1351
|
+
return;
|
|
1352
|
+
if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
|
|
1353
|
+
const oldest = this.assetMemo.values().next();
|
|
1354
|
+
if (!oldest.done)
|
|
1355
|
+
this.assetMemo.delete(oldest.value);
|
|
1356
|
+
}
|
|
1357
|
+
this.assetMemo.add(unit);
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit), plus
|
|
1361
|
+
* one EpochLedgerSnapshots row that marks the epoch as observed. With a block hash and an Ogmios
|
|
1362
|
+
* backend the node's ledger state AT that block is read; otherwise Koios reports current state
|
|
1363
|
+
* (and the live `Pools` / `Dreps` rows are refreshed). Neither available: no-op.
|
|
1364
|
+
* @returns counts written and the source used (null = skipped)
|
|
1365
|
+
*/
|
|
1366
|
+
async snapshotEpoch(epoch, at) {
|
|
1367
|
+
const epochState = at.hash ? this.client.getEpochStateBackend() : null;
|
|
1368
|
+
if (epochState && at.hash)
|
|
1369
|
+
return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash });
|
|
1370
|
+
const backend = this.client.getEnumeratingBackend();
|
|
1371
|
+
if (!backend) {
|
|
1372
|
+
logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
|
|
1373
|
+
return { pools: 0, dreps: 0, source: null };
|
|
1374
|
+
}
|
|
1375
|
+
// Network first, DB second — the provider round-trips must not run with a write lock held.
|
|
1376
|
+
const [poolData, drepData] = await Promise.all([
|
|
1377
|
+
backend.getPoolIds().then(ids => backend.getPools(ids)),
|
|
1378
|
+
backend.getDrepIds().then(ids => backend.getDreps(ids)),
|
|
1379
|
+
]);
|
|
1380
|
+
const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
|
|
1381
|
+
const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
|
|
1382
|
+
const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
|
|
1383
|
+
const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
|
|
1384
|
+
const ledgerRow = {
|
|
1385
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: null, source: 'koios',
|
|
1386
|
+
liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1387
|
+
poolCount: poolData.length, drepCount: drepData.length,
|
|
1388
|
+
};
|
|
1389
|
+
await cds_1.default.tx(async (tx) => {
|
|
1390
|
+
// Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
|
|
1391
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1392
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1393
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1394
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1395
|
+
for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
|
|
1396
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
|
|
1397
|
+
for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
|
|
1398
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
|
|
1399
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1400
|
+
});
|
|
1401
|
+
logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1402
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Epoch snapshot from the node's ledger state at block `at`. The live `Pools` / `Dreps` rows are
|
|
1406
|
+
* NOT refreshed: the acquired state may be hours old. `blocksMinted` counts crawled blocks up to
|
|
1407
|
+
* `at`, only when the crawl covers the chain since Shelley.
|
|
1408
|
+
*/
|
|
1409
|
+
async snapshotEpochFromLedger(backend, epoch, at) {
|
|
1410
|
+
const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
|
|
1411
|
+
if (state.epoch !== epoch) {
|
|
1412
|
+
logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch} — stored as ${epoch}`);
|
|
1413
|
+
}
|
|
1414
|
+
const minted = await this.crawledBlocksByPool(at.slot);
|
|
1415
|
+
const previous = await this.previousLiveStake(epoch);
|
|
1416
|
+
const activeTotal = previous ? [...previous.values()].reduce((a, b) => a + b, 0n) : 0n;
|
|
1417
|
+
const origin = { source: 'ogmios', hash: at.hash };
|
|
1418
|
+
const poolSnapshots = state.pools.map(p => {
|
|
1419
|
+
const active = previous?.get(p.poolId);
|
|
1420
|
+
return {
|
|
1421
|
+
...(0, mappers_1.mapPoolSnapshot)(p, epoch, at, origin),
|
|
1422
|
+
blocksMinted: minted ? (minted.get(p.poolId) ?? 0) : null,
|
|
1423
|
+
activeStake: active == null ? null : active.toString(),
|
|
1424
|
+
activeSize: active == null || activeTotal === 0n ? null : Number((active * 1000000n) / activeTotal) / 1_000_000,
|
|
1425
|
+
};
|
|
1426
|
+
});
|
|
1427
|
+
const drepSnapshots = state.dreps.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at, origin));
|
|
1428
|
+
const reserves = state.reserves == null ? null : BigInt(state.reserves);
|
|
1429
|
+
const ledgerRow = {
|
|
1430
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: at.hash, source: 'ogmios',
|
|
1431
|
+
treasury: state.treasury,
|
|
1432
|
+
reserves: state.reserves,
|
|
1433
|
+
totalSupply: reserves == null ? null : (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves).toString(),
|
|
1434
|
+
liveStake: state.pools.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1435
|
+
activeStake: previous ? activeTotal.toString() : null,
|
|
1436
|
+
poolCount: state.pools.length,
|
|
1437
|
+
drepCount: state.dreps.length,
|
|
1438
|
+
drepAbstainStake: state.drepAbstainStake,
|
|
1439
|
+
drepNoConfidenceStake: state.drepNoConfidenceStake,
|
|
1440
|
+
};
|
|
1441
|
+
await cds_1.default.tx(async (tx) => {
|
|
1442
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1443
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1444
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1445
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1446
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1447
|
+
});
|
|
1448
|
+
logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1449
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Active stake of epoch E = the stake distribution taken at the E-1 boundary, which is the live
|
|
1453
|
+
* stake the Ogmios snapshot of E-1 recorded at its first block. null without that snapshot.
|
|
1454
|
+
*/
|
|
1455
|
+
async previousLiveStake(epoch) {
|
|
1456
|
+
const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
|
|
1457
|
+
if (!rows?.length)
|
|
1458
|
+
return null;
|
|
1459
|
+
return new Map(rows.map(r => [r.poolId, BigInt(lovelaceSum(r.liveStake))]));
|
|
1460
|
+
}
|
|
1461
|
+
/** Crawled blocks per pool up to `slot`; null unless the crawl started at or before Shelley. */
|
|
1462
|
+
async crawledBlocksByPool(slot) {
|
|
1463
|
+
const db = cds_1.default.db;
|
|
1464
|
+
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
1465
|
+
const shelley = const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot;
|
|
1466
|
+
if (cursor?.startSlot == null || cursor.startSlot > shelley)
|
|
1467
|
+
return null;
|
|
1468
|
+
const rows = await db.run(SELECT.from(CardanoODataService_1.Blocks).columns('slotLeader', 'count(*) as n').where({ slot: { '<=': slot } }).groupBy('slotLeader'));
|
|
1469
|
+
const out = new Map();
|
|
1470
|
+
for (const r of rows ?? [])
|
|
1471
|
+
if (r.slotLeader)
|
|
1472
|
+
out.set(r.slotLeader, Number(r.n));
|
|
1473
|
+
return out;
|
|
1474
|
+
}
|
|
1475
|
+
/** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
|
|
1476
|
+
collectBlockUnits(txs, assetHistoryRows) {
|
|
1477
|
+
const units = new Set();
|
|
1478
|
+
for (const t of txs) {
|
|
1479
|
+
for (const o of t.outputs ?? []) {
|
|
1480
|
+
for (const a of o.amount ?? [])
|
|
1481
|
+
if (a.unit !== 'lovelace')
|
|
1482
|
+
units.add(a.unit);
|
|
1483
|
+
}
|
|
1484
|
+
for (const i of t.inputs ?? []) {
|
|
1485
|
+
for (const a of i.amount ?? [])
|
|
1486
|
+
if (a.unit !== 'lovelace')
|
|
1487
|
+
units.add(a.unit);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
for (const row of assetHistoryRows)
|
|
1491
|
+
if (row.unit)
|
|
1492
|
+
units.add(row.unit);
|
|
1493
|
+
return units;
|
|
1494
|
+
}
|
|
1495
|
+
/** Index an epoch by number. */
|
|
589
1496
|
async indexEpoch(tx, epochNumber) {
|
|
590
1497
|
const epochInfo = await this.client.getEpoch(epochNumber);
|
|
591
1498
|
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
592
1499
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
593
1500
|
return epochEntity;
|
|
594
1501
|
}
|
|
595
|
-
/**
|
|
596
|
-
* Index & return the account information data
|
|
597
|
-
* @param tx CAP transaction object
|
|
598
|
-
* @param stakeAddress stake address (bech32)
|
|
599
|
-
* @returns {Promise<Account>} account entity data
|
|
600
|
-
*/
|
|
1502
|
+
/** Index an account by stake address, plus its addresses when it has any. */
|
|
601
1503
|
async indexAccount(tx, stakeAddress) {
|
|
602
|
-
const accountInfo = await this.
|
|
1504
|
+
const accountInfo = await this.resolveAccount(tx, stakeAddress);
|
|
603
1505
|
const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
|
|
604
1506
|
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
605
|
-
const addresses = accountInfo.addresses.map(a => a.address);
|
|
606
1507
|
if (accountEntity.hasAddresses) {
|
|
607
|
-
await this._ensureAddresses(tx, addresses);
|
|
1508
|
+
await this._ensureAddresses(tx, accountInfo.addresses);
|
|
608
1509
|
}
|
|
609
1510
|
return accountEntity;
|
|
610
1511
|
}
|
|
611
|
-
/**
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1512
|
+
/** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
|
|
1513
|
+
async resolveAccount(tx, stakeAddress) {
|
|
1514
|
+
const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
|
|
1515
|
+
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
|
|
1516
|
+
// the addresses come from the set too (the node has no stake-key -> address index)
|
|
1517
|
+
if ((await this.localCoverage(tx))?.ledger) {
|
|
1518
|
+
const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
|
|
1519
|
+
accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
|
|
1520
|
+
accountInfo.addresses = await this.localAccountAddresses(tx, stakeAddress);
|
|
1521
|
+
}
|
|
1522
|
+
if (accountInfo.withdrawalsSum === '0') {
|
|
1523
|
+
const local = await this.localWithdrawalsSum(tx, stakeAddress);
|
|
1524
|
+
if (local != null)
|
|
1525
|
+
accountInfo.withdrawalsSum = local;
|
|
1526
|
+
}
|
|
1527
|
+
return accountInfo;
|
|
1528
|
+
}
|
|
1529
|
+
/** Index a DRep by bech32 id. */
|
|
617
1530
|
async indexDrep(tx, drepId) {
|
|
618
1531
|
const drepInfo = await this.client.getDrep(drepId);
|
|
619
1532
|
const drepEntity = (0, mappers_1.mapDrep)(drepInfo, this.client.max_age_ms);
|
|
620
1533
|
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
|
|
621
1534
|
return drepEntity;
|
|
622
1535
|
}
|
|
623
|
-
/**
|
|
624
|
-
* Index & return the pool information data
|
|
625
|
-
* @param tx CAP transaction object
|
|
626
|
-
* @param poolId pool id (hex)
|
|
627
|
-
* @returns {Promise<Pool>} pool entity data
|
|
628
|
-
*/
|
|
1536
|
+
/** Index a pool by id. */
|
|
629
1537
|
async indexPool(tx, poolId) {
|
|
630
|
-
const
|
|
631
|
-
const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
|
|
1538
|
+
const poolEntity = (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
|
|
632
1539
|
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
633
1540
|
return poolEntity;
|
|
634
1541
|
}
|
|
635
|
-
/**
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1542
|
+
/** Pool from the backend with crawled block counts and the snapshot's active stake. */
|
|
1543
|
+
async resolvePool(tx, poolId) {
|
|
1544
|
+
const poolInfo = { ...(await this.client.getPool(poolId)), ...(await this.localPoolBlocks(tx, poolId)) };
|
|
1545
|
+
// The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
|
|
1546
|
+
if (poolInfo.activeStake === '0')
|
|
1547
|
+
Object.assign(poolInfo, await this.snapshotActiveStake(tx, poolId));
|
|
1548
|
+
return poolInfo;
|
|
1549
|
+
}
|
|
1550
|
+
/** Index an asset by unit (policyId + assetNameHex). */
|
|
641
1551
|
async indexAsset(tx, unit) {
|
|
642
|
-
const assetInfo = await this.
|
|
1552
|
+
const assetInfo = await this.resolveAssetInfo(tx, unit);
|
|
643
1553
|
const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
|
|
644
1554
|
await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
|
|
645
1555
|
return assetEntity;
|
|
646
1556
|
}
|
|
647
1557
|
/**
|
|
648
|
-
* Index
|
|
649
|
-
*
|
|
650
|
-
* UPSERTs entries by (unit, txHash) — events are immutable, so re-fetching
|
|
651
|
-
* just refreshes the cap of recent entries; older cached entries persist.
|
|
652
|
-
* @param tx CAP transaction object
|
|
653
|
-
* @param unit asset unit (policyId + assetNameHex)
|
|
654
|
-
* @param limit max number of recent events to fetch (default 100)
|
|
655
|
-
* @returns {Promise<AssetHistory[]>} list of mint/burn event entity rows
|
|
1558
|
+
* Index mint/burn history for an asset, always fresh. Rows are keyed (unit, txHash), so a
|
|
1559
|
+
* refetch refreshes the recent cap and older cached entries persist.
|
|
656
1560
|
*/
|
|
657
1561
|
async indexAssetHistory(tx, unit, limit = 100) {
|
|
1562
|
+
if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
|
|
1563
|
+
return await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
|
|
1564
|
+
}
|
|
658
1565
|
const events = await this.client.getAssetHistory(unit, limit);
|
|
659
1566
|
if (events.length === 0)
|
|
660
1567
|
return [];
|
|
@@ -662,14 +1569,7 @@ class CardanoIndexer {
|
|
|
662
1569
|
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
|
|
663
1570
|
return rows;
|
|
664
1571
|
}
|
|
665
|
-
/**
|
|
666
|
-
* Common method: build a transaction, persist build result with inputs/outputs/address associations.
|
|
667
|
-
* All four public indexBuild*Result methods delegate to this to eliminate duplication.
|
|
668
|
-
* @param tx CAP transaction object
|
|
669
|
-
* @param buildreq transaction build request data
|
|
670
|
-
* @param buildFn the specific builder method to call
|
|
671
|
-
* @returns {Promise<TransactionBuild>} transaction build entity data
|
|
672
|
-
*/
|
|
1572
|
+
/** Build a transaction and persist the build result with inputs/outputs/address association. */
|
|
673
1573
|
async _indexBuildResult(tx, buildreq, buildFn) {
|
|
674
1574
|
const protocolParams = await this.indexProtocolParameters(tx);
|
|
675
1575
|
const txbuildResult = await buildFn(buildreq, protocolParams);
|
|
@@ -683,6 +1583,10 @@ class CardanoIndexer {
|
|
|
683
1583
|
const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
|
|
684
1584
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
|
|
685
1585
|
}
|
|
1586
|
+
if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
|
|
1587
|
+
const buildId = buildResult.id;
|
|
1588
|
+
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildRedeemers).entries(txbuildResult.redeemers.map(r => ({ build_id: buildId, tag: r.tag, redeemerIndex: r.index, mem: Number(r.mem), steps: Number(r.steps) }))));
|
|
1589
|
+
}
|
|
686
1590
|
if (buildResult.id && buildreq.senderAddress) {
|
|
687
1591
|
await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
|
|
688
1592
|
}
|
|
@@ -703,52 +1607,40 @@ class CardanoIndexer {
|
|
|
703
1607
|
async indexPlutusSpendBuildResult(tx, buildreq) {
|
|
704
1608
|
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
|
|
705
1609
|
}
|
|
706
|
-
/**
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
1610
|
+
/** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
|
|
1611
|
+
async indexPlutusBuildResult(tx, buildreq) {
|
|
1612
|
+
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
|
|
1613
|
+
}
|
|
1614
|
+
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
711
1615
|
async indexProtocolParameters(tx) {
|
|
712
1616
|
const network = this.client.network;
|
|
713
1617
|
const now = Date.now();
|
|
714
|
-
|
|
715
|
-
const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes — matches client cache TTL
|
|
1618
|
+
const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // matches the client cache TTL
|
|
716
1619
|
if (now - this.lastParamsFetchTime < PROTOCOL_PARAMS_TTL_MS) {
|
|
717
|
-
// (network, epoch) is the
|
|
718
|
-
// order by epoch desc to return the LATEST instead of an arbitrary row.
|
|
1620
|
+
// (network, epoch) is the key; order by epoch desc to get the latest row
|
|
719
1621
|
const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
|
|
720
1622
|
if (existing)
|
|
721
1623
|
return existing;
|
|
722
1624
|
}
|
|
723
|
-
// Fetch from provider (client has 5-min in-memory TTL cache, so this is cheap)
|
|
724
1625
|
const protocolParamsInfo = await this.client.getProtocolParameters();
|
|
725
1626
|
const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
|
|
726
1627
|
await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
|
|
727
1628
|
this.lastParamsFetchTime = now;
|
|
728
1629
|
return protocolParams;
|
|
729
1630
|
}
|
|
730
|
-
/**
|
|
731
|
-
* Persist a transaction submission with optional build association
|
|
732
|
-
* Handles: TransactionSubmission insert, optional Build status update
|
|
733
|
-
* @param tx CAP transaction object
|
|
734
|
-
* @param params submission parameters
|
|
735
|
-
* @returns {Promise<TransactionSubmission>} persisted transaction submission entity
|
|
736
|
-
*/
|
|
1631
|
+
/** Persist a transaction submission and flag the build as submitted when linked. */
|
|
737
1632
|
async persistTransactionSubmission(tx, params) {
|
|
738
1633
|
const { signedTxCbor, txHash, buildId } = params;
|
|
739
|
-
// Map submission data
|
|
740
1634
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
|
|
741
|
-
//
|
|
1635
|
+
// status 'pending' until the second phase of the submit flow confirms
|
|
742
1636
|
const submissionRecord = {
|
|
743
1637
|
...indexSubmission,
|
|
744
1638
|
build_id: buildId || null,
|
|
745
1639
|
backendResponse: 'Submitted successfully',
|
|
746
1640
|
status: 'pending',
|
|
747
1641
|
};
|
|
748
|
-
// Persist submission
|
|
749
1642
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
750
1643
|
logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
|
|
751
|
-
// Update build status if buildId provided
|
|
752
1644
|
if (buildId) {
|
|
753
1645
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
754
1646
|
.set({ wasSubmitted: true })
|
|
@@ -757,14 +1649,7 @@ class CardanoIndexer {
|
|
|
757
1649
|
}
|
|
758
1650
|
return submissionRecord;
|
|
759
1651
|
}
|
|
760
|
-
/**
|
|
761
|
-
* Update the status of a transaction submission
|
|
762
|
-
* Used for the two-phase submit flow: pending → submitted (or failed)
|
|
763
|
-
* @param tx CAP transaction object
|
|
764
|
-
* @param submissionId the submission to update
|
|
765
|
-
* @param status new status value
|
|
766
|
-
* @param errorMessage optional error message for failed status
|
|
767
|
-
*/
|
|
1652
|
+
/** Update a submission's status (two-phase submit: pending → submitted or failed). */
|
|
768
1653
|
async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
|
|
769
1654
|
const updateData = { status };
|
|
770
1655
|
if (errorMessage) {
|
|
@@ -775,15 +1660,9 @@ class CardanoIndexer {
|
|
|
775
1660
|
.where({ id: submissionId }));
|
|
776
1661
|
logger.debug({ submissionId, status }, 'Updated submission status');
|
|
777
1662
|
}
|
|
778
|
-
/**
|
|
779
|
-
* Persist a new signing request
|
|
780
|
-
* @param tx CAP transaction object
|
|
781
|
-
* @param params signing request parameters from external signer module
|
|
782
|
-
* @returns persisted signing request record
|
|
783
|
-
*/
|
|
1663
|
+
/** Persist a new signing request and link it to the build's sender address. */
|
|
784
1664
|
async persistSigningRequest(tx, params) {
|
|
785
1665
|
const { buildId, signingPayload } = params;
|
|
786
|
-
// Create signing request record
|
|
787
1666
|
const signingRequestRecord = {
|
|
788
1667
|
id: signingPayload.signingRequestId,
|
|
789
1668
|
build_id: buildId,
|
|
@@ -796,26 +1675,17 @@ class CardanoIndexer {
|
|
|
796
1675
|
cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
|
|
797
1676
|
cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
|
|
798
1677
|
};
|
|
799
|
-
// Persist to database
|
|
800
1678
|
await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
|
|
801
1679
|
logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
|
|
802
|
-
// Index address-signing request association
|
|
803
1680
|
const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
|
|
804
1681
|
if (build?.senderAddress) {
|
|
805
1682
|
await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
|
|
806
1683
|
}
|
|
807
1684
|
return signingRequestRecord;
|
|
808
1685
|
}
|
|
809
|
-
/**
|
|
810
|
-
* Persist a signature verification with signing request status update
|
|
811
|
-
* Handles: SignatureVerification insert, SigningRequest status update
|
|
812
|
-
* @param tx CAP transaction object
|
|
813
|
-
* @param params verification parameters
|
|
814
|
-
* @returns persisted signature verification record
|
|
815
|
-
*/
|
|
1686
|
+
/** Persist a signature verification and update the signing request status. */
|
|
816
1687
|
async persistSignatureVerification(tx, params) {
|
|
817
1688
|
const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
|
|
818
|
-
// Create verification record
|
|
819
1689
|
const verificationRecord = {
|
|
820
1690
|
id: cds_1.default.utils.uuid(),
|
|
821
1691
|
signingRequest_id: signingRequestId,
|
|
@@ -828,10 +1698,8 @@ class CardanoIndexer {
|
|
|
828
1698
|
warnings: JSON.stringify(verificationResult.warnings),
|
|
829
1699
|
verifiedAt: new Date().toISOString(),
|
|
830
1700
|
};
|
|
831
|
-
// Persist verification
|
|
832
1701
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
833
1702
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
834
|
-
// Update signing request status
|
|
835
1703
|
const newStatus = verificationResult.isValid ? 'verified' : 'failed';
|
|
836
1704
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
837
1705
|
.set({
|
|
@@ -845,16 +1713,9 @@ class CardanoIndexer {
|
|
|
845
1713
|
logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
|
|
846
1714
|
return verificationRecord;
|
|
847
1715
|
}
|
|
848
|
-
/**
|
|
849
|
-
* Index a verified transaction submission with all related records
|
|
850
|
-
* Handles persistence of: SignatureVerification, TransactionSubmission, SigningRequest update, Build update
|
|
851
|
-
* @param tx CAP transaction object
|
|
852
|
-
* @param params submission parameters
|
|
853
|
-
* @returns {Promise<TransactionSubmission>} transaction submission entity data
|
|
854
|
-
*/
|
|
1716
|
+
/** Persist a verified submission: verification, submission, signing request and build updates. */
|
|
855
1717
|
async indexVerifiedTransactionSubmission(tx, params) {
|
|
856
1718
|
const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
|
|
857
|
-
// Step 1: Create and persist verification record
|
|
858
1719
|
const verificationRecord = {
|
|
859
1720
|
id: cds_1.default.utils.uuid(),
|
|
860
1721
|
signingRequest_id: signingRequestId,
|
|
@@ -869,7 +1730,6 @@ class CardanoIndexer {
|
|
|
869
1730
|
};
|
|
870
1731
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
871
1732
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
872
|
-
// Step 2: Create and persist submission record
|
|
873
1733
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
|
|
874
1734
|
const submissionRecord = {
|
|
875
1735
|
...indexSubmission,
|
|
@@ -879,7 +1739,6 @@ class CardanoIndexer {
|
|
|
879
1739
|
};
|
|
880
1740
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
881
1741
|
logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
|
|
882
|
-
// Step 3: Update signing request metadata and status
|
|
883
1742
|
const now = new Date().toISOString();
|
|
884
1743
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
885
1744
|
.set({
|
|
@@ -892,29 +1751,20 @@ class CardanoIndexer {
|
|
|
892
1751
|
})
|
|
893
1752
|
.where({ id: signingRequestId }));
|
|
894
1753
|
logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
|
|
895
|
-
// Step 4: Update build status
|
|
896
1754
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
897
1755
|
.set({ wasSubmitted: true })
|
|
898
1756
|
.where({ id: buildId }));
|
|
899
1757
|
logger.debug({ buildId }, 'Updated build wasSubmitted flag');
|
|
900
1758
|
return submissionRecord;
|
|
901
1759
|
}
|
|
902
|
-
/**
|
|
903
|
-
* Index & return the latest epoch information data
|
|
904
|
-
* @param tx CAP transaction object
|
|
905
|
-
* @returns {Promise<Epoch>} epoch entity data
|
|
906
|
-
*/
|
|
1760
|
+
/** Index the latest epoch. */
|
|
907
1761
|
async indexLatestEpoch(tx) {
|
|
908
1762
|
const epochInfo = await this.client.getLatestEpoch();
|
|
909
1763
|
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
910
1764
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
911
1765
|
return epochEntity;
|
|
912
1766
|
}
|
|
913
|
-
/**
|
|
914
|
-
* Index & return the latest block information data
|
|
915
|
-
* @param tx CAP transaction object
|
|
916
|
-
* @returns {Promise<Block>} block entity data
|
|
917
|
-
*/
|
|
1767
|
+
/** Index the latest block, with best-effort epoch enrichment. */
|
|
918
1768
|
async indexLatestBlock(tx) {
|
|
919
1769
|
const blockInfo = await this.client.getLatestBlock();
|
|
920
1770
|
let epoch;
|
|
@@ -925,6 +1775,12 @@ class CardanoIndexer {
|
|
|
925
1775
|
// Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
|
|
926
1776
|
}
|
|
927
1777
|
const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
|
|
1778
|
+
// A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
|
|
1779
|
+
// crawled row of the same hash, or outlive the block when the tip is rolled back.
|
|
1780
|
+
if (blockInfo.headerOnly) {
|
|
1781
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: blockInfo.hash }));
|
|
1782
|
+
return stored ?? blockEntity;
|
|
1783
|
+
}
|
|
928
1784
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
|
|
929
1785
|
return blockEntity;
|
|
930
1786
|
}
|
|
@@ -933,54 +1789,75 @@ class CardanoIndexer {
|
|
|
933
1789
|
//-----------------------------------------------------------------------------
|
|
934
1790
|
/** Max addresses to index concurrently (avoid overloading backends) */
|
|
935
1791
|
static ADDR_CONCURRENCY = 5;
|
|
1792
|
+
/** Block position of a transaction already in the local index (crawled or cached), or null. */
|
|
1793
|
+
async findIndexedTransaction(tx, txHash) {
|
|
1794
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash').where({ hash: txHash }));
|
|
1795
|
+
return row ?? null;
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Blocks on top of a transaction, its own block included; 0 while it is not on chain.
|
|
1799
|
+
* A stored row counts only when its block lies in the crawled chain, because the crawler
|
|
1800
|
+
* removes those rows on a rollback. Otherwise height and tip come from the backends.
|
|
1801
|
+
*/
|
|
1802
|
+
async resolveTransactionConfirmations(tx, txHash) {
|
|
1803
|
+
const crawled = await this.crawledTransactionDepth(tx, txHash);
|
|
1804
|
+
if (crawled)
|
|
1805
|
+
return { txHash, ...crawled, confirmations: crawled.tipHeight - crawled.blockHeight + 1 };
|
|
1806
|
+
let blockHeight;
|
|
1807
|
+
try {
|
|
1808
|
+
const indexed = await this.indexTransaction(tx, txHash);
|
|
1809
|
+
blockHeight = indexed.blockHeight == null ? null : Number(indexed.blockHeight);
|
|
1810
|
+
}
|
|
1811
|
+
catch (err) {
|
|
1812
|
+
if (!(0, errors_1.isNotFoundOnAllBackends)(err))
|
|
1813
|
+
throw err;
|
|
1814
|
+
blockHeight = null;
|
|
1815
|
+
}
|
|
1816
|
+
if (blockHeight == null)
|
|
1817
|
+
return { txHash, blockHeight: null, tipHeight: null, confirmations: 0 };
|
|
1818
|
+
const tip = await this.client.getLatestBlock();
|
|
1819
|
+
if (tip.height == null)
|
|
1820
|
+
throw new errors_1.ProviderUnavailableError('Chain tip height unknown');
|
|
1821
|
+
// a tip from a backend that lags the one that found the tx counts the tx block only
|
|
1822
|
+
const tipHeight = Math.max(tip.height, blockHeight);
|
|
1823
|
+
return { txHash, blockHeight, tipHeight, confirmations: tipHeight - blockHeight + 1 };
|
|
1824
|
+
}
|
|
1825
|
+
/** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
|
|
1826
|
+
async crawledTransactionDepth(tx, txHash) {
|
|
1827
|
+
const coverage = await this.localCoverage(tx);
|
|
1828
|
+
if (coverage?.tipHeight == null)
|
|
1829
|
+
return null;
|
|
1830
|
+
const stored = await this.findIndexedTransaction(tx, txHash);
|
|
1831
|
+
if (stored?.blockHeight == null || stored.slot == null || !stored.blockHash)
|
|
1832
|
+
return null;
|
|
1833
|
+
const slot = Number(stored.slot);
|
|
1834
|
+
if (slot < coverage.fromSlot || slot > coverage.lastSlot)
|
|
1835
|
+
return null;
|
|
1836
|
+
const block = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('hash').where({ hash: stored.blockHash }));
|
|
1837
|
+
if (!block)
|
|
1838
|
+
return null;
|
|
1839
|
+
const blockHeight = Number(stored.blockHeight);
|
|
1840
|
+
return { blockHeight, tipHeight: Math.max(coverage.tipHeight, blockHeight) };
|
|
1841
|
+
}
|
|
936
1842
|
/**
|
|
937
|
-
* Ensure a set of transactions
|
|
938
|
-
*
|
|
939
|
-
* 2. Check which hashes already exist in DB
|
|
940
|
-
* 3. Batch-fetch missing transactions from backend
|
|
941
|
-
* 4. UPSERT all entities (Transactions, Inputs, Outputs, Assets, Metadata)
|
|
942
|
-
*
|
|
943
|
-
* @param tx CAP transaction (cds.tx)
|
|
944
|
-
* @param txHashes array of transaction hashes to ensure
|
|
945
|
-
* @returns Map of txHash → provider Transaction (all requested, from DB fetch or backend)
|
|
1843
|
+
* Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
|
|
1844
|
+
* @returns provider transactions for the hashes that had to be fetched
|
|
946
1845
|
*/
|
|
947
1846
|
async ensureTransactionsIndexed(tx, txHashes) {
|
|
948
1847
|
const unique = [...new Set(txHashes)];
|
|
949
1848
|
if (unique.length === 0)
|
|
950
1849
|
return new Map();
|
|
951
|
-
// DB check — which hashes are already indexed?
|
|
952
1850
|
const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
|
|
953
1851
|
const existingSet = new Set(existingRows.map((r) => r.hash));
|
|
954
1852
|
const missing = unique.filter(h => !existingSet.has(h));
|
|
955
1853
|
logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
|
|
956
|
-
// Batch-fetch missing from backend
|
|
957
1854
|
let fetched = new Map();
|
|
958
1855
|
if (missing.length > 0) {
|
|
959
1856
|
fetched = await this.client.getTransactionsBatch(missing);
|
|
960
|
-
// UPSERT all fetched transactions + child entities
|
|
961
1857
|
for (const [, providerTx] of fetched) {
|
|
962
1858
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
963
1859
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
964
|
-
|
|
965
|
-
const inputRows = (0, mappers_1.mapTransactionInputs)(providerTx.hash, providerTx.inputs);
|
|
966
|
-
const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(providerTx.hash, providerTx.inputs);
|
|
967
|
-
if (inputRows.length)
|
|
968
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
969
|
-
if (inputAssetRows.length)
|
|
970
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
|
|
971
|
-
}
|
|
972
|
-
// outputs independent of inputs (see indexTransaction)
|
|
973
|
-
if (providerTx.outputs) {
|
|
974
|
-
const outputRows = (0, mappers_1.mapTransactionOutputs)(providerTx.hash, providerTx.outputs);
|
|
975
|
-
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(providerTx.hash, providerTx.outputs);
|
|
976
|
-
if (outputRows.length)
|
|
977
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
978
|
-
if (outputAssetRows.length)
|
|
979
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
980
|
-
}
|
|
981
|
-
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
|
|
982
|
-
if (metadataRows.length)
|
|
983
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
1860
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
984
1861
|
}
|
|
985
1862
|
}
|
|
986
1863
|
return fetched;
|
|
@@ -989,16 +1866,15 @@ class CardanoIndexer {
|
|
|
989
1866
|
// Private Helpers
|
|
990
1867
|
//-----------------------------------------------------------------------------
|
|
991
1868
|
/**
|
|
992
|
-
* Index
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
* @param bech32List array of bech32 addresses
|
|
1869
|
+
* Index the addresses of an account with bounded concurrency. The address data the account
|
|
1870
|
+
* carries (from the backend, or from the crawled set) is used as is, so an account costs no
|
|
1871
|
+
* request per address; an entry without UTxOs is fetched.
|
|
996
1872
|
*/
|
|
997
|
-
async _ensureAddresses(tx,
|
|
1873
|
+
async _ensureAddresses(tx, accountAddresses) {
|
|
998
1874
|
const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
|
|
999
|
-
for (let i = 0; i <
|
|
1000
|
-
const chunk =
|
|
1001
|
-
await Promise.all(chunk.map(
|
|
1875
|
+
for (let i = 0; i < accountAddresses.length; i += concurrency) {
|
|
1876
|
+
const chunk = accountAddresses.slice(i, i + concurrency);
|
|
1877
|
+
await Promise.all(chunk.map(a => this.indexAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined)));
|
|
1002
1878
|
}
|
|
1003
1879
|
}
|
|
1004
1880
|
}
|