@odatano/core 2.0.0-rc.3 → 2.0.0-rc.30
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 +294 -7
- package/@cds-models/CardanoODataService/index.js +33 -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 +52 -19
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +18 -0
- package/@cds-models/index.js +3 -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 +677 -13
- package/db/types.cds +27 -0
- package/package.json +182 -173
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +11 -10
- package/src/index.js +28 -14
- package/src/plugin.js +39 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +49 -160
- 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 +356 -217
- 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 +548 -197
- 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 +78 -205
- package/srv/blockchain/cardano-client.js +186 -242
- package/srv/blockchain/cardano-indexer.d.ts +302 -242
- package/srv/blockchain/cardano-indexer.js +1191 -362
- package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
- package/srv/blockchain/cardano-tx-builder.js +177 -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 +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- 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 +108 -160
- package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
- package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
- package/srv/blockchain/transaction-building/caller-datums.js +50 -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 +48 -24
- 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 +56 -1
- package/srv/cardano-service.js +52 -113
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +439 -364
- package/srv/cardano-tx-service.js +305 -209
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.js +7 -15
- package/srv/cbor/parse.js +13 -1
- package/srv/server.d.ts +28 -86
- package/srv/server.js +127 -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 +13 -0
- package/srv/utils/epoch-slots.js +25 -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/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 +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +26 -92
- package/srv/utils/tx-build-helper.js +68 -123
- package/srv/utils/tx-request-parsers.d.ts +107 -21
- package/srv/utils/tx-request-parsers.js +433 -34
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +238 -169
- 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;
|
|
47
83
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
|
|
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, 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
|
+
}
|
|
161
|
+
/**
|
|
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,127 @@ 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
|
+
return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
|
|
551
|
+
* transaction, so either everything persists or nothing does.
|
|
119
552
|
*/
|
|
120
553
|
async indexTransaction(tx, txHash) {
|
|
121
|
-
|
|
554
|
+
await this.refuseOutsideCrawl(tx, 'getTransaction', `Transaction ${txHash}`);
|
|
122
555
|
const providerTx = await this.client.getTransaction(txHash);
|
|
123
556
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
124
557
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
125
558
|
logger.debug(`indexTransaction: upserted transaction ${txHash}`);
|
|
559
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
560
|
+
return txRow;
|
|
561
|
+
}
|
|
562
|
+
/** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
|
|
563
|
+
async writeTransactionChildren(tx, providerTx, txSeq) {
|
|
126
564
|
if (providerTx.inputs) {
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
if (inputRows.length) {
|
|
565
|
+
const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
|
|
566
|
+
const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
|
|
567
|
+
if (inputRows.length)
|
|
131
568
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
if (inputAssetRows.length) {
|
|
569
|
+
if (inputAssetRows.length)
|
|
135
570
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
|
|
136
|
-
logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
|
|
137
|
-
}
|
|
138
571
|
}
|
|
139
|
-
//
|
|
140
|
-
// `inputs` previously skipped its outputs entirely)
|
|
572
|
+
// outputs must not depend on the inputs branch
|
|
141
573
|
if (providerTx.outputs) {
|
|
142
|
-
const outputRows = (0, mappers_1.mapTransactionOutputs)(
|
|
143
|
-
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(
|
|
144
|
-
if (outputRows.length)
|
|
574
|
+
const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
|
|
575
|
+
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
|
|
576
|
+
if (outputRows.length)
|
|
145
577
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
146
|
-
|
|
147
|
-
if (outputAssetRows.length) {
|
|
578
|
+
if (outputAssetRows.length)
|
|
148
579
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
149
|
-
}
|
|
150
580
|
}
|
|
151
581
|
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
|
|
152
|
-
if (metadataRows.length)
|
|
582
|
+
if (metadataRows.length)
|
|
153
583
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
154
|
-
}
|
|
155
|
-
return txRow;
|
|
156
584
|
}
|
|
157
585
|
/**
|
|
158
|
-
* Index
|
|
159
|
-
*
|
|
160
|
-
* @param tx CAP transaction
|
|
161
|
-
* @param addr bech32 address
|
|
162
|
-
* @return {Promise<Address>} address entity data
|
|
586
|
+
* Index address data with assets and UTxOs; transactions are loaded separately via
|
|
587
|
+
* indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
|
|
163
588
|
*/
|
|
164
|
-
async indexAddress(tx, addr) {
|
|
165
|
-
const addrData = await this.
|
|
589
|
+
async indexAddress(tx, addr, prefetched) {
|
|
590
|
+
const addrData = prefetched ?? await this.resolveAddress(tx, addr);
|
|
166
591
|
logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
|
|
167
592
|
const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
|
|
168
593
|
const now = new Date().toISOString();
|
|
169
594
|
const validFrom = AddrEntity.validFrom ?? now;
|
|
170
595
|
const validTo = AddrEntity.validTo ?? now;
|
|
171
596
|
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
|
|
597
|
+
// Supplement address-level amounts with assets only present in UTxOs
|
|
174
598
|
const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
|
|
175
599
|
for (const utxo of addrData.utxos) {
|
|
176
600
|
for (const amt of utxo.amount) {
|
|
@@ -220,21 +644,13 @@ class CardanoIndexer {
|
|
|
220
644
|
return AddrEntity;
|
|
221
645
|
}
|
|
222
646
|
/**
|
|
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
|
|
647
|
+
* Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
|
|
648
|
+
* rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
|
|
234
649
|
*/
|
|
235
650
|
async indexCredentialUtxos(tx, credHash) {
|
|
236
|
-
const
|
|
237
|
-
|
|
651
|
+
const local = await this.localCredentialUtxos(tx, credHash);
|
|
652
|
+
const utxos = local ?? await this.client.getCredentialUtxos(credHash);
|
|
653
|
+
logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
|
|
238
654
|
if (utxos.length === 0)
|
|
239
655
|
return [];
|
|
240
656
|
// Group by bech32 address — Koios returns UTxOs across all bech32 forms
|
|
@@ -271,17 +687,104 @@ class CardanoIndexer {
|
|
|
271
687
|
return allRows;
|
|
272
688
|
}
|
|
273
689
|
/**
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
* the
|
|
277
|
-
*
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
690
|
+
* UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
|
|
691
|
+
* UTxO set (see openLedgerUtxos).
|
|
692
|
+
* null = the crawled set cannot answer (not synced, no set, credential column still filling).
|
|
693
|
+
* An address first used in the last `confirmationDepth` blocks is not in the set yet.
|
|
694
|
+
*/
|
|
695
|
+
async localCredentialUtxos(tx, credHash) {
|
|
696
|
+
if (!(await this.localCoverage(tx))?.ledger || !(await this.paymentCredentialsReady()))
|
|
697
|
+
return null;
|
|
698
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
|
|
699
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
700
|
+
if (addresses.length === 0)
|
|
701
|
+
return [];
|
|
702
|
+
return this.openLedgerUtxos(tx, addresses);
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Unspent outputs of addresses from the crawled set, checked against the node by output reference
|
|
706
|
+
* (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
|
|
707
|
+
* the cursor. Without a usable node, or when the check fails, the set as of the cursor.
|
|
708
|
+
*/
|
|
709
|
+
async openLedgerUtxos(tx, addresses) {
|
|
710
|
+
const rows = await this.ledgerUtxosOf(tx, addresses);
|
|
711
|
+
if (rows.length === 0)
|
|
712
|
+
return rows;
|
|
713
|
+
try {
|
|
714
|
+
const unspent = new Map();
|
|
715
|
+
for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
|
|
716
|
+
const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
|
|
717
|
+
if (live === null)
|
|
718
|
+
return rows;
|
|
719
|
+
for (const u of live)
|
|
720
|
+
unspent.set(`${u.txHash}#${u.outputIndex}`, u);
|
|
721
|
+
}
|
|
722
|
+
// The node's answer names the reference script, which a snapshot row from a file import lacks
|
|
723
|
+
return rows.flatMap(u => {
|
|
724
|
+
const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
|
|
725
|
+
if (!live)
|
|
726
|
+
return [];
|
|
727
|
+
return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
catch (err) {
|
|
731
|
+
logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
|
|
732
|
+
return rows;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
/** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
|
|
736
|
+
async ledgerUtxosOf(tx, addresses) {
|
|
737
|
+
const out = [];
|
|
738
|
+
for (const addrChunk of (0, collections_1.chunk)(addresses, collections_1.IN_CHUNK)) {
|
|
739
|
+
const utxos = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: { in: addrChunk }, spentTxHash: null }));
|
|
740
|
+
const amounts = await this.ledgerAmounts(tx, utxos ?? []);
|
|
741
|
+
for (const u of utxos ?? []) {
|
|
742
|
+
const txHash = String(u.txHash);
|
|
743
|
+
const outputIndex = Number(u.outputIndex);
|
|
744
|
+
out.push({
|
|
745
|
+
txHash,
|
|
746
|
+
outputIndex,
|
|
747
|
+
address: String(u.address),
|
|
748
|
+
amount: amounts.get(`${txHash}#${outputIndex}`) ?? [],
|
|
749
|
+
blockHash: '',
|
|
750
|
+
datumHash: u.utxo_dataHash ?? undefined,
|
|
751
|
+
inlineDatum: u.utxo_inlineDatum ?? null,
|
|
752
|
+
scriptRef: u.utxo_referenceScriptHash ?? undefined,
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return out;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* True once every Shelley-type `LedgerAddresses` row carries its payment credential. Until then
|
|
760
|
+
* the fill runs in the background (started once per process) and callers use the provider.
|
|
761
|
+
*/
|
|
762
|
+
async paymentCredentialsReady() {
|
|
763
|
+
if (this.credentialsReady)
|
|
764
|
+
return true;
|
|
765
|
+
if (!this.credentialFill) {
|
|
766
|
+
const generation = this.credentialGeneration;
|
|
767
|
+
this.credentialFill = (0, ledger_state_1.backfillPaymentCredentials)()
|
|
768
|
+
.then((n) => {
|
|
769
|
+
if (generation !== this.credentialGeneration)
|
|
770
|
+
return;
|
|
771
|
+
this.credentialsReady = true;
|
|
772
|
+
if (n > 0)
|
|
773
|
+
logger.info(`payment credentials filled for ${n} ledger addresses`);
|
|
774
|
+
})
|
|
775
|
+
.catch((err) => logger.error('payment credential fill failed (retried on the next lookup):', err))
|
|
776
|
+
.finally(() => { this.credentialFill = null; });
|
|
777
|
+
}
|
|
778
|
+
return false;
|
|
779
|
+
}
|
|
780
|
+
/** The ledger tables were replaced (re-import): the credential column has to be filled again. */
|
|
781
|
+
resetPaymentCredentials() {
|
|
782
|
+
this.credentialGeneration++;
|
|
783
|
+
this.credentialsReady = false;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
|
|
787
|
+
* backends without address aggregation such as Ogmios. Writes no parent Addresses row.
|
|
285
788
|
*/
|
|
286
789
|
async indexAddressUtxos(tx, addr) {
|
|
287
790
|
const utxos = await this.client.getAddressUtxos(addr);
|
|
@@ -307,21 +810,9 @@ class CardanoIndexer {
|
|
|
307
810
|
return utxoEntities;
|
|
308
811
|
}
|
|
309
812
|
/**
|
|
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
|
|
813
|
+
* Evict cached rows a submitted transaction made stale: every consumed input ref (under any
|
|
814
|
+
* address) and all address-level rows of the output addresses plus `extraAddresses`. Only the
|
|
815
|
+
* read cache is touched; lagging backends may still serve pre-submit state on refetch.
|
|
325
816
|
*/
|
|
326
817
|
async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
|
|
327
818
|
const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
|
|
@@ -339,21 +830,32 @@ class CardanoIndexer {
|
|
|
339
830
|
logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
|
|
340
831
|
}
|
|
341
832
|
}
|
|
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
|
-
*/
|
|
833
|
+
/** Index address transactions (separate from indexAddress for lazy loading). */
|
|
349
834
|
async indexAddressTransactions(tx, addr, limit) {
|
|
350
835
|
logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
|
|
351
|
-
|
|
352
|
-
const
|
|
836
|
+
const local = await this.localAddressTransactions(tx, addr, limit);
|
|
837
|
+
const keepLocal = async () => {
|
|
838
|
+
if (local.rows.length)
|
|
839
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(local.rows));
|
|
840
|
+
return local.rows;
|
|
841
|
+
};
|
|
842
|
+
if (local && (local.complete || local.rows.length >= limit))
|
|
843
|
+
return keepLocal();
|
|
844
|
+
// Hash-only listing (one API call)
|
|
845
|
+
let txHashes;
|
|
846
|
+
try {
|
|
847
|
+
txHashes = await this.client.getAddressTransactionHashes(addr, limit);
|
|
848
|
+
}
|
|
849
|
+
catch (err) {
|
|
850
|
+
// No backend with address history: what the crawled set holds is the best answer there is.
|
|
851
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError))
|
|
852
|
+
return keepLocal();
|
|
853
|
+
throw err;
|
|
854
|
+
}
|
|
353
855
|
logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
|
|
354
856
|
if (txHashes.length === 0)
|
|
355
857
|
return [];
|
|
356
|
-
//
|
|
858
|
+
// DB-first dedup + batch fetch
|
|
357
859
|
const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
|
|
358
860
|
// For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
|
|
359
861
|
// Transactions already in DB were not re-fetched — batch-fetch those separately.
|
|
@@ -387,42 +889,29 @@ class CardanoIndexer {
|
|
|
387
889
|
transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
|
|
388
890
|
return transactionsEntities;
|
|
389
891
|
}
|
|
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
|
-
*/
|
|
892
|
+
/** Link an address to a signing request for address-based queries. */
|
|
398
893
|
async indexAddressSigningRequests(tx, addr, signingRequestId) {
|
|
399
894
|
logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
|
|
400
895
|
const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
|
|
401
896
|
await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
|
|
402
897
|
logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
|
|
403
898
|
}
|
|
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
|
-
*/
|
|
899
|
+
/** Link an address to a transaction build for address-based queries. */
|
|
412
900
|
async indexAddressTransactionBuilds(tx, addr, buildId) {
|
|
413
901
|
logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
|
|
414
902
|
const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
|
|
415
903
|
await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
|
|
416
904
|
logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
|
|
417
905
|
}
|
|
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
|
-
*/
|
|
906
|
+
/** Index the metadata rows of a transaction. */
|
|
425
907
|
async indexTransactionMetadata(tx, tx_hash) {
|
|
908
|
+
// A crawled transaction without metadata rows has no metadata.
|
|
909
|
+
if (await this.crawlAnswers(tx, 'getTransactionMetadata')) {
|
|
910
|
+
const known = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
|
|
911
|
+
if (known)
|
|
912
|
+
return [];
|
|
913
|
+
await this.refuseOutsideCrawl(tx, 'getTransactionMetadata', `Transaction ${tx_hash}`);
|
|
914
|
+
}
|
|
426
915
|
const metadata = await this.client.getTransactionMetadata(tx_hash);
|
|
427
916
|
const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
|
|
428
917
|
if (rows.length) {
|
|
@@ -430,24 +919,23 @@ class CardanoIndexer {
|
|
|
430
919
|
}
|
|
431
920
|
return rows;
|
|
432
921
|
}
|
|
433
|
-
/**
|
|
434
|
-
* Index & return the network information data
|
|
435
|
-
* @param tx CAP transaction object
|
|
436
|
-
* @returns {Promise<NetworkInformation>} network information entity data
|
|
437
|
-
*/
|
|
922
|
+
/** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
|
|
438
923
|
async indexNetworkInformation(tx) {
|
|
439
|
-
const
|
|
440
|
-
const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
|
|
924
|
+
const netEntity = (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
|
|
441
925
|
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
442
926
|
return netEntity;
|
|
443
927
|
}
|
|
444
|
-
/**
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
928
|
+
/** Network information from the backend; circulating supply from the crawled UTxO set when current. */
|
|
929
|
+
async resolveNetworkInformation(tx) {
|
|
930
|
+
const netInfo = await this.client.getNetworkInformation();
|
|
931
|
+
const circulating = (await this.localCoverage(tx))?.ledger
|
|
932
|
+
? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
|
|
933
|
+
: null;
|
|
934
|
+
return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
|
|
935
|
+
}
|
|
936
|
+
/** Index a block by hash, with best-effort epoch enrichment. */
|
|
450
937
|
async indexBlock(tx, blockHash) {
|
|
938
|
+
await this.refuseOutsideCrawl(tx, 'getBlock', `Block ${blockHash}`);
|
|
451
939
|
const blockInfo = await this.client.getBlock(blockHash);
|
|
452
940
|
let epoch;
|
|
453
941
|
try {
|
|
@@ -461,48 +949,78 @@ class CardanoIndexer {
|
|
|
461
949
|
return blockEntity;
|
|
462
950
|
}
|
|
463
951
|
/**
|
|
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)
|
|
952
|
+
* Bulk-index a whole block and its transactions in one pass for the crawler: no per-hash
|
|
953
|
+
* re-fetch, one UPSERT per table, all inside the caller's transaction so the block persists
|
|
954
|
+
* atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
|
|
481
955
|
*/
|
|
482
956
|
async indexBlockFull(tx, blockData, txs) {
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
// if the caller skipped
|
|
957
|
+
// Memo updates of a rolled-back attempt must not survive into this one.
|
|
958
|
+
this.pendingCommit = [];
|
|
959
|
+
// Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
|
|
960
|
+
// (memoized) and accept the in-tx fetch.
|
|
486
961
|
let epoch;
|
|
487
962
|
if (blockData.epoch != null) {
|
|
488
963
|
await this.prefetchCrawlEpoch(blockData.epoch);
|
|
489
964
|
epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
|
|
490
965
|
const epochRows = [...this.crawlEpochCache.values()]
|
|
491
966
|
.map((entry) => entry.row)
|
|
492
|
-
.filter((row) => row !== undefined);
|
|
493
|
-
if (epochRows.length)
|
|
967
|
+
.filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
|
|
968
|
+
if (epochRows.length) {
|
|
494
969
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
970
|
+
this.pendingCommit.push(() => { for (const row of epochRows)
|
|
971
|
+
this.crawlEpochWritten.add(row); });
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
// Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
|
|
975
|
+
// Decided up front so input resolution and the ledger apply share one read of the set.
|
|
976
|
+
const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
|
|
977
|
+
const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
|
|
978
|
+
let anchorVerified = false;
|
|
979
|
+
if (ledgerDue && !priorInvalidation) {
|
|
980
|
+
anchorVerified = this.utxoAnchorVerified;
|
|
981
|
+
if (!anchorVerified) {
|
|
982
|
+
const anchor = this.utxoAnchor;
|
|
983
|
+
anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
|
|
984
|
+
// Remembered only once this transaction commits, like the other crawl memos.
|
|
985
|
+
if (anchorVerified)
|
|
986
|
+
this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
|
|
987
|
+
this.utxoAnchorVerified = true; });
|
|
988
|
+
}
|
|
495
989
|
}
|
|
990
|
+
const ledgerLookup = anchorVerified
|
|
991
|
+
? { hashes: new Set(), rows: new Map(), assets: new Map() }
|
|
992
|
+
: undefined;
|
|
993
|
+
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
994
|
+
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
995
|
+
// corrected fee changes the block's fee total.
|
|
996
|
+
await this.resolveInputs(tx, txs, ledgerLookup);
|
|
997
|
+
this.applyCollateralFees(blockData, txs);
|
|
496
998
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
497
|
-
|
|
498
|
-
await this.
|
|
499
|
-
//
|
|
999
|
+
await this.removeSupersededBlocks(tx, blockData);
|
|
1000
|
+
await this.removeStaleTxSeqs(tx, txs);
|
|
1001
|
+
// One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
|
|
1002
|
+
// srv/utils/db-sanitize.ts, not per call site.
|
|
500
1003
|
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.
|
|
1004
|
+
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
1005
|
+
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
|
|
1006
|
+
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
1007
|
+
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
505
1008
|
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
|
|
1009
|
+
// Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
|
|
1010
|
+
// re-crawl is idempotent and a reorg removes them with their tx.
|
|
1011
|
+
const certificateRows = this.crawlCertificates
|
|
1012
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
|
|
1013
|
+
: [];
|
|
1014
|
+
const withdrawalRows = this.crawlCertificates
|
|
1015
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
|
|
1016
|
+
: [];
|
|
1017
|
+
if (this.crawlCertificates)
|
|
1018
|
+
this.warnIfCertificatesUnreported(txs);
|
|
1019
|
+
// Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
|
|
1020
|
+
const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
|
|
1021
|
+
// Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
|
|
1022
|
+
// idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
|
|
1023
|
+
const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
|
|
506
1024
|
if (txRows.length)
|
|
507
1025
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
|
|
508
1026
|
if (inputRows.length)
|
|
@@ -515,21 +1033,97 @@ class CardanoIndexer {
|
|
|
515
1033
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
516
1034
|
if (metadataRows.length)
|
|
517
1035
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
518
|
-
|
|
1036
|
+
if (certificateRows.length)
|
|
1037
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
|
|
1038
|
+
if (withdrawalRows.length)
|
|
1039
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
|
|
1040
|
+
if (redeemerRows.length)
|
|
1041
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
|
|
1042
|
+
// Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
|
|
1043
|
+
if (ledgerDue) {
|
|
1044
|
+
if (priorInvalidation) {
|
|
1045
|
+
// Decided in an earlier attempt of this block whose transaction rolled back: re-write
|
|
1046
|
+
// the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
|
|
1047
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
|
|
1048
|
+
}
|
|
1049
|
+
else if (ledgerLookup) {
|
|
1050
|
+
const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
|
|
1051
|
+
if (ledger.missing) {
|
|
1052
|
+
logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
|
|
1053
|
+
'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
if (assetHistoryRows.length)
|
|
1058
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
|
|
1059
|
+
// Catalogue last; collecting the units is skipped entirely when the catalogue is off.
|
|
1060
|
+
const newAssets = this.crawlAssetCatalogue === 'off'
|
|
1061
|
+
? 0
|
|
1062
|
+
: await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
|
|
1063
|
+
logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
|
|
1064
|
+
`${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Drop other Block rows at the crawled block's height that no transaction references: lazily
|
|
1068
|
+
* indexed tips that were rolled back, which no crawler reorg covers.
|
|
1069
|
+
*/
|
|
1070
|
+
async removeSupersededBlocks(tx, blockData) {
|
|
1071
|
+
if (blockData.height == null)
|
|
1072
|
+
return;
|
|
1073
|
+
const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
|
|
1074
|
+
if (!others?.length)
|
|
1075
|
+
return;
|
|
1076
|
+
const hashes = others.map(r => r.hash);
|
|
1077
|
+
const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
|
|
1078
|
+
const keep = new Set((referenced ?? []).map(r => r.blockHash));
|
|
1079
|
+
const stale = hashes.filter(h => !keep.has(h));
|
|
1080
|
+
if (!stale.length)
|
|
1081
|
+
return;
|
|
1082
|
+
await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
|
|
1083
|
+
logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* Drop transactions of another fork that hold one of this block's txSeq keys (a lazily indexed
|
|
1087
|
+
* tx from a rolled-back block at the same slot); their input/output rows would mix with ours.
|
|
1088
|
+
*/
|
|
1089
|
+
async removeStaleTxSeqs(tx, txs) {
|
|
1090
|
+
if (!txs.length)
|
|
1091
|
+
return;
|
|
1092
|
+
const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
1093
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
|
|
1094
|
+
.where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
|
|
1095
|
+
const ours = new Set(txs.map(t => t.hash));
|
|
1096
|
+
const stale = (rows ?? []).filter(r => !ours.has(r.hash));
|
|
1097
|
+
if (!stale.length)
|
|
1098
|
+
return;
|
|
1099
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
|
|
1100
|
+
logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Warn once when `crawler.certificates` is on but the source reports none (`certificates`
|
|
1104
|
+
* undefined, as with Blockfrost). `[]` means "none" and is not a warning.
|
|
1105
|
+
*/
|
|
1106
|
+
warnIfCertificatesUnreported(txs) {
|
|
1107
|
+
if (this.certificatesUnreportedWarned || !txs.length)
|
|
1108
|
+
return;
|
|
1109
|
+
if (txs.some(t => t.certificates !== undefined))
|
|
1110
|
+
return;
|
|
1111
|
+
this.certificatesUnreportedWarned = true;
|
|
1112
|
+
logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
|
|
1113
|
+
'(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
|
|
1114
|
+
'the crawl runs on Ogmios chain-sync or Koios');
|
|
519
1115
|
}
|
|
520
1116
|
/**
|
|
521
|
-
* Backfill
|
|
522
|
-
*
|
|
523
|
-
*
|
|
524
|
-
* DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
|
|
1117
|
+
* Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
|
|
1118
|
+
* own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
|
|
1119
|
+
* already carry an address are skipped.
|
|
525
1120
|
*/
|
|
526
|
-
async resolveInputs(tx, txs) {
|
|
527
|
-
// 1. In-memory index of this block's outputs (txHash#outputIndex ->
|
|
1121
|
+
async resolveInputs(tx, txs, ledger) {
|
|
1122
|
+
// 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
|
|
528
1123
|
const blockOutputs = new Map();
|
|
529
1124
|
for (const t of txs) {
|
|
530
|
-
for (const o of t.outputs ?? [])
|
|
531
|
-
blockOutputs.set(`${t.hash}#${o.outputIndex}`,
|
|
532
|
-
}
|
|
1125
|
+
for (const o of t.outputs ?? [])
|
|
1126
|
+
blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
|
|
533
1127
|
}
|
|
534
1128
|
// 2. Collect inputs still needing resolution after the same-block pass
|
|
535
1129
|
const unresolved = [];
|
|
@@ -541,7 +1135,8 @@ class CardanoIndexer {
|
|
|
541
1135
|
const local = blockOutputs.get(key);
|
|
542
1136
|
if (local) {
|
|
543
1137
|
input.address = local.address;
|
|
544
|
-
input.amount = local.amount;
|
|
1138
|
+
input.amount = local.amount ?? [];
|
|
1139
|
+
copyUtxoData(input, local.dataHash, local.inlineDatum, local.referenceScriptHash);
|
|
545
1140
|
}
|
|
546
1141
|
else {
|
|
547
1142
|
unresolved.push({ input, key });
|
|
@@ -550,111 +1145,421 @@ class CardanoIndexer {
|
|
|
550
1145
|
}
|
|
551
1146
|
if (!unresolved.length)
|
|
552
1147
|
return;
|
|
553
|
-
// 3.
|
|
554
|
-
//
|
|
555
|
-
|
|
1148
|
+
// 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
|
|
1149
|
+
// reuses the same lookup instead of reading these outpoints a second time.
|
|
1150
|
+
if (ledger) {
|
|
1151
|
+
await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
|
|
1152
|
+
for (let i = unresolved.length - 1; i >= 0; i--) {
|
|
1153
|
+
const row = ledger.rows.get(unresolved[i].key);
|
|
1154
|
+
if (!row)
|
|
1155
|
+
continue;
|
|
1156
|
+
unresolved[i].input.address = row.address;
|
|
1157
|
+
unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
|
|
1158
|
+
copyUtxoData(unresolved[i].input, row.utxo_dataHash, row.utxo_inlineDatum, row.utxo_referenceScriptHash);
|
|
1159
|
+
unresolved.splice(i, 1);
|
|
1160
|
+
}
|
|
1161
|
+
if (!unresolved.length)
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
// 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
|
|
1165
|
+
// never exceeds a driver's bind-variable cap
|
|
556
1166
|
const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
|
|
557
|
-
const
|
|
1167
|
+
const hashBySeq = new Map();
|
|
1168
|
+
for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
|
|
1169
|
+
if (k.txSeq != null)
|
|
1170
|
+
hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
|
|
1171
|
+
}
|
|
1172
|
+
const outByKey = new Map();
|
|
558
1173
|
const amtByKey = new Map();
|
|
559
|
-
for (const
|
|
1174
|
+
for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
|
|
560
1175
|
const [outRows, assetRows] = await Promise.all([
|
|
561
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({
|
|
562
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({
|
|
1176
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
|
|
1177
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
|
|
563
1178
|
]);
|
|
564
1179
|
for (const r of outRows) {
|
|
565
|
-
|
|
1180
|
+
outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
|
|
566
1181
|
}
|
|
567
1182
|
for (const r of assetRows) {
|
|
568
|
-
const k = `${r.
|
|
1183
|
+
const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
|
|
569
1184
|
const list = amtByKey.get(k) ?? [];
|
|
570
1185
|
list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
|
|
571
1186
|
amtByKey.set(k, list);
|
|
572
1187
|
}
|
|
573
1188
|
}
|
|
574
1189
|
for (const { input, key } of unresolved) {
|
|
575
|
-
const
|
|
576
|
-
if (
|
|
577
|
-
input.address =
|
|
1190
|
+
const out = outByKey.get(key);
|
|
1191
|
+
if (out?.address_address != null)
|
|
1192
|
+
input.address = out.address_address;
|
|
1193
|
+
if (out)
|
|
1194
|
+
copyUtxoData(input, out.utxo_dataHash, out.utxo_inlineDatum, out.utxo_referenceScriptHash);
|
|
578
1195
|
const amt = amtByKey.get(key);
|
|
579
1196
|
if (amt)
|
|
580
1197
|
input.amount = amt;
|
|
581
1198
|
}
|
|
582
1199
|
}
|
|
583
1200
|
/**
|
|
584
|
-
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
|
|
1201
|
+
* Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
|
|
1202
|
+
* and the block total. The declared fee is kept when the mapper already set it via
|
|
1203
|
+
* `total_collateral` or a collateral input is not indexed locally (the sum would be short).
|
|
1204
|
+
*/
|
|
1205
|
+
applyCollateralFees(blockData, txs) {
|
|
1206
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
1207
|
+
let corrected = false;
|
|
1208
|
+
for (const t of txs) {
|
|
1209
|
+
// totalCollateral set = the mapper already put the charged amount in `fee`
|
|
1210
|
+
if (!t.spendsCollaterals || t.totalCollateral != null)
|
|
1211
|
+
continue;
|
|
1212
|
+
const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
|
|
1213
|
+
if (!collateral.length)
|
|
1214
|
+
continue; // nothing to derive from — leave the declared fee
|
|
1215
|
+
const unresolved = collateral.find(i => !i.address);
|
|
1216
|
+
if (unresolved) {
|
|
1217
|
+
logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
1218
|
+
`— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
|
|
1222
|
+
const returned = (t.outputs ?? [])
|
|
1223
|
+
.filter(o => o.isCollateral)
|
|
1224
|
+
.reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
|
|
1225
|
+
const charged = consumed - returned;
|
|
1226
|
+
if (charged < 0n) {
|
|
1227
|
+
logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
|
|
1228
|
+
`— keeping the declared fee ${t.fee}`);
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
t.fee = charged.toString();
|
|
1232
|
+
corrected = true;
|
|
1233
|
+
}
|
|
1234
|
+
if (corrected) {
|
|
1235
|
+
blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Mint/burn rows for a block from data in hand: the ledger's mint field when the source
|
|
1240
|
+
* reports it (Ogmios, Koios), else Σ outputs − Σ inputs per unit, excluding reference and
|
|
1241
|
+
* collateral inputs. A tx with an unresolvable consumed input is skipped and logged.
|
|
1242
|
+
*/
|
|
1243
|
+
buildAssetHistoryRows(blockData, txs) {
|
|
1244
|
+
const entries = [];
|
|
1245
|
+
let skipped = 0;
|
|
1246
|
+
for (const t of txs) {
|
|
1247
|
+
let net;
|
|
1248
|
+
if (t.mint) {
|
|
1249
|
+
// A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
|
|
1250
|
+
net = new Map();
|
|
1251
|
+
for (const m of t.mint) {
|
|
1252
|
+
if (m.unit === 'lovelace')
|
|
1253
|
+
continue;
|
|
1254
|
+
net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
else {
|
|
1258
|
+
if (t.spendsCollaterals)
|
|
1259
|
+
continue; // no mint is applied when the script phase failed
|
|
1260
|
+
const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
|
|
1261
|
+
const unresolved = consumed.find(i => !i.address);
|
|
1262
|
+
if (unresolved) {
|
|
1263
|
+
logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
1264
|
+
`— skipping, mint/burn of this transaction is not recorded`);
|
|
1265
|
+
skipped++;
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
net = new Map();
|
|
1269
|
+
const add = (amount, sign) => {
|
|
1270
|
+
for (const a of amount ?? []) {
|
|
1271
|
+
if (a.unit === 'lovelace')
|
|
1272
|
+
continue;
|
|
1273
|
+
net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
|
|
1277
|
+
add(o.amount, 1n);
|
|
1278
|
+
for (const i of consumed)
|
|
1279
|
+
add(i.amount, -1n);
|
|
1280
|
+
}
|
|
1281
|
+
for (const [unit, quantity] of net) {
|
|
1282
|
+
if (quantity === 0n)
|
|
1283
|
+
continue;
|
|
1284
|
+
entries.push({
|
|
1285
|
+
unit,
|
|
1286
|
+
txHash: t.hash,
|
|
1287
|
+
action: quantity > 0n ? 'mint' : 'burn',
|
|
1288
|
+
quantity: (quantity < 0n ? -quantity : quantity).toString(),
|
|
1289
|
+
blockTime: blockData.time ?? null,
|
|
1290
|
+
blockHeight: blockData.height ?? null,
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
if (skipped) {
|
|
1295
|
+
logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
|
|
1296
|
+
}
|
|
1297
|
+
return (0, mappers_1.mapAssetHistory)(entries);
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* Keep the `Assets` catalogue complete for every unit the crawl meets, without provider calls.
|
|
1301
|
+
* `Assets` is temporal, key `(validFrom, unit)`: the bare row's fixed epoch-zero stamp never
|
|
1302
|
+
* aliases an enriched slice, so the UPSERT is safe inside the block transaction. The existence
|
|
1303
|
+
* check uses the DB-level entity: the service projection's temporal filter hides such rows.
|
|
588
1304
|
*/
|
|
1305
|
+
async ensureAssetRows(tx, units) {
|
|
1306
|
+
if (this.crawlAssetCatalogue === 'off' || !units.size)
|
|
1307
|
+
return 0;
|
|
1308
|
+
const unknown = [...units].filter(u => !this.assetMemo.has(u));
|
|
1309
|
+
if (!unknown.length)
|
|
1310
|
+
return 0;
|
|
1311
|
+
const missing = [];
|
|
1312
|
+
for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
|
|
1313
|
+
const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
|
|
1314
|
+
const known = new Set(rows.map(r => r.unit));
|
|
1315
|
+
for (const unit of unitChunk) {
|
|
1316
|
+
if (known.has(unit))
|
|
1317
|
+
this.noteAssetSeen(unit);
|
|
1318
|
+
else
|
|
1319
|
+
missing.push(unit);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
if (!missing.length)
|
|
1323
|
+
return 0;
|
|
1324
|
+
const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
|
|
1325
|
+
// Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
|
|
1326
|
+
for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
|
|
1327
|
+
await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
|
|
1328
|
+
}
|
|
1329
|
+
// Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
|
|
1330
|
+
// the commit: a rolled-back block must write its bare rows again.
|
|
1331
|
+
this.pendingCommit.push(() => { for (const unit of missing)
|
|
1332
|
+
this.noteAssetSeen(unit); });
|
|
1333
|
+
if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
|
|
1334
|
+
for (const row of rows) {
|
|
1335
|
+
if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
|
|
1336
|
+
this.enrichQueue.shift();
|
|
1337
|
+
this.enrichQueue.push(row.unit);
|
|
1338
|
+
}
|
|
1339
|
+
this.startAssetEnrichment();
|
|
1340
|
+
}
|
|
1341
|
+
return rows.length;
|
|
1342
|
+
}
|
|
1343
|
+
/**
|
|
1344
|
+
* Remember a unit as present in the catalogue. Insertion-ordered eviction keeps a long
|
|
1345
|
+
* backfill's memory flat; losing an entry costs one SELECT, never a wrong write.
|
|
1346
|
+
*/
|
|
1347
|
+
noteAssetSeen(unit) {
|
|
1348
|
+
if (this.assetMemo.has(unit))
|
|
1349
|
+
return;
|
|
1350
|
+
if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
|
|
1351
|
+
const oldest = this.assetMemo.values().next();
|
|
1352
|
+
if (!oldest.done)
|
|
1353
|
+
this.assetMemo.delete(oldest.value);
|
|
1354
|
+
}
|
|
1355
|
+
this.assetMemo.add(unit);
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit), plus
|
|
1359
|
+
* one EpochLedgerSnapshots row that marks the epoch as observed. With a block hash and an Ogmios
|
|
1360
|
+
* backend the node's ledger state AT that block is read; otherwise Koios reports current state
|
|
1361
|
+
* (and the live `Pools` / `Dreps` rows are refreshed). Neither available: no-op.
|
|
1362
|
+
* @returns counts written and the source used (null = skipped)
|
|
1363
|
+
*/
|
|
1364
|
+
async snapshotEpoch(epoch, at) {
|
|
1365
|
+
const epochState = at.hash ? this.client.getEpochStateBackend() : null;
|
|
1366
|
+
if (epochState && at.hash)
|
|
1367
|
+
return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash });
|
|
1368
|
+
const backend = this.client.getEnumeratingBackend();
|
|
1369
|
+
if (!backend) {
|
|
1370
|
+
logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
|
|
1371
|
+
return { pools: 0, dreps: 0, source: null };
|
|
1372
|
+
}
|
|
1373
|
+
// Network first, DB second — the provider round-trips must not run with a write lock held.
|
|
1374
|
+
const [poolData, drepData] = await Promise.all([
|
|
1375
|
+
backend.getPoolIds().then(ids => backend.getPools(ids)),
|
|
1376
|
+
backend.getDrepIds().then(ids => backend.getDreps(ids)),
|
|
1377
|
+
]);
|
|
1378
|
+
const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
|
|
1379
|
+
const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
|
|
1380
|
+
const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
|
|
1381
|
+
const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
|
|
1382
|
+
const ledgerRow = {
|
|
1383
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: null, source: 'koios',
|
|
1384
|
+
liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1385
|
+
poolCount: poolData.length, drepCount: drepData.length,
|
|
1386
|
+
};
|
|
1387
|
+
await cds_1.default.tx(async (tx) => {
|
|
1388
|
+
// Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
|
|
1389
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1390
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1391
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1392
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1393
|
+
for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
|
|
1394
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
|
|
1395
|
+
for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
|
|
1396
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
|
|
1397
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1398
|
+
});
|
|
1399
|
+
logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1400
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Epoch snapshot from the node's ledger state at block `at`. The live `Pools` / `Dreps` rows are
|
|
1404
|
+
* NOT refreshed: the acquired state may be hours old. `blocksMinted` counts crawled blocks up to
|
|
1405
|
+
* `at`, only when the crawl covers the chain since Shelley.
|
|
1406
|
+
*/
|
|
1407
|
+
async snapshotEpochFromLedger(backend, epoch, at) {
|
|
1408
|
+
const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
|
|
1409
|
+
if (state.epoch !== epoch) {
|
|
1410
|
+
logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch} — stored as ${epoch}`);
|
|
1411
|
+
}
|
|
1412
|
+
const minted = await this.crawledBlocksByPool(at.slot);
|
|
1413
|
+
const previous = await this.previousLiveStake(epoch);
|
|
1414
|
+
const activeTotal = previous ? [...previous.values()].reduce((a, b) => a + b, 0n) : 0n;
|
|
1415
|
+
const origin = { source: 'ogmios', hash: at.hash };
|
|
1416
|
+
const poolSnapshots = state.pools.map(p => {
|
|
1417
|
+
const active = previous?.get(p.poolId);
|
|
1418
|
+
return {
|
|
1419
|
+
...(0, mappers_1.mapPoolSnapshot)(p, epoch, at, origin),
|
|
1420
|
+
blocksMinted: minted ? (minted.get(p.poolId) ?? 0) : null,
|
|
1421
|
+
activeStake: active == null ? null : active.toString(),
|
|
1422
|
+
activeSize: active == null || activeTotal === 0n ? null : Number((active * 1000000n) / activeTotal) / 1_000_000,
|
|
1423
|
+
};
|
|
1424
|
+
});
|
|
1425
|
+
const drepSnapshots = state.dreps.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at, origin));
|
|
1426
|
+
const reserves = state.reserves == null ? null : BigInt(state.reserves);
|
|
1427
|
+
const ledgerRow = {
|
|
1428
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: at.hash, source: 'ogmios',
|
|
1429
|
+
treasury: state.treasury,
|
|
1430
|
+
reserves: state.reserves,
|
|
1431
|
+
totalSupply: reserves == null ? null : (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves).toString(),
|
|
1432
|
+
liveStake: state.pools.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1433
|
+
activeStake: previous ? activeTotal.toString() : null,
|
|
1434
|
+
poolCount: state.pools.length,
|
|
1435
|
+
drepCount: state.dreps.length,
|
|
1436
|
+
drepAbstainStake: state.drepAbstainStake,
|
|
1437
|
+
drepNoConfidenceStake: state.drepNoConfidenceStake,
|
|
1438
|
+
};
|
|
1439
|
+
await cds_1.default.tx(async (tx) => {
|
|
1440
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1441
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1442
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1443
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1444
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1445
|
+
});
|
|
1446
|
+
logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1447
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Active stake of epoch E = the stake distribution taken at the E-1 boundary, which is the live
|
|
1451
|
+
* stake the Ogmios snapshot of E-1 recorded at its first block. null without that snapshot.
|
|
1452
|
+
*/
|
|
1453
|
+
async previousLiveStake(epoch) {
|
|
1454
|
+
const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
|
|
1455
|
+
if (!rows?.length)
|
|
1456
|
+
return null;
|
|
1457
|
+
return new Map(rows.map(r => [r.poolId, BigInt(lovelaceSum(r.liveStake))]));
|
|
1458
|
+
}
|
|
1459
|
+
/** Crawled blocks per pool up to `slot`; null unless the crawl started at or before Shelley. */
|
|
1460
|
+
async crawledBlocksByPool(slot) {
|
|
1461
|
+
const db = cds_1.default.db;
|
|
1462
|
+
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
1463
|
+
const shelley = const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot;
|
|
1464
|
+
if (cursor?.startSlot == null || cursor.startSlot > shelley)
|
|
1465
|
+
return null;
|
|
1466
|
+
const rows = await db.run(SELECT.from(CardanoODataService_1.Blocks).columns('slotLeader', 'count(*) as n').where({ slot: { '<=': slot } }).groupBy('slotLeader'));
|
|
1467
|
+
const out = new Map();
|
|
1468
|
+
for (const r of rows ?? [])
|
|
1469
|
+
if (r.slotLeader)
|
|
1470
|
+
out.set(r.slotLeader, Number(r.n));
|
|
1471
|
+
return out;
|
|
1472
|
+
}
|
|
1473
|
+
/** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
|
|
1474
|
+
collectBlockUnits(txs, assetHistoryRows) {
|
|
1475
|
+
const units = new Set();
|
|
1476
|
+
for (const t of txs) {
|
|
1477
|
+
for (const o of t.outputs ?? []) {
|
|
1478
|
+
for (const a of o.amount ?? [])
|
|
1479
|
+
if (a.unit !== 'lovelace')
|
|
1480
|
+
units.add(a.unit);
|
|
1481
|
+
}
|
|
1482
|
+
for (const i of t.inputs ?? []) {
|
|
1483
|
+
for (const a of i.amount ?? [])
|
|
1484
|
+
if (a.unit !== 'lovelace')
|
|
1485
|
+
units.add(a.unit);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
for (const row of assetHistoryRows)
|
|
1489
|
+
if (row.unit)
|
|
1490
|
+
units.add(row.unit);
|
|
1491
|
+
return units;
|
|
1492
|
+
}
|
|
1493
|
+
/** Index an epoch by number. */
|
|
589
1494
|
async indexEpoch(tx, epochNumber) {
|
|
590
1495
|
const epochInfo = await this.client.getEpoch(epochNumber);
|
|
591
1496
|
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
592
1497
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
593
1498
|
return epochEntity;
|
|
594
1499
|
}
|
|
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
|
-
*/
|
|
1500
|
+
/** Index an account by stake address, plus its addresses when it has any. */
|
|
601
1501
|
async indexAccount(tx, stakeAddress) {
|
|
602
|
-
const accountInfo = await this.
|
|
1502
|
+
const accountInfo = await this.resolveAccount(tx, stakeAddress);
|
|
603
1503
|
const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
|
|
604
1504
|
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
605
|
-
const addresses = accountInfo.addresses.map(a => a.address);
|
|
606
1505
|
if (accountEntity.hasAddresses) {
|
|
607
|
-
await this._ensureAddresses(tx, addresses);
|
|
1506
|
+
await this._ensureAddresses(tx, accountInfo.addresses);
|
|
608
1507
|
}
|
|
609
1508
|
return accountEntity;
|
|
610
1509
|
}
|
|
611
|
-
/**
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1510
|
+
/** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
|
|
1511
|
+
async resolveAccount(tx, stakeAddress) {
|
|
1512
|
+
const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
|
|
1513
|
+
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
|
|
1514
|
+
// the addresses come from the set too (the node has no stake-key -> address index)
|
|
1515
|
+
if ((await this.localCoverage(tx))?.ledger) {
|
|
1516
|
+
const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
|
|
1517
|
+
accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
|
|
1518
|
+
accountInfo.addresses = await this.localAccountAddresses(tx, stakeAddress);
|
|
1519
|
+
}
|
|
1520
|
+
if (accountInfo.withdrawalsSum === '0') {
|
|
1521
|
+
const local = await this.localWithdrawalsSum(tx, stakeAddress);
|
|
1522
|
+
if (local != null)
|
|
1523
|
+
accountInfo.withdrawalsSum = local;
|
|
1524
|
+
}
|
|
1525
|
+
return accountInfo;
|
|
1526
|
+
}
|
|
1527
|
+
/** Index a DRep by bech32 id. */
|
|
617
1528
|
async indexDrep(tx, drepId) {
|
|
618
1529
|
const drepInfo = await this.client.getDrep(drepId);
|
|
619
1530
|
const drepEntity = (0, mappers_1.mapDrep)(drepInfo, this.client.max_age_ms);
|
|
620
1531
|
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
|
|
621
1532
|
return drepEntity;
|
|
622
1533
|
}
|
|
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
|
-
*/
|
|
1534
|
+
/** Index a pool by id. */
|
|
629
1535
|
async indexPool(tx, poolId) {
|
|
630
|
-
const
|
|
631
|
-
const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
|
|
1536
|
+
const poolEntity = (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
|
|
632
1537
|
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
633
1538
|
return poolEntity;
|
|
634
1539
|
}
|
|
635
|
-
/**
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1540
|
+
/** Pool from the backend with crawled block counts and the snapshot's active stake. */
|
|
1541
|
+
async resolvePool(tx, poolId) {
|
|
1542
|
+
const poolInfo = { ...(await this.client.getPool(poolId)), ...(await this.localPoolBlocks(tx, poolId)) };
|
|
1543
|
+
// The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
|
|
1544
|
+
if (poolInfo.activeStake === '0')
|
|
1545
|
+
Object.assign(poolInfo, await this.snapshotActiveStake(tx, poolId));
|
|
1546
|
+
return poolInfo;
|
|
1547
|
+
}
|
|
1548
|
+
/** Index an asset by unit (policyId + assetNameHex). */
|
|
641
1549
|
async indexAsset(tx, unit) {
|
|
642
|
-
const assetInfo = await this.
|
|
1550
|
+
const assetInfo = await this.resolveAssetInfo(tx, unit);
|
|
643
1551
|
const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
|
|
644
1552
|
await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
|
|
645
1553
|
return assetEntity;
|
|
646
1554
|
}
|
|
647
1555
|
/**
|
|
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
|
|
1556
|
+
* Index mint/burn history for an asset, always fresh. Rows are keyed (unit, txHash), so a
|
|
1557
|
+
* refetch refreshes the recent cap and older cached entries persist.
|
|
656
1558
|
*/
|
|
657
1559
|
async indexAssetHistory(tx, unit, limit = 100) {
|
|
1560
|
+
if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
|
|
1561
|
+
return await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
|
|
1562
|
+
}
|
|
658
1563
|
const events = await this.client.getAssetHistory(unit, limit);
|
|
659
1564
|
if (events.length === 0)
|
|
660
1565
|
return [];
|
|
@@ -662,14 +1567,7 @@ class CardanoIndexer {
|
|
|
662
1567
|
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
|
|
663
1568
|
return rows;
|
|
664
1569
|
}
|
|
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
|
-
*/
|
|
1570
|
+
/** Build a transaction and persist the build result with inputs/outputs/address association. */
|
|
673
1571
|
async _indexBuildResult(tx, buildreq, buildFn) {
|
|
674
1572
|
const protocolParams = await this.indexProtocolParameters(tx);
|
|
675
1573
|
const txbuildResult = await buildFn(buildreq, protocolParams);
|
|
@@ -683,6 +1581,10 @@ class CardanoIndexer {
|
|
|
683
1581
|
const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
|
|
684
1582
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
|
|
685
1583
|
}
|
|
1584
|
+
if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
|
|
1585
|
+
const buildId = buildResult.id;
|
|
1586
|
+
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) }))));
|
|
1587
|
+
}
|
|
686
1588
|
if (buildResult.id && buildreq.senderAddress) {
|
|
687
1589
|
await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
|
|
688
1590
|
}
|
|
@@ -703,52 +1605,40 @@ class CardanoIndexer {
|
|
|
703
1605
|
async indexPlutusSpendBuildResult(tx, buildreq) {
|
|
704
1606
|
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
|
|
705
1607
|
}
|
|
706
|
-
/**
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
1608
|
+
/** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
|
|
1609
|
+
async indexPlutusBuildResult(tx, buildreq) {
|
|
1610
|
+
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
|
|
1611
|
+
}
|
|
1612
|
+
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
711
1613
|
async indexProtocolParameters(tx) {
|
|
712
1614
|
const network = this.client.network;
|
|
713
1615
|
const now = Date.now();
|
|
714
|
-
|
|
715
|
-
const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes — matches client cache TTL
|
|
1616
|
+
const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // matches the client cache TTL
|
|
716
1617
|
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.
|
|
1618
|
+
// (network, epoch) is the key; order by epoch desc to get the latest row
|
|
719
1619
|
const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
|
|
720
1620
|
if (existing)
|
|
721
1621
|
return existing;
|
|
722
1622
|
}
|
|
723
|
-
// Fetch from provider (client has 5-min in-memory TTL cache, so this is cheap)
|
|
724
1623
|
const protocolParamsInfo = await this.client.getProtocolParameters();
|
|
725
1624
|
const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
|
|
726
1625
|
await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
|
|
727
1626
|
this.lastParamsFetchTime = now;
|
|
728
1627
|
return protocolParams;
|
|
729
1628
|
}
|
|
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
|
-
*/
|
|
1629
|
+
/** Persist a transaction submission and flag the build as submitted when linked. */
|
|
737
1630
|
async persistTransactionSubmission(tx, params) {
|
|
738
1631
|
const { signedTxCbor, txHash, buildId } = params;
|
|
739
|
-
// Map submission data
|
|
740
1632
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
|
|
741
|
-
//
|
|
1633
|
+
// status 'pending' until the second phase of the submit flow confirms
|
|
742
1634
|
const submissionRecord = {
|
|
743
1635
|
...indexSubmission,
|
|
744
1636
|
build_id: buildId || null,
|
|
745
1637
|
backendResponse: 'Submitted successfully',
|
|
746
1638
|
status: 'pending',
|
|
747
1639
|
};
|
|
748
|
-
// Persist submission
|
|
749
1640
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
750
1641
|
logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
|
|
751
|
-
// Update build status if buildId provided
|
|
752
1642
|
if (buildId) {
|
|
753
1643
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
754
1644
|
.set({ wasSubmitted: true })
|
|
@@ -757,14 +1647,7 @@ class CardanoIndexer {
|
|
|
757
1647
|
}
|
|
758
1648
|
return submissionRecord;
|
|
759
1649
|
}
|
|
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
|
-
*/
|
|
1650
|
+
/** Update a submission's status (two-phase submit: pending → submitted or failed). */
|
|
768
1651
|
async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
|
|
769
1652
|
const updateData = { status };
|
|
770
1653
|
if (errorMessage) {
|
|
@@ -775,15 +1658,9 @@ class CardanoIndexer {
|
|
|
775
1658
|
.where({ id: submissionId }));
|
|
776
1659
|
logger.debug({ submissionId, status }, 'Updated submission status');
|
|
777
1660
|
}
|
|
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
|
-
*/
|
|
1661
|
+
/** Persist a new signing request and link it to the build's sender address. */
|
|
784
1662
|
async persistSigningRequest(tx, params) {
|
|
785
1663
|
const { buildId, signingPayload } = params;
|
|
786
|
-
// Create signing request record
|
|
787
1664
|
const signingRequestRecord = {
|
|
788
1665
|
id: signingPayload.signingRequestId,
|
|
789
1666
|
build_id: buildId,
|
|
@@ -796,26 +1673,17 @@ class CardanoIndexer {
|
|
|
796
1673
|
cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
|
|
797
1674
|
cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
|
|
798
1675
|
};
|
|
799
|
-
// Persist to database
|
|
800
1676
|
await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
|
|
801
1677
|
logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
|
|
802
|
-
// Index address-signing request association
|
|
803
1678
|
const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
|
|
804
1679
|
if (build?.senderAddress) {
|
|
805
1680
|
await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
|
|
806
1681
|
}
|
|
807
1682
|
return signingRequestRecord;
|
|
808
1683
|
}
|
|
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
|
-
*/
|
|
1684
|
+
/** Persist a signature verification and update the signing request status. */
|
|
816
1685
|
async persistSignatureVerification(tx, params) {
|
|
817
1686
|
const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
|
|
818
|
-
// Create verification record
|
|
819
1687
|
const verificationRecord = {
|
|
820
1688
|
id: cds_1.default.utils.uuid(),
|
|
821
1689
|
signingRequest_id: signingRequestId,
|
|
@@ -828,10 +1696,8 @@ class CardanoIndexer {
|
|
|
828
1696
|
warnings: JSON.stringify(verificationResult.warnings),
|
|
829
1697
|
verifiedAt: new Date().toISOString(),
|
|
830
1698
|
};
|
|
831
|
-
// Persist verification
|
|
832
1699
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
833
1700
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
834
|
-
// Update signing request status
|
|
835
1701
|
const newStatus = verificationResult.isValid ? 'verified' : 'failed';
|
|
836
1702
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
837
1703
|
.set({
|
|
@@ -845,16 +1711,9 @@ class CardanoIndexer {
|
|
|
845
1711
|
logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
|
|
846
1712
|
return verificationRecord;
|
|
847
1713
|
}
|
|
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
|
-
*/
|
|
1714
|
+
/** Persist a verified submission: verification, submission, signing request and build updates. */
|
|
855
1715
|
async indexVerifiedTransactionSubmission(tx, params) {
|
|
856
1716
|
const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
|
|
857
|
-
// Step 1: Create and persist verification record
|
|
858
1717
|
const verificationRecord = {
|
|
859
1718
|
id: cds_1.default.utils.uuid(),
|
|
860
1719
|
signingRequest_id: signingRequestId,
|
|
@@ -869,7 +1728,6 @@ class CardanoIndexer {
|
|
|
869
1728
|
};
|
|
870
1729
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
871
1730
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
872
|
-
// Step 2: Create and persist submission record
|
|
873
1731
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
|
|
874
1732
|
const submissionRecord = {
|
|
875
1733
|
...indexSubmission,
|
|
@@ -879,7 +1737,6 @@ class CardanoIndexer {
|
|
|
879
1737
|
};
|
|
880
1738
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
881
1739
|
logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
|
|
882
|
-
// Step 3: Update signing request metadata and status
|
|
883
1740
|
const now = new Date().toISOString();
|
|
884
1741
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
885
1742
|
.set({
|
|
@@ -892,29 +1749,20 @@ class CardanoIndexer {
|
|
|
892
1749
|
})
|
|
893
1750
|
.where({ id: signingRequestId }));
|
|
894
1751
|
logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
|
|
895
|
-
// Step 4: Update build status
|
|
896
1752
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
897
1753
|
.set({ wasSubmitted: true })
|
|
898
1754
|
.where({ id: buildId }));
|
|
899
1755
|
logger.debug({ buildId }, 'Updated build wasSubmitted flag');
|
|
900
1756
|
return submissionRecord;
|
|
901
1757
|
}
|
|
902
|
-
/**
|
|
903
|
-
* Index & return the latest epoch information data
|
|
904
|
-
* @param tx CAP transaction object
|
|
905
|
-
* @returns {Promise<Epoch>} epoch entity data
|
|
906
|
-
*/
|
|
1758
|
+
/** Index the latest epoch. */
|
|
907
1759
|
async indexLatestEpoch(tx) {
|
|
908
1760
|
const epochInfo = await this.client.getLatestEpoch();
|
|
909
1761
|
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
910
1762
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
911
1763
|
return epochEntity;
|
|
912
1764
|
}
|
|
913
|
-
/**
|
|
914
|
-
* Index & return the latest block information data
|
|
915
|
-
* @param tx CAP transaction object
|
|
916
|
-
* @returns {Promise<Block>} block entity data
|
|
917
|
-
*/
|
|
1765
|
+
/** Index the latest block, with best-effort epoch enrichment. */
|
|
918
1766
|
async indexLatestBlock(tx) {
|
|
919
1767
|
const blockInfo = await this.client.getLatestBlock();
|
|
920
1768
|
let epoch;
|
|
@@ -925,6 +1773,12 @@ class CardanoIndexer {
|
|
|
925
1773
|
// Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
|
|
926
1774
|
}
|
|
927
1775
|
const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
|
|
1776
|
+
// A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
|
|
1777
|
+
// crawled row of the same hash, or outlive the block when the tip is rolled back.
|
|
1778
|
+
if (blockInfo.headerOnly) {
|
|
1779
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: blockInfo.hash }));
|
|
1780
|
+
return stored ?? blockEntity;
|
|
1781
|
+
}
|
|
928
1782
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
|
|
929
1783
|
return blockEntity;
|
|
930
1784
|
}
|
|
@@ -933,54 +1787,30 @@ class CardanoIndexer {
|
|
|
933
1787
|
//-----------------------------------------------------------------------------
|
|
934
1788
|
/** Max addresses to index concurrently (avoid overloading backends) */
|
|
935
1789
|
static ADDR_CONCURRENCY = 5;
|
|
1790
|
+
/** Block position of a transaction already in the local index (crawled or cached), or null. */
|
|
1791
|
+
async findIndexedTransaction(tx, txHash) {
|
|
1792
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight').where({ hash: txHash }));
|
|
1793
|
+
return row ?? null;
|
|
1794
|
+
}
|
|
936
1795
|
/**
|
|
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)
|
|
1796
|
+
* Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
|
|
1797
|
+
* @returns provider transactions for the hashes that had to be fetched
|
|
946
1798
|
*/
|
|
947
1799
|
async ensureTransactionsIndexed(tx, txHashes) {
|
|
948
1800
|
const unique = [...new Set(txHashes)];
|
|
949
1801
|
if (unique.length === 0)
|
|
950
1802
|
return new Map();
|
|
951
|
-
// DB check — which hashes are already indexed?
|
|
952
1803
|
const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
|
|
953
1804
|
const existingSet = new Set(existingRows.map((r) => r.hash));
|
|
954
1805
|
const missing = unique.filter(h => !existingSet.has(h));
|
|
955
1806
|
logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
|
|
956
|
-
// Batch-fetch missing from backend
|
|
957
1807
|
let fetched = new Map();
|
|
958
1808
|
if (missing.length > 0) {
|
|
959
1809
|
fetched = await this.client.getTransactionsBatch(missing);
|
|
960
|
-
// UPSERT all fetched transactions + child entities
|
|
961
1810
|
for (const [, providerTx] of fetched) {
|
|
962
1811
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
963
1812
|
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));
|
|
1813
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
984
1814
|
}
|
|
985
1815
|
}
|
|
986
1816
|
return fetched;
|
|
@@ -989,16 +1819,15 @@ class CardanoIndexer {
|
|
|
989
1819
|
// Private Helpers
|
|
990
1820
|
//-----------------------------------------------------------------------------
|
|
991
1821
|
/**
|
|
992
|
-
* Index
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
* @param bech32List array of bech32 addresses
|
|
1822
|
+
* Index the addresses of an account with bounded concurrency. The address data the account
|
|
1823
|
+
* carries (from the backend, or from the crawled set) is used as is, so an account costs no
|
|
1824
|
+
* request per address; an entry without UTxOs is fetched.
|
|
996
1825
|
*/
|
|
997
|
-
async _ensureAddresses(tx,
|
|
1826
|
+
async _ensureAddresses(tx, accountAddresses) {
|
|
998
1827
|
const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
|
|
999
|
-
for (let i = 0; i <
|
|
1000
|
-
const chunk =
|
|
1001
|
-
await Promise.all(chunk.map(
|
|
1828
|
+
for (let i = 0; i < accountAddresses.length; i += concurrency) {
|
|
1829
|
+
const chunk = accountAddresses.slice(i, i + concurrency);
|
|
1830
|
+
await Promise.all(chunk.map(a => this.indexAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined)));
|
|
1002
1831
|
}
|
|
1003
1832
|
}
|
|
1004
1833
|
}
|