@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -8,47 +8,429 @@ 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 deep_json_1 = require("../utils/deep-json");
|
|
18
|
+
const tx_utils_1 = require("../utils/tx-utils");
|
|
19
|
+
const transaction_rows_1 = require("./transaction-rows");
|
|
20
|
+
const ledger_state_1 = require("./ledger-state");
|
|
21
|
+
const sync_state_1 = require("./crawler/sync-state");
|
|
22
|
+
const asset_decimals_1 = require("./asset-decimals");
|
|
23
|
+
const pool_metadata_1 = require("./pool-metadata");
|
|
24
|
+
const epoch_slots_1 = require("../utils/epoch-slots");
|
|
25
|
+
const const_1 = require("../utils/const");
|
|
13
26
|
const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
|
|
14
27
|
const logger = cds_1.default.log('CardanoIndexer');
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*/
|
|
28
|
+
/** Newest first; the tx hash breaks ties inside one block. */
|
|
29
|
+
function sortAddressTransactions(rows) {
|
|
30
|
+
return rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0) || String(b.tx_hash).localeCompare(String(a.tx_hash)));
|
|
31
|
+
}
|
|
32
|
+
/** Datum hash, inline datum and reference script of the spent output onto its input. */
|
|
33
|
+
function copyUtxoData(input, out) {
|
|
34
|
+
input.dataHash = input.dataHash ?? out.utxo_dataHash ?? null;
|
|
35
|
+
input.inlineDatum = input.inlineDatum ?? out.utxo_inlineDatum ?? null;
|
|
36
|
+
input.referenceScriptHash = input.referenceScriptHash ?? out.utxo_referenceScriptHash ?? null;
|
|
37
|
+
input.referenceScriptSize = input.referenceScriptSize ?? out.utxo_referenceScriptSize ?? null;
|
|
38
|
+
input.referenceScriptType = input.referenceScriptType ?? out.utxo_referenceScriptType ?? null;
|
|
39
|
+
}
|
|
40
|
+
/** A provider output in the stored-column shape, for copyUtxoData. */
|
|
41
|
+
function utxoDataOf(o) {
|
|
42
|
+
return {
|
|
43
|
+
utxo_dataHash: o.dataHash,
|
|
44
|
+
utxo_inlineDatum: o.inlineDatum,
|
|
45
|
+
utxo_referenceScriptHash: o.referenceScriptHash,
|
|
46
|
+
utxo_referenceScriptSize: o.referenceScriptSize,
|
|
47
|
+
utxo_referenceScriptType: o.referenceScriptType,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function lovelaceSum(value) {
|
|
51
|
+
if (value === null || value === undefined || value === '')
|
|
52
|
+
return '0';
|
|
53
|
+
return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
|
|
54
|
+
}
|
|
55
|
+
/** Provider-shaped address from its unspent outputs: type and stake address decoded from the address. */
|
|
56
|
+
function addressFromUtxos(address, utxos) {
|
|
57
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
58
|
+
return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
|
|
59
|
+
}
|
|
60
|
+
/** Fetches chain data, maps it to entity rows and UPSERTs them in the caller's transaction. */
|
|
28
61
|
class CardanoIndexer {
|
|
29
62
|
client;
|
|
30
63
|
txBuilder;
|
|
31
64
|
lastParamsFetchTime = 0;
|
|
32
65
|
static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
|
|
33
66
|
static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
* live and once more when the next epoch starts, so counters such as block_count,
|
|
37
|
-
* fees and lastBlockTime do not remain frozen at their first observed value.
|
|
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.
|
|
43
|
-
*/
|
|
67
|
+
// Crawler epoch memo for the current and previous epoch, refreshed while an epoch is live.
|
|
68
|
+
// A row is UPSERTed again until a block transaction that wrote it has committed.
|
|
44
69
|
crawlEpochCache = new Map();
|
|
45
70
|
crawlEpochCurrent = null;
|
|
71
|
+
/** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
|
|
72
|
+
crawlEpochWritten = new WeakSet();
|
|
73
|
+
/** Memo updates of the running block transaction, applied only after its commit. */
|
|
74
|
+
pendingCommit = [];
|
|
46
75
|
crawlEpochPrevious = null;
|
|
47
|
-
/**
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
76
|
+
/** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
|
|
77
|
+
crawlAssetHistory = true;
|
|
78
|
+
crawlAssetCatalogue = 'bare';
|
|
79
|
+
/** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
|
|
80
|
+
crawlCertificates = false;
|
|
81
|
+
/** Logged once per process: the active source reports no certificates (Blockfrost). */
|
|
82
|
+
certificatesUnreportedWarned = false;
|
|
83
|
+
/** Blocks after utxoAnchor are applied to the Ledger* tables. Without an anchor the mode is inactive. */
|
|
84
|
+
crawlUtxoSet = false;
|
|
85
|
+
/** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
|
|
86
|
+
crawlAuthoritative = false;
|
|
87
|
+
/** crawler.inputAssetCopies: every crawled input keeps a copy of its assets and points at no output. */
|
|
88
|
+
crawlInputAssetCopies = false;
|
|
89
|
+
utxoAnchor = null;
|
|
90
|
+
/** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
|
|
91
|
+
credentialsReady = false;
|
|
92
|
+
credentialFill = null;
|
|
93
|
+
credentialGeneration = 0;
|
|
94
|
+
/** The anchor block was found in the crawled chain (checked once, before the first apply). */
|
|
95
|
+
utxoAnchorVerified = false;
|
|
96
|
+
/** Kept until the crawler confirms the block commit, so a rolled-back attempt changes nothing. */
|
|
97
|
+
ledgerInvalidation = null;
|
|
98
|
+
/** Load pool metadata files from their registered URL. Off unless configured. */
|
|
99
|
+
poolMetadataFetch = false;
|
|
100
|
+
poolMetadataByHash = new Map();
|
|
101
|
+
static POOL_METADATA_MEMO_CAP = 10_000;
|
|
102
|
+
/** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
|
|
103
|
+
static ASSET_MEMO_CAP = 200_000;
|
|
104
|
+
/** Output references per node lookup when checking crawled UTxOs. */
|
|
105
|
+
static OUTREF_CHUNK = 500;
|
|
106
|
+
assetMemo = new Set();
|
|
107
|
+
// Registry enrichment queue, drained at a fixed rate outside the block transaction.
|
|
108
|
+
// Above the cap the oldest units are dropped and keep their bare row.
|
|
109
|
+
static ENRICH_QUEUE_CAP = 50_000;
|
|
110
|
+
enrichQueue = [];
|
|
111
|
+
enrichTimer = null;
|
|
112
|
+
enrichRate = 2;
|
|
113
|
+
/** Adopt the crawler's coverage settings; the lazy request path never touches these. */
|
|
114
|
+
configureCrawlCoverage(coverage) {
|
|
115
|
+
this.crawlAuthoritative = coverage.authoritative ?? false;
|
|
116
|
+
this.crawlInputAssetCopies = coverage.inputAssetCopies ?? false;
|
|
117
|
+
this.crawlAssetHistory = coverage.assetHistory;
|
|
118
|
+
this.crawlAssetCatalogue = coverage.assetCatalogue;
|
|
119
|
+
this.crawlCertificates = coverage.certificates ?? false;
|
|
120
|
+
this.crawlUtxoSet = coverage.utxoSet ?? false;
|
|
121
|
+
this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
|
|
122
|
+
if (coverage.assetCatalogue !== 'enrich')
|
|
123
|
+
this.stopAssetEnrichment();
|
|
124
|
+
}
|
|
125
|
+
// Range the crawled data answers authoritatively, only while a live crawler is at the tip.
|
|
126
|
+
// ledger is true when the crawled UTxO set is active.
|
|
127
|
+
async localCoverage(tx) {
|
|
128
|
+
const cursor = await (0, sync_state_1.readCursor)(tx);
|
|
129
|
+
if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
|
|
130
|
+
return null;
|
|
131
|
+
return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
|
|
132
|
+
}
|
|
133
|
+
// Block counts of a pool from crawled blocks. The epoch count needs the whole current epoch
|
|
134
|
+
// crawled, the lifetime count the whole chain since Shelley.
|
|
135
|
+
async localPoolBlocks(tx, poolId) {
|
|
136
|
+
const coverage = await this.localCoverage(tx);
|
|
137
|
+
if (!coverage)
|
|
138
|
+
return {};
|
|
139
|
+
const network = this.client.network;
|
|
140
|
+
const countSince = async (fromSlot) => {
|
|
141
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('count(*) as n').where({ slotLeader: poolId, slot: { '>=': fromSlot } }));
|
|
142
|
+
return Number(row?.n ?? 0);
|
|
143
|
+
};
|
|
144
|
+
const counts = {};
|
|
145
|
+
const epochStart = (0, epoch_slots_1.epochStartSlot)(network, (0, epoch_slots_1.epochOfSlot)(network, coverage.lastSlot));
|
|
146
|
+
if (coverage.fromSlot < epochStart)
|
|
147
|
+
counts.blocksEpoch = await countSince(epochStart);
|
|
148
|
+
if (coverage.fromSlot <= const_1.EPOCH_CONFIG_BY_NETWORK[network].shelleyStartSlot)
|
|
149
|
+
counts.blocksMinted = await countSince(0);
|
|
150
|
+
return counts;
|
|
151
|
+
}
|
|
152
|
+
// Non-null when the crawled chain answers method alone. Needs a live crawler at the tip, a crawl
|
|
153
|
+
// from Shelley, and either crawler.authoritative or no backend that serves the method.
|
|
154
|
+
async crawlAnswers(tx, method) {
|
|
155
|
+
const coverage = await this.localCoverage(tx);
|
|
156
|
+
if (!coverage || coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
|
|
157
|
+
return null;
|
|
158
|
+
if (!this.crawlAuthoritative && this.client.hasBackendFor(method))
|
|
159
|
+
return null;
|
|
160
|
+
return { lastSlot: coverage.lastSlot };
|
|
161
|
+
}
|
|
162
|
+
/** 404 for a lookup the crawled chain answers on its own (the caller already missed in the DB). */
|
|
163
|
+
async refuseOutsideCrawl(tx, method, what) {
|
|
164
|
+
const coverage = await this.crawlAnswers(tx, method);
|
|
165
|
+
if (coverage)
|
|
166
|
+
throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
|
|
167
|
+
}
|
|
168
|
+
// Asset from crawled mint and burn rows. Registry fields stay null.
|
|
169
|
+
// Null when the crawled chain does not answer.
|
|
170
|
+
async localAssetInfo(tx, unit) {
|
|
171
|
+
if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
|
|
172
|
+
return null;
|
|
173
|
+
const events = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).columns('txHash', 'action', 'quantity', 'blockTime', 'blockHeight').where({ unit }));
|
|
174
|
+
if (!events?.length)
|
|
175
|
+
throw new errors_1.NotFoundError(`Asset ${unit} (never minted in the crawled chain)`);
|
|
176
|
+
const ordered = [...events].sort((a, b) => Number(a.blockHeight ?? 0) - Number(b.blockHeight ?? 0));
|
|
177
|
+
let supply = 0n;
|
|
178
|
+
for (const e of ordered)
|
|
179
|
+
supply += (e.action === 'burn' ? -1n : 1n) * BigInt(String(e.quantity ?? '0'));
|
|
180
|
+
const mints = ordered.filter(e => e.action !== 'burn');
|
|
181
|
+
const first = mints[0];
|
|
182
|
+
const latest = mints[mints.length - 1];
|
|
183
|
+
let onchainMetadata = null;
|
|
184
|
+
if (latest) {
|
|
185
|
+
const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
|
|
186
|
+
if (meta?.payload) {
|
|
187
|
+
try {
|
|
188
|
+
onchainMetadata = (0, deep_json_1.parseJson)(meta.payload);
|
|
189
|
+
}
|
|
190
|
+
catch { /* unparseable payload: leave empty */ }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const policyId = unit.slice(0, 56);
|
|
194
|
+
const assetNameHex = unit.slice(56);
|
|
195
|
+
return {
|
|
196
|
+
unit,
|
|
197
|
+
policyId,
|
|
198
|
+
assetNameHex,
|
|
199
|
+
assetName: assetNameHex ? (0, mappers_1.decodeAssetName)(assetNameHex) : null,
|
|
200
|
+
fingerprint: (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex),
|
|
201
|
+
totalSupply: supply.toString(),
|
|
202
|
+
mintOrBurnCount: ordered.length,
|
|
203
|
+
initialMintTxHash: first?.txHash ?? null,
|
|
204
|
+
initialMintTime: first?.blockTime == null ? null : Number(first.blockTime),
|
|
205
|
+
onchainMetadata,
|
|
206
|
+
registryName: null,
|
|
207
|
+
registryTicker: null,
|
|
208
|
+
registryDecimals: null,
|
|
209
|
+
registryDescription: null,
|
|
210
|
+
registryUrl: null,
|
|
211
|
+
registryLogo: null,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/** Address from the crawled UTxO set when it answers, else from the backend. */
|
|
215
|
+
async resolveAddress(tx, addr) {
|
|
216
|
+
return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
|
|
217
|
+
}
|
|
218
|
+
/** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
|
|
219
|
+
async resolveAddressUtxos(tx, addr) {
|
|
220
|
+
return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
|
|
221
|
+
}
|
|
222
|
+
/** Asset from the crawled chain when it answers, else from the backend. */
|
|
223
|
+
async resolveAssetInfo(tx, unit) {
|
|
224
|
+
return (await (0, tx_utils_1.readOutside)(tx, (db) => this.localAssetInfo(db, unit))) ?? await this.client.getAssetInfo(unit);
|
|
225
|
+
}
|
|
226
|
+
/** Stored mint/burn rows, newest first. Null when the crawled chain does not answer for them. */
|
|
227
|
+
async crawledAssetHistory(tx, unit, limit) {
|
|
228
|
+
if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetHistory')))
|
|
229
|
+
return null;
|
|
230
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc', 'txHash desc').limit(limit));
|
|
231
|
+
return rows ?? [];
|
|
232
|
+
}
|
|
233
|
+
/** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
|
|
234
|
+
async resolveAssetHistory(tx, unit, limit) {
|
|
235
|
+
const rows = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
|
|
236
|
+
if (!rows)
|
|
237
|
+
return this.client.getAssetHistory(unit, limit);
|
|
238
|
+
return rows.map(r => ({
|
|
239
|
+
unit: String(r.unit),
|
|
240
|
+
txHash: String(r.txHash),
|
|
241
|
+
action: r.action === 'burn' ? 'burn' : 'mint',
|
|
242
|
+
quantity: String(r.quantity),
|
|
243
|
+
blockTime: r.blockTime == null ? null : Number(r.blockTime),
|
|
244
|
+
blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
|
|
245
|
+
}));
|
|
246
|
+
}
|
|
247
|
+
/** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
|
|
248
|
+
async resolveCredentialUtxos(tx, credHash) {
|
|
249
|
+
return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
|
|
250
|
+
}
|
|
251
|
+
/** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
|
|
252
|
+
async resolveAddressTransactionHashes(tx, addr, limit) {
|
|
253
|
+
const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
|
|
254
|
+
if (local && (local.complete || local.rows.length >= limit)) {
|
|
255
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
return await this.client.getAddressTransactionHashes(addr, limit);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
|
|
262
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
263
|
+
}
|
|
264
|
+
throw err;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
|
|
268
|
+
async ledgerCoverageActive(tx) {
|
|
269
|
+
return Boolean((await this.localCoverage(tx))?.ledger);
|
|
270
|
+
}
|
|
271
|
+
// Address from the crawled UTxO set. An address the set never saw is empty, not an error.
|
|
272
|
+
// Null when the set cannot answer.
|
|
273
|
+
async localAddress(tx, addr) {
|
|
274
|
+
const rows = await (0, tx_utils_1.readOutside)(tx, async (db) => (await this.localCoverage(db))?.ledger ? this.ledgerUtxosOf(db, [addr]) : null);
|
|
275
|
+
if (!rows)
|
|
276
|
+
return null;
|
|
277
|
+
return addressFromUtxos(addr, await this.unspentAtNode(rows));
|
|
278
|
+
}
|
|
279
|
+
/** Addresses of a stake key in the crawled UTxO set, with their stored unspent outputs (one read for all). */
|
|
280
|
+
async ledgerAccountUtxos(tx, stakeAddress) {
|
|
281
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
|
|
282
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
283
|
+
return { addresses, utxos: addresses.length ? await this.ledgerUtxosOf(tx, addresses) : [] };
|
|
284
|
+
}
|
|
285
|
+
// Transactions that paid to or spent from the address since the anchor. complete is true when the
|
|
286
|
+
// address first appeared after the anchor, so nothing older exists. Null when the set cannot answer.
|
|
287
|
+
async localAddressTransactions(tx, addr, limit) {
|
|
288
|
+
if (!(await this.localCoverage(tx))?.ledger)
|
|
289
|
+
return null;
|
|
290
|
+
const known = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('firstSeenSlot').where({ address: addr }));
|
|
291
|
+
if (!known)
|
|
292
|
+
return { rows: [], complete: false };
|
|
293
|
+
const complete = known.firstSeenSlot != null;
|
|
294
|
+
// Candidate transactions by slot; a transaction can touch the address with several outputs.
|
|
295
|
+
const scan = Math.min(limit * 20, 2000);
|
|
296
|
+
const [created, spent] = await Promise.all([
|
|
297
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'createdSlot')
|
|
298
|
+
.where({ address: addr, createdSlot: { '>=': 0 } }).orderBy('createdSlot desc').limit(scan)),
|
|
299
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('spentTxHash', 'spentSlot')
|
|
300
|
+
.where({ address: addr, spentSlot: { '>=': 0 } }).orderBy('spentSlot desc').limit(scan)),
|
|
301
|
+
]);
|
|
302
|
+
const slotOf = new Map();
|
|
303
|
+
for (const r of created ?? [])
|
|
304
|
+
slotOf.set(r.txHash, Number(r.createdSlot));
|
|
305
|
+
for (const r of spent ?? [])
|
|
306
|
+
slotOf.set(r.spentTxHash, Number(r.spentSlot));
|
|
307
|
+
const selected = [...slotOf].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([hash]) => hash);
|
|
308
|
+
if (selected.length === 0)
|
|
309
|
+
return { rows: [], complete };
|
|
310
|
+
const [outRows, inRows] = await Promise.all([
|
|
311
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, txHash: { in: selected } })),
|
|
312
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, spentTxHash: { in: selected } })),
|
|
313
|
+
]);
|
|
314
|
+
const amounts = await this.ledgerAmounts(tx, [...(outRows ?? []), ...(inRows ?? [])]);
|
|
315
|
+
const amountOf = (r) => amounts.get(`${r.txHash}#${Number(r.outputIndex)}`) ?? [];
|
|
316
|
+
const txs = selected.map((hash) => ({
|
|
317
|
+
hash,
|
|
318
|
+
blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, slotOf.get(hash)),
|
|
319
|
+
inputs: (inRows ?? []).filter(r => r.spentTxHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
|
|
320
|
+
outputs: (outRows ?? []).filter(r => r.txHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
|
|
321
|
+
}));
|
|
322
|
+
const rows = (0, mappers_1.mapAddressTransactions)(addr, txs);
|
|
323
|
+
return { rows: sortAddressTransactions(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
|
+
// Active stake from the Ogmios snapshot of the running epoch.
|
|
341
|
+
// Empty when the crawler is not at the tip or that snapshot is missing.
|
|
342
|
+
async snapshotActiveStake(tx, poolId) {
|
|
343
|
+
const coverage = await this.localCoverage(tx);
|
|
344
|
+
if (!coverage)
|
|
345
|
+
return {};
|
|
346
|
+
const epoch = (0, epoch_slots_1.epochOfSlot)(this.client.network, coverage.lastSlot);
|
|
347
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.PoolEpochSnapshots).columns('activeStake', 'activeSize').where({ poolId, epoch, source: 'ogmios' }));
|
|
348
|
+
if (!row || row.activeStake == null)
|
|
349
|
+
return {};
|
|
350
|
+
return { activeStake: lovelaceSum(row.activeStake), activeSize: Number(row.activeSize ?? 0) };
|
|
351
|
+
}
|
|
352
|
+
// Lifetime withdrawals from crawled rows. Null unless certificates are crawled
|
|
353
|
+
// and the crawl covers the chain since Shelley.
|
|
354
|
+
async localWithdrawalsSum(tx, stakeAddress) {
|
|
355
|
+
const coverage = await this.localCoverage(tx);
|
|
356
|
+
if (!coverage || !this.crawlCertificates)
|
|
357
|
+
return null;
|
|
358
|
+
if (coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
|
|
359
|
+
return null;
|
|
360
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionWithdrawals).columns('sum(lovelace) as total').where({ stakeAddress }));
|
|
361
|
+
return lovelaceSum(row?.total);
|
|
362
|
+
}
|
|
363
|
+
/** The anchor the imported UTxO set describes (null = ledger mode inactive). */
|
|
364
|
+
setUtxoAnchor(anchor) {
|
|
365
|
+
this.utxoAnchor = anchor;
|
|
366
|
+
this.utxoAnchorVerified = false;
|
|
367
|
+
this.ledgerInvalidation = null;
|
|
368
|
+
}
|
|
369
|
+
// The imported set describes the chain at the anchor block. Before the first block past it, the
|
|
370
|
+
// cursor must equal the anchor, else the snapshot came from a fork. Skipped once a block applied.
|
|
371
|
+
async verifyUtxoAnchor(tx, anchor) {
|
|
372
|
+
const cursor = await (0, sync_state_1.readCursor)(tx);
|
|
373
|
+
if (cursor?.utxoSet.appliedSlot != null)
|
|
374
|
+
return true;
|
|
375
|
+
if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
|
|
376
|
+
return true;
|
|
377
|
+
const reason = cursor
|
|
378
|
+
? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
|
|
379
|
+
: `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
|
|
380
|
+
logger.error(`UTxO set invalidated: ${reason}. The snapshot describes a fork; re-import at the crawler cursor`);
|
|
381
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
|
|
382
|
+
this.ledgerInvalidation = reason;
|
|
383
|
+
return false;
|
|
384
|
+
}
|
|
385
|
+
/** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
|
|
386
|
+
getUtxoAnchor() {
|
|
387
|
+
return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
|
|
388
|
+
}
|
|
389
|
+
/** Apply the memo updates of the block transaction that just committed. */
|
|
390
|
+
confirmBlockCommit() {
|
|
391
|
+
const pending = this.pendingCommit;
|
|
392
|
+
this.pendingCommit = [];
|
|
393
|
+
for (const apply of pending)
|
|
394
|
+
apply();
|
|
395
|
+
}
|
|
396
|
+
/** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
|
|
397
|
+
takeLedgerInvalidation() {
|
|
398
|
+
const reason = this.ledgerInvalidation;
|
|
399
|
+
if (reason) {
|
|
400
|
+
this.ledgerInvalidation = null;
|
|
401
|
+
this.utxoAnchor = null;
|
|
402
|
+
this.utxoAnchorVerified = false;
|
|
403
|
+
}
|
|
404
|
+
return reason;
|
|
405
|
+
}
|
|
406
|
+
// Drains the queue at enrichRate units per second, each in its own transaction.
|
|
407
|
+
// A failing unit is dropped and its bare row stays for the lazy path.
|
|
408
|
+
startAssetEnrichment() {
|
|
409
|
+
if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
|
|
410
|
+
return;
|
|
411
|
+
const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
|
|
412
|
+
this.enrichTimer = setInterval(() => {
|
|
413
|
+
const unit = this.enrichQueue.shift();
|
|
414
|
+
if (unit === undefined) {
|
|
415
|
+
this.stopAssetEnrichment();
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
|
|
419
|
+
logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
|
|
420
|
+
});
|
|
421
|
+
}, intervalMs);
|
|
422
|
+
this.enrichTimer.unref?.();
|
|
423
|
+
}
|
|
424
|
+
/** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
|
|
425
|
+
stopAssetEnrichment() {
|
|
426
|
+
if (this.enrichTimer) {
|
|
427
|
+
clearInterval(this.enrichTimer);
|
|
428
|
+
this.enrichTimer = null;
|
|
429
|
+
}
|
|
430
|
+
this.enrichQueue = [];
|
|
431
|
+
}
|
|
432
|
+
// Call before opening the block write transaction, so no backend round trip
|
|
433
|
+
// runs under the DB write lock. Never throws.
|
|
52
434
|
async prefetchCrawlEpoch(epochNumber) {
|
|
53
435
|
const previousEpoch = this.crawlEpochCurrent;
|
|
54
436
|
const enteringNewEpoch = previousEpoch !== null && previousEpoch !== epochNumber;
|
|
@@ -81,96 +463,177 @@ class CardanoIndexer {
|
|
|
81
463
|
return;
|
|
82
464
|
if (!force && existing && now < existing.nextRefreshAt)
|
|
83
465
|
return;
|
|
466
|
+
const crawled = await this.crawledEpochTotals(epochNumber);
|
|
84
467
|
try {
|
|
85
|
-
const
|
|
468
|
+
const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
|
|
86
469
|
this.crawlEpochCache.set(epochNumber, {
|
|
87
|
-
row,
|
|
470
|
+
row: crawled ? { ...provided, ...crawled } : provided,
|
|
88
471
|
nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
|
|
89
472
|
finalized,
|
|
90
473
|
});
|
|
91
474
|
}
|
|
92
475
|
catch {
|
|
93
|
-
// Keep the last good snapshot, but retry transient/negative
|
|
94
|
-
// than suppressing enrichment for the rest of the five-day epoch.
|
|
476
|
+
// Keep the last good snapshot (or the crawled totals alone), but retry transient/negative
|
|
477
|
+
// results soon rather than suppressing enrichment for the rest of the five-day epoch.
|
|
478
|
+
const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
|
|
95
479
|
this.crawlEpochCache.set(epochNumber, {
|
|
96
|
-
row:
|
|
480
|
+
row: base && crawled ? { ...base, ...crawled } : base,
|
|
97
481
|
nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
|
|
98
482
|
finalized: false,
|
|
99
483
|
});
|
|
100
484
|
}
|
|
101
485
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
486
|
+
// Block, tx and fee totals from crawled blocks. Null unless the crawl covers the whole epoch.
|
|
487
|
+
// Output and active stake still come from the backend.
|
|
488
|
+
async crawledEpochTotals(epochNumber) {
|
|
489
|
+
try {
|
|
490
|
+
const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
|
|
491
|
+
if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
|
|
492
|
+
return null;
|
|
493
|
+
const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
|
|
494
|
+
.columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(slot) as firstSlot', 'max(slot) as lastSlot')
|
|
495
|
+
.where({ epochNumber }));
|
|
496
|
+
if (!row || Number(row.blockCount ?? 0) === 0)
|
|
497
|
+
return null;
|
|
498
|
+
// The slot gives the block time exactly; a time aggregate comes back in the database's own form.
|
|
499
|
+
const timeOf = (slot) => slot == null ? null : (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, Number(slot));
|
|
500
|
+
return {
|
|
501
|
+
blockCount: Number(row.blockCount),
|
|
502
|
+
txCount: Number(row.txCount ?? 0),
|
|
503
|
+
fees: lovelaceSum(row.fees),
|
|
504
|
+
firstBlockTime: timeOf(row.firstSlot),
|
|
505
|
+
lastBlockTime: timeOf(row.lastSlot),
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
catch (err) {
|
|
509
|
+
logger.debug(`Crawled totals for epoch ${epochNumber} unavailable:`, err);
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
|
|
514
|
+
bareEpochRow(epochNumber) {
|
|
515
|
+
const network = this.client.network;
|
|
516
|
+
const start = (0, epoch_slots_1.epochStartSlot)(network, epochNumber);
|
|
517
|
+
return {
|
|
518
|
+
epoch: epochNumber,
|
|
519
|
+
startTime: (0, epoch_slots_1.slotToPosixSeconds)(network, start),
|
|
520
|
+
endTime: (0, epoch_slots_1.slotToPosixSeconds)(network, (0, epoch_slots_1.epochStartSlot)(network, epochNumber + 1)),
|
|
521
|
+
output: null,
|
|
522
|
+
activeStake: null,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
// Writes block count, transaction count, fees and first and last block time of every epoch the
|
|
526
|
+
// crawl covers in full, from the stored blocks. An epoch without a row gets one. No backend.
|
|
527
|
+
async backfillEpochs(onProgress) {
|
|
528
|
+
const progress = { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
|
|
529
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
530
|
+
if (cursor?.startSlot == null)
|
|
531
|
+
return progress;
|
|
532
|
+
const network = this.client.network;
|
|
533
|
+
progress.toEpoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.lastSlot);
|
|
534
|
+
for (let epoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.startSlot); epoch <= progress.toEpoch; epoch++) {
|
|
535
|
+
const totals = await this.crawledEpochTotals(epoch);
|
|
536
|
+
if (totals) {
|
|
537
|
+
const created = await cds_1.default.tx(async (tx) => {
|
|
538
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Epoch).columns('epoch').where({ epoch }));
|
|
539
|
+
if (stored)
|
|
540
|
+
await tx.run(UPDATE.entity(CardanoODataService_1.Epoch).set(totals).where({ epoch }));
|
|
541
|
+
else
|
|
542
|
+
await tx.run(INSERT.into(CardanoODataService_1.Epoch).entries({ ...this.bareEpochRow(epoch), ...totals }));
|
|
543
|
+
return !stored;
|
|
544
|
+
});
|
|
545
|
+
if (created)
|
|
546
|
+
progress.created++;
|
|
547
|
+
else
|
|
548
|
+
progress.updated++;
|
|
549
|
+
}
|
|
550
|
+
progress.atEpoch = epoch;
|
|
551
|
+
onProgress?.({ ...progress });
|
|
552
|
+
}
|
|
553
|
+
logger.info(`epochs rebuilt from crawled blocks: ${progress.updated} updated, ${progress.created} created, up to epoch ${progress.toEpoch}`);
|
|
554
|
+
return progress;
|
|
555
|
+
}
|
|
107
556
|
constructor(client, txBuilder) {
|
|
108
557
|
this.client = client;
|
|
109
558
|
this.txBuilder = txBuilder;
|
|
559
|
+
txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
|
|
110
560
|
logger.info('CardanoIndexer instance created');
|
|
111
561
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
562
|
+
// Unspent outputs for the transaction builder. Null when the set cannot answer.
|
|
563
|
+
// Reads through the running request's transaction, which stays idle unless it already holds its connection.
|
|
564
|
+
async localAddressUtxos(address) {
|
|
565
|
+
if (!cds_1.default.db)
|
|
566
|
+
return null;
|
|
567
|
+
const tx = (cds_1.default.context ? cds_1.default.tx(cds_1.default.context) : cds_1.default.db);
|
|
568
|
+
return (await this.localAddress(tx, address))?.utxos ?? null;
|
|
569
|
+
}
|
|
570
|
+
/** A transaction from the backend. 404 when the crawled chain answers for it alone. */
|
|
571
|
+
async fetchTransaction(tx, txHash) {
|
|
572
|
+
await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getTransaction', `Transaction ${txHash}`));
|
|
573
|
+
return this.client.getTransaction(txHash);
|
|
574
|
+
}
|
|
575
|
+
/** All UPSERTs run in the caller's transaction, so everything persists or nothing does. */
|
|
576
|
+
async storeTransaction(tx, providerTx) {
|
|
123
577
|
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
124
578
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
125
|
-
logger.debug(`indexTransaction: upserted transaction ${
|
|
579
|
+
logger.debug(`indexTransaction: upserted transaction ${providerTx.hash}`);
|
|
580
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
581
|
+
return txRow;
|
|
582
|
+
}
|
|
583
|
+
/** Reads a transaction from the backend and stores it. */
|
|
584
|
+
async indexTransaction(tx, txHash) {
|
|
585
|
+
return this.storeTransaction(tx, await this.fetchTransaction(tx, txHash));
|
|
586
|
+
}
|
|
587
|
+
/** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
|
|
588
|
+
async writeTransactionChildren(tx, providerTx, txSeq) {
|
|
126
589
|
if (providerTx.inputs) {
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
if (inputRows.length) {
|
|
590
|
+
const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
|
|
591
|
+
const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
|
|
592
|
+
if (inputRows.length)
|
|
131
593
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if (inputAssetRows.length) {
|
|
135
|
-
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
|
|
136
|
-
logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
|
|
137
|
-
}
|
|
594
|
+
if (inputAssetRows.length)
|
|
595
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
|
|
138
596
|
}
|
|
139
|
-
//
|
|
140
|
-
// `inputs` previously skipped its outputs entirely)
|
|
597
|
+
// outputs must not depend on the inputs branch
|
|
141
598
|
if (providerTx.outputs) {
|
|
142
|
-
const outputRows = (0, mappers_1.mapTransactionOutputs)(
|
|
143
|
-
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(
|
|
144
|
-
if (outputRows.length)
|
|
599
|
+
const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
|
|
600
|
+
const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
|
|
601
|
+
if (outputRows.length)
|
|
145
602
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
146
|
-
|
|
147
|
-
if (outputAssetRows.length) {
|
|
603
|
+
if (outputAssetRows.length)
|
|
148
604
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
149
|
-
}
|
|
150
605
|
}
|
|
151
|
-
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
|
|
152
|
-
if (metadataRows.length)
|
|
606
|
+
const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || [], txSeq);
|
|
607
|
+
if (metadataRows.length)
|
|
153
608
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
609
|
+
}
|
|
610
|
+
// An address and its ten newest transactions, read but not stored.
|
|
611
|
+
// prefetched is address data the caller already fetched in a batch.
|
|
612
|
+
async fetchAddress(tx, addr, prefetched) {
|
|
613
|
+
const data = prefetched ?? await this.resolveAddress(tx, addr);
|
|
614
|
+
logger.debug(`indexAddress: provider response for ${addr}: ${data.amount?.length ?? 0} amounts, ${data.utxos?.length ?? 0} utxos`);
|
|
615
|
+
let transactions = null;
|
|
616
|
+
try {
|
|
617
|
+
transactions = await this.fetchAddressTransactions(tx, addr, 10);
|
|
154
618
|
}
|
|
155
|
-
|
|
619
|
+
catch (err) {
|
|
620
|
+
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
621
|
+
}
|
|
622
|
+
return { address: addr, data, transactions };
|
|
623
|
+
}
|
|
624
|
+
/** Reads an address and its newest transactions, then stores them. */
|
|
625
|
+
async indexAddress(tx, addr, prefetched) {
|
|
626
|
+
return this.storeAddress(tx, await this.fetchAddress(tx, addr, prefetched));
|
|
156
627
|
}
|
|
157
|
-
/**
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
* @param tx CAP transaction
|
|
161
|
-
* @param addr bech32 address
|
|
162
|
-
* @return {Promise<Address>} address entity data
|
|
163
|
-
*/
|
|
164
|
-
async indexAddress(tx, addr) {
|
|
165
|
-
const addrData = await this.client.getAddress(addr);
|
|
166
|
-
logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
|
|
628
|
+
/** Stores what fetchAddress read: the address, its assets, UTxOs and newest transactions. */
|
|
629
|
+
async storeAddress(tx, fetched) {
|
|
630
|
+
const { address: addr, data: addrData } = fetched;
|
|
167
631
|
const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
|
|
168
632
|
const now = new Date().toISOString();
|
|
169
633
|
const validFrom = AddrEntity.validFrom ?? now;
|
|
170
634
|
const validTo = AddrEntity.validTo ?? now;
|
|
171
635
|
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
|
|
636
|
+
// Supplement address-level amounts with assets only present in UTxOs
|
|
174
637
|
const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
|
|
175
638
|
for (const utxo of addrData.utxos) {
|
|
176
639
|
for (const amt of utxo.amount) {
|
|
@@ -206,39 +669,38 @@ class CardanoIndexer {
|
|
|
206
669
|
logger.debug(`indexAddress: ${utxoAssetEntities.length} assets, ${uniqueAssets.length} unique (removed ${utxoAssetEntities.length - uniqueAssets.length} duplicates)`);
|
|
207
670
|
await tx.run(UPSERT.into(CardanoODataService_1.UTxOAssets).entries(uniqueAssets));
|
|
208
671
|
}
|
|
209
|
-
//
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
672
|
+
// Recent transactions are always stored with the address (regardless of asset presence)
|
|
673
|
+
if (fetched.transactions) {
|
|
674
|
+
try {
|
|
675
|
+
const txEntities = await this.storeAddressTransactions(tx, fetched.transactions);
|
|
676
|
+
if (txEntities.length > 0) {
|
|
677
|
+
await tx.run(UPDATE.entity(CardanoODataService_1.Addresses).set({ hasTransactions: true }).where({ address: addr }));
|
|
678
|
+
AddrEntity.hasTransactions = true;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
catch (err) {
|
|
682
|
+
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
215
683
|
}
|
|
216
|
-
}
|
|
217
|
-
catch (err) {
|
|
218
|
-
logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
|
|
219
684
|
}
|
|
220
685
|
return AddrEntity;
|
|
221
686
|
}
|
|
222
|
-
/**
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
|
234
|
-
*/
|
|
687
|
+
/** UTxOs of a payment credential, always fresh: the crawled set when it answers, else the backend. */
|
|
688
|
+
async fetchCredentialUtxos(tx, credHash) {
|
|
689
|
+
const local = await this.localCredentialUtxos(tx, credHash);
|
|
690
|
+
const utxos = local ?? await this.client.getCredentialUtxos(credHash);
|
|
691
|
+
logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
|
|
692
|
+
return utxos;
|
|
693
|
+
}
|
|
694
|
+
/** Reads the UTxOs of a payment credential and stores them. */
|
|
235
695
|
async indexCredentialUtxos(tx, credHash) {
|
|
236
|
-
|
|
237
|
-
|
|
696
|
+
return this.storeCredentialUtxos(tx, await this.fetchCredentialUtxos(tx, credHash));
|
|
697
|
+
}
|
|
698
|
+
/** Stores credential UTxOs. Rows are written without a parent Addresses row. */
|
|
699
|
+
async storeCredentialUtxos(tx, utxos) {
|
|
238
700
|
if (utxos.length === 0)
|
|
239
701
|
return [];
|
|
240
|
-
//
|
|
241
|
-
//
|
|
702
|
+
// Koios returns UTxOs of every address form sharing the credential.
|
|
703
|
+
// mapAddressUtxos keys rows by address, so group them first.
|
|
242
704
|
const byAddress = new Map();
|
|
243
705
|
for (const u of utxos) {
|
|
244
706
|
const list = byAddress.get(u.address) ?? [];
|
|
@@ -270,21 +732,107 @@ class CardanoIndexer {
|
|
|
270
732
|
logger.debug(`indexCredentialUtxos: indexed ${allRows.length} utxos across ${byAddress.size} addresses`);
|
|
271
733
|
return allRows;
|
|
272
734
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
735
|
+
// Credential UTxOs from the crawled set. Null when the set cannot answer yet.
|
|
736
|
+
// An address first used in the last confirmationDepth blocks is not in the set yet.
|
|
737
|
+
async localCredentialUtxos(tx, credHash) {
|
|
738
|
+
const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
739
|
+
if (!(await this.localCoverage(db))?.ledger || !(await this.paymentCredentialsReady()))
|
|
740
|
+
return null;
|
|
741
|
+
const rows = await db.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
|
|
742
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
743
|
+
return addresses.length ? this.ledgerUtxosOf(db, addresses) : [];
|
|
744
|
+
});
|
|
745
|
+
if (!stored)
|
|
746
|
+
return null;
|
|
747
|
+
return this.unspentAtNode(stored);
|
|
748
|
+
}
|
|
749
|
+
// Crawled outputs checked against the node by output reference, to drop what was spent after
|
|
750
|
+
// the cursor. The node's address query would scan its whole UTxO set. Falls back to the set as is.
|
|
751
|
+
async unspentAtNode(rows) {
|
|
752
|
+
if (rows.length === 0)
|
|
753
|
+
return rows;
|
|
754
|
+
try {
|
|
755
|
+
const unspent = new Map();
|
|
756
|
+
for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
|
|
757
|
+
const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
|
|
758
|
+
if (live === null)
|
|
759
|
+
return rows;
|
|
760
|
+
for (const u of live)
|
|
761
|
+
unspent.set(`${u.txHash}#${u.outputIndex}`, u);
|
|
762
|
+
}
|
|
763
|
+
// The node's answer names the reference script, which a snapshot row from a file import lacks
|
|
764
|
+
return rows.flatMap(u => {
|
|
765
|
+
const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
|
|
766
|
+
if (!live)
|
|
767
|
+
return [];
|
|
768
|
+
return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
catch (err) {
|
|
772
|
+
logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
|
|
773
|
+
return rows;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
/** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
|
|
777
|
+
async ledgerUtxosOf(tx, addresses) {
|
|
778
|
+
const out = [];
|
|
779
|
+
for (const addrChunk of (0, collections_1.chunk)(addresses, collections_1.IN_CHUNK)) {
|
|
780
|
+
const utxos = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: { in: addrChunk }, spentTxHash: null }));
|
|
781
|
+
const amounts = await this.ledgerAmounts(tx, utxos ?? []);
|
|
782
|
+
for (const u of utxos ?? []) {
|
|
783
|
+
const txHash = String(u.txHash);
|
|
784
|
+
const outputIndex = Number(u.outputIndex);
|
|
785
|
+
out.push({
|
|
786
|
+
txHash,
|
|
787
|
+
outputIndex,
|
|
788
|
+
address: String(u.address),
|
|
789
|
+
amount: amounts.get(`${txHash}#${outputIndex}`) ?? [],
|
|
790
|
+
blockHash: '',
|
|
791
|
+
datumHash: u.utxo_dataHash ?? undefined,
|
|
792
|
+
inlineDatum: u.utxo_inlineDatum ?? null,
|
|
793
|
+
scriptRef: u.utxo_referenceScriptHash ?? undefined,
|
|
794
|
+
scriptRefSize: u.utxo_referenceScriptSize == null ? null : Number(u.utxo_referenceScriptSize),
|
|
795
|
+
scriptRefType: u.utxo_referenceScriptType ?? null,
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return out;
|
|
800
|
+
}
|
|
801
|
+
// True once every Shelley address row has its payment credential.
|
|
802
|
+
// Until then a background fill runs and callers use the provider.
|
|
803
|
+
async paymentCredentialsReady() {
|
|
804
|
+
if (this.credentialsReady)
|
|
805
|
+
return true;
|
|
806
|
+
if (!this.credentialFill) {
|
|
807
|
+
const generation = this.credentialGeneration;
|
|
808
|
+
this.credentialFill = (0, ledger_state_1.backfillPaymentCredentials)()
|
|
809
|
+
.then((n) => {
|
|
810
|
+
if (generation !== this.credentialGeneration)
|
|
811
|
+
return;
|
|
812
|
+
this.credentialsReady = true;
|
|
813
|
+
if (n > 0)
|
|
814
|
+
logger.info(`payment credentials filled for ${n} ledger addresses`);
|
|
815
|
+
})
|
|
816
|
+
.catch((err) => logger.error('payment credential fill failed (retried on the next lookup):', err))
|
|
817
|
+
.finally(() => { this.credentialFill = null; });
|
|
818
|
+
}
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
/** The ledger tables were replaced (re-import): the credential column has to be filled again. */
|
|
822
|
+
resetPaymentCredentials() {
|
|
823
|
+
this.credentialGeneration++;
|
|
824
|
+
this.credentialsReady = false;
|
|
825
|
+
}
|
|
826
|
+
// Skips getAddress, so it works on backends without address aggregation such as Ogmios.
|
|
286
827
|
async indexAddressUtxos(tx, addr) {
|
|
287
|
-
|
|
828
|
+
return this.storeAddressUtxos(tx, addr, await this.fetchAddressUtxos(addr));
|
|
829
|
+
}
|
|
830
|
+
/** The UTxOs of an address from the backend. */
|
|
831
|
+
async fetchAddressUtxos(addr) {
|
|
832
|
+
return this.client.getAddressUtxos(addr);
|
|
833
|
+
}
|
|
834
|
+
/** Stores the UTxOs of an address. Writes no parent Addresses row. */
|
|
835
|
+
async storeAddressUtxos(tx, addr, utxos) {
|
|
288
836
|
logger.debug(`indexAddressUtxos: provider returned ${utxos.length} utxos for ${addr}`);
|
|
289
837
|
const validFrom = new Date().toISOString();
|
|
290
838
|
const validTo = new Date(Date.now() + this.client.max_age_ms).toISOString();
|
|
@@ -306,23 +854,8 @@ class CardanoIndexer {
|
|
|
306
854
|
}
|
|
307
855
|
return utxoEntities;
|
|
308
856
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
* refetches instead of serving spent UTxOs for up to indexTtlMs:
|
|
312
|
-
* - every consumed input ref (spent under WHATEVER address cached it),
|
|
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
|
|
325
|
-
*/
|
|
857
|
+
// Evicts cached rows a submitted tx made stale: its spent inputs and its output addresses.
|
|
858
|
+
// A lagging backend may still return the old state on refetch.
|
|
326
859
|
async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
|
|
327
860
|
const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
|
|
328
861
|
for (const address of addresses) {
|
|
@@ -339,28 +872,50 @@ class CardanoIndexer {
|
|
|
339
872
|
logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
|
|
340
873
|
}
|
|
341
874
|
}
|
|
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
|
-
*/
|
|
875
|
+
/** Index address transactions (separate from indexAddress for lazy loading). */
|
|
349
876
|
async indexAddressTransactions(tx, addr, limit) {
|
|
877
|
+
return this.storeAddressTransactions(tx, await this.fetchAddressTransactions(tx, addr, limit));
|
|
878
|
+
}
|
|
879
|
+
// The newest transactions of an address, read but not stored.
|
|
880
|
+
// Rows this address already has stay as stored; only new hashes are fetched.
|
|
881
|
+
async fetchAddressTransactions(tx, addr, limit) {
|
|
350
882
|
logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
|
|
351
|
-
|
|
352
|
-
const
|
|
883
|
+
const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
|
|
884
|
+
const keepLocal = () => ({ rows: local.rows, newRows: local.rows, transactions: new Map() });
|
|
885
|
+
if (local && (local.complete || local.rows.length >= limit))
|
|
886
|
+
return keepLocal();
|
|
887
|
+
// Hash-only listing (one API call)
|
|
888
|
+
let txHashes;
|
|
889
|
+
try {
|
|
890
|
+
txHashes = await this.client.getAddressTransactionHashes(addr, limit);
|
|
891
|
+
}
|
|
892
|
+
catch (err) {
|
|
893
|
+
// No backend with address history: what the crawled set holds is the best answer there is.
|
|
894
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError))
|
|
895
|
+
return keepLocal();
|
|
896
|
+
throw err;
|
|
897
|
+
}
|
|
353
898
|
logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
|
|
354
899
|
if (txHashes.length === 0)
|
|
355
|
-
return [];
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
900
|
+
return { rows: [], newRows: [], transactions: new Map() };
|
|
901
|
+
const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
902
|
+
const known = await db.run(SELECT.from(CardanoODataService_1.AddressTransactions).where({ address_address: addr, tx_hash: { in: txHashes } })) ?? [];
|
|
903
|
+
const knownHashes = new Set(known.map(r => r.tx_hash));
|
|
904
|
+
const newHashes = txHashes.filter(h => !knownHashes.has(h));
|
|
905
|
+
return { known, newHashes, unstored: newHashes.length ? await this.unstoredTransactionHashes(db, newHashes) : [] };
|
|
906
|
+
});
|
|
907
|
+
const { known, newHashes } = stored;
|
|
908
|
+
if (!newHashes.length)
|
|
909
|
+
return { rows: sortAddressTransactions(known), newRows: [], transactions: new Map() };
|
|
910
|
+
const transactions = stored.unstored.length
|
|
911
|
+
? await this.client.getTransactionsBatch(stored.unstored)
|
|
912
|
+
: new Map();
|
|
913
|
+
// The net amounts need the inputs and outputs of every new transaction.
|
|
914
|
+
// A transaction that is stored already is read again, but not written.
|
|
360
915
|
const allTxData = [];
|
|
361
916
|
const missingFromBatch = [];
|
|
362
|
-
for (const hash of
|
|
363
|
-
const fromBatch =
|
|
917
|
+
for (const hash of newHashes) {
|
|
918
|
+
const fromBatch = transactions.get(hash);
|
|
364
919
|
if (fromBatch) {
|
|
365
920
|
allTxData.push(fromBatch);
|
|
366
921
|
}
|
|
@@ -376,172 +931,310 @@ class CardanoIndexer {
|
|
|
376
931
|
allTxData.push(providerTx);
|
|
377
932
|
}
|
|
378
933
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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
|
-
*/
|
|
934
|
+
const newRows = (0, mappers_1.mapAddressTransactions)(addr, allTxData);
|
|
935
|
+
logger.debug({ count: newRows.length }, 'indexAddressTransactions: transaction entities');
|
|
936
|
+
return { rows: sortAddressTransactions([...known, ...newRows]), newRows, transactions };
|
|
937
|
+
}
|
|
938
|
+
// Stores what fetchAddressTransactions read and returns the rows to answer with.
|
|
939
|
+
// No TTL, because a row per address and confirmed tx never changes.
|
|
940
|
+
async storeAddressTransactions(tx, fetched) {
|
|
941
|
+
await this.storeTransactions(tx, fetched.transactions);
|
|
942
|
+
if (fetched.newRows.length)
|
|
943
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(fetched.newRows));
|
|
944
|
+
return fetched.rows;
|
|
945
|
+
}
|
|
946
|
+
/** Link an address to a signing request for address-based queries. */
|
|
398
947
|
async indexAddressSigningRequests(tx, addr, signingRequestId) {
|
|
399
948
|
logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
|
|
400
949
|
const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
|
|
401
950
|
await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
|
|
402
951
|
logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
|
|
403
952
|
}
|
|
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
|
-
*/
|
|
953
|
+
/** Link an address to a transaction build for address-based queries. */
|
|
412
954
|
async indexAddressTransactionBuilds(tx, addr, buildId) {
|
|
413
955
|
logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
|
|
414
956
|
const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
|
|
415
957
|
await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
|
|
416
958
|
logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
|
|
417
959
|
}
|
|
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
|
-
*/
|
|
960
|
+
/** Index the metadata rows of a transaction. */
|
|
425
961
|
async indexTransactionMetadata(tx, tx_hash) {
|
|
426
|
-
|
|
427
|
-
|
|
962
|
+
return this.storeTransactionMetadata(tx, await this.fetchTransactionMetadata(tx, tx_hash));
|
|
963
|
+
}
|
|
964
|
+
/** Metadata of a transaction from the backend. Null when the transaction is known to have none. */
|
|
965
|
+
async fetchTransactionMetadata(tx, tx_hash) {
|
|
966
|
+
const isStored = (db) => db.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
|
|
967
|
+
// A crawled transaction without metadata rows has no metadata.
|
|
968
|
+
const crawledWithout = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
969
|
+
if (!(await this.crawlAnswers(db, 'getTransactionMetadata')))
|
|
970
|
+
return false;
|
|
971
|
+
if (await isStored(db))
|
|
972
|
+
return true;
|
|
973
|
+
await this.refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${tx_hash}`);
|
|
974
|
+
return false;
|
|
975
|
+
});
|
|
976
|
+
if (crawledWithout)
|
|
977
|
+
return null;
|
|
978
|
+
try {
|
|
979
|
+
return { txHash: tx_hash, metadata: await this.client.getTransactionMetadata(tx_hash) };
|
|
980
|
+
}
|
|
981
|
+
catch (err) {
|
|
982
|
+
// providers answer "not found" for a transaction without metadata; a stored transaction has none
|
|
983
|
+
if ((0, errors_1.isNotFoundOnAllBackends)(err) && await (0, tx_utils_1.readOutside)(tx, isStored))
|
|
984
|
+
return null;
|
|
985
|
+
throw err;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
/** Stores the metadata rows of a transaction and returns them. */
|
|
989
|
+
async storeTransactionMetadata(tx, fetched) {
|
|
990
|
+
if (!fetched)
|
|
991
|
+
return [];
|
|
992
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('txSeq').where({ hash: fetched.txHash }));
|
|
993
|
+
const rows = (0, mappers_1.mapTransactionMetadata)(fetched.metadata, stored?.txSeq == null ? null : Number(stored.txSeq));
|
|
428
994
|
if (rows.length) {
|
|
429
995
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(rows));
|
|
430
996
|
}
|
|
431
997
|
return rows;
|
|
432
998
|
}
|
|
433
|
-
/**
|
|
434
|
-
* Index & return the network information data
|
|
435
|
-
* @param tx CAP transaction object
|
|
436
|
-
* @returns {Promise<NetworkInformation>} network information entity data
|
|
437
|
-
*/
|
|
999
|
+
/** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
|
|
438
1000
|
async indexNetworkInformation(tx) {
|
|
439
|
-
|
|
440
|
-
|
|
1001
|
+
return this.storeNetworkInformation(tx, await this.fetchNetworkInformation(tx));
|
|
1002
|
+
}
|
|
1003
|
+
/** The network information row, read but not stored. */
|
|
1004
|
+
async fetchNetworkInformation(tx) {
|
|
1005
|
+
return (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
|
|
1006
|
+
}
|
|
1007
|
+
async storeNetworkInformation(tx, netEntity) {
|
|
441
1008
|
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
442
1009
|
return netEntity;
|
|
443
1010
|
}
|
|
444
|
-
/**
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
1011
|
+
/** Network information from the backend; circulating supply from the crawled UTxO set when current. */
|
|
1012
|
+
async resolveNetworkInformation(tx) {
|
|
1013
|
+
const netInfo = await this.client.getNetworkInformation();
|
|
1014
|
+
const circulating = (await this.localCoverage(tx))?.ledger
|
|
1015
|
+
? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
|
|
1016
|
+
: null;
|
|
1017
|
+
return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
|
|
1018
|
+
}
|
|
1019
|
+
/** Index a block by hash, with best-effort epoch enrichment. */
|
|
450
1020
|
async indexBlock(tx, blockHash) {
|
|
451
|
-
|
|
452
|
-
|
|
1021
|
+
return this.storeBlock(tx, await this.fetchBlock(tx, blockHash));
|
|
1022
|
+
}
|
|
1023
|
+
/** A block and its epoch from the backend. 404 when the crawled chain answers for it alone. */
|
|
1024
|
+
async fetchBlock(tx, blockHash) {
|
|
1025
|
+
await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getBlock', `Block ${blockHash}`));
|
|
1026
|
+
return this.withEpoch(await this.client.getBlock(blockHash));
|
|
1027
|
+
}
|
|
1028
|
+
async withEpoch(block) {
|
|
453
1029
|
try {
|
|
454
|
-
epoch
|
|
1030
|
+
return { block, epoch: (0, mappers_1.mapEpoch)(await this.client.getEpoch(block.epoch)) };
|
|
455
1031
|
}
|
|
456
1032
|
catch {
|
|
457
1033
|
// Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
|
|
1034
|
+
return { block };
|
|
458
1035
|
}
|
|
459
|
-
|
|
1036
|
+
}
|
|
1037
|
+
/** Stores a block and, when it was read, its epoch. */
|
|
1038
|
+
async storeBlock(tx, fetched) {
|
|
1039
|
+
if (fetched.epoch)
|
|
1040
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([fetched.epoch]));
|
|
1041
|
+
const blockEntity = (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
|
|
460
1042
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
|
|
461
1043
|
return blockEntity;
|
|
462
1044
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
* v2.0). Unlike indexTransaction()/indexBlock() this does NOT re-fetch per hash — the
|
|
466
|
-
* crawler already carries the block + full tx list from the stream/page. Rows are
|
|
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)
|
|
481
|
-
*/
|
|
1045
|
+
// Indexes a whole block for the crawler with one UPSERT per table in the caller's transaction.
|
|
1046
|
+
// The block persists atomically. resolveInputs() fills bare chain-sync inputs first.
|
|
482
1047
|
async indexBlockFull(tx, blockData, txs) {
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
// if the caller skipped
|
|
1048
|
+
// Memo updates of a rolled-back attempt must not survive into this one.
|
|
1049
|
+
this.pendingCommit = [];
|
|
1050
|
+
// Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
|
|
1051
|
+
// (memoized) and accept the in-tx fetch.
|
|
486
1052
|
let epoch;
|
|
487
1053
|
if (blockData.epoch != null) {
|
|
488
1054
|
await this.prefetchCrawlEpoch(blockData.epoch);
|
|
489
1055
|
epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
|
|
490
1056
|
const epochRows = [...this.crawlEpochCache.values()]
|
|
491
1057
|
.map((entry) => entry.row)
|
|
492
|
-
.filter((row) => row !== undefined);
|
|
493
|
-
if (epochRows.length)
|
|
1058
|
+
.filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
|
|
1059
|
+
if (epochRows.length) {
|
|
494
1060
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
1061
|
+
this.pendingCommit.push(() => { for (const row of epochRows)
|
|
1062
|
+
this.crawlEpochWritten.add(row); });
|
|
1063
|
+
}
|
|
495
1064
|
}
|
|
1065
|
+
// Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
|
|
1066
|
+
// Decided up front so input resolution and the ledger apply share one read of the set.
|
|
1067
|
+
const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
|
|
1068
|
+
const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
|
|
1069
|
+
let anchorVerified = false;
|
|
1070
|
+
if (ledgerDue && !priorInvalidation) {
|
|
1071
|
+
anchorVerified = this.utxoAnchorVerified;
|
|
1072
|
+
if (!anchorVerified) {
|
|
1073
|
+
const anchor = this.utxoAnchor;
|
|
1074
|
+
anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
|
|
1075
|
+
// Remembered only once this transaction commits, like the other crawl memos.
|
|
1076
|
+
if (anchorVerified)
|
|
1077
|
+
this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
|
|
1078
|
+
this.utxoAnchorVerified = true; });
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
const ledgerLookup = anchorVerified
|
|
1082
|
+
? { hashes: new Set(), rows: new Map(), assets: new Map() }
|
|
1083
|
+
: undefined;
|
|
1084
|
+
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
1085
|
+
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
1086
|
+
// corrected fee changes the block's fee total.
|
|
1087
|
+
await this.resolveInputs(tx, txs, ledgerLookup);
|
|
1088
|
+
// an input without a copy reads its assets from its output, so every stored output must be found
|
|
1089
|
+
const byReference = !this.crawlInputAssetCopies;
|
|
1090
|
+
if (byReference)
|
|
1091
|
+
await this.referenceStoredOutputs(tx, txs);
|
|
1092
|
+
this.applyCollateralFees(blockData, txs);
|
|
1093
|
+
this.applyDeposits(txs);
|
|
496
1094
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
//
|
|
1095
|
+
await this.removeStaleTxSeqs(tx, txs);
|
|
1096
|
+
// One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
|
|
1097
|
+
// srv/utils/db-sanitize.ts, not per call site.
|
|
500
1098
|
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.
|
|
505
|
-
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
|
|
1099
|
+
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
|
|
1100
|
+
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
|
|
1101
|
+
const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
1102
|
+
const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
|
|
1103
|
+
const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? [], (0, mappers_1.txSeqOf)(t.slot, t.index)));
|
|
1104
|
+
// Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
|
|
1105
|
+
// re-crawl is idempotent and a reorg removes them with their tx.
|
|
1106
|
+
const certificateRows = this.crawlCertificates
|
|
1107
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
|
|
1108
|
+
: [];
|
|
1109
|
+
const withdrawalRows = this.crawlCertificates
|
|
1110
|
+
? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
|
|
1111
|
+
: [];
|
|
1112
|
+
if (this.crawlCertificates)
|
|
1113
|
+
this.warnIfCertificatesUnreported(txs);
|
|
1114
|
+
// Redeemers and witness datums come with the block on chain-sync; keyed by tx like the certificates.
|
|
1115
|
+
const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
|
|
1116
|
+
const datumRows = txs.flatMap(t => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
|
|
1117
|
+
// Mint and burn rows are keyed by unit and tx, so a re-crawl is idempotent.
|
|
1118
|
+
// A reorg removes them with their transactions.
|
|
1119
|
+
const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
|
|
506
1120
|
if (txRows.length)
|
|
507
1121
|
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
|
|
508
1122
|
if (inputRows.length)
|
|
509
1123
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
|
|
510
1124
|
if (inputAssetRows.length)
|
|
511
|
-
await tx.run(UPSERT.into(
|
|
1125
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
|
|
512
1126
|
if (outputRows.length)
|
|
513
1127
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
|
|
514
1128
|
if (outputAssetRows.length)
|
|
515
1129
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
|
|
516
1130
|
if (metadataRows.length)
|
|
517
1131
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
1132
|
+
if (certificateRows.length)
|
|
1133
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
|
|
1134
|
+
if (withdrawalRows.length)
|
|
1135
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
|
|
1136
|
+
if (redeemerRows.length)
|
|
1137
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
|
|
1138
|
+
if (datumRows.length)
|
|
1139
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionDatums).entries(datumRows));
|
|
1140
|
+
// after the transactions moved here, so a rolled-back block they pointed at is no longer kept
|
|
1141
|
+
await this.removeSupersededBlocks(tx, blockData);
|
|
1142
|
+
// Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
|
|
1143
|
+
if (ledgerDue) {
|
|
1144
|
+
if (priorInvalidation) {
|
|
1145
|
+
// Decided in an earlier attempt of this block whose transaction rolled back: re-write
|
|
1146
|
+
// the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
|
|
1147
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
|
|
1148
|
+
}
|
|
1149
|
+
else if (ledgerLookup) {
|
|
1150
|
+
const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
|
|
1151
|
+
if (ledger.missing) {
|
|
1152
|
+
logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row: ` +
|
|
1153
|
+
'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (assetHistoryRows.length)
|
|
1158
|
+
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
|
|
1159
|
+
// Catalogue last; collecting the units is skipped entirely when the catalogue is off.
|
|
1160
|
+
const newAssets = this.crawlAssetCatalogue === 'off'
|
|
1161
|
+
? 0
|
|
1162
|
+
: await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
|
|
1163
|
+
// A reference NFT moved or minted in this block carries the current CIP-68 metadata of its token.
|
|
1164
|
+
await (0, asset_decimals_1.applyReferenceDatums)(tx, txs);
|
|
1165
|
+
logger.debug(`indexBlockFull: block ${blockData.hash}: ${txs.length} txs, ${outputRows.length} outputs, ` +
|
|
1166
|
+
`${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
|
|
1167
|
+
}
|
|
1168
|
+
// Drops unreferenced Block rows at the same height. They are lazily indexed tips
|
|
1169
|
+
// that were rolled back, which no crawler reorg covers.
|
|
1170
|
+
async removeSupersededBlocks(tx, blockData) {
|
|
1171
|
+
if (blockData.height == null)
|
|
1172
|
+
return;
|
|
1173
|
+
const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
|
|
1174
|
+
if (!others?.length)
|
|
1175
|
+
return;
|
|
1176
|
+
const hashes = others.map(r => r.hash);
|
|
1177
|
+
const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
|
|
1178
|
+
const keep = new Set((referenced ?? []).map(r => r.blockHash));
|
|
1179
|
+
const stale = hashes.filter(h => !keep.has(h));
|
|
1180
|
+
if (!stale.length)
|
|
1181
|
+
return;
|
|
1182
|
+
await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
|
|
1183
|
+
logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
|
|
1184
|
+
}
|
|
1185
|
+
// Drops transactions of another fork that hold one of this block's txSeq keys.
|
|
1186
|
+
// Their input and output rows would mix with ours.
|
|
1187
|
+
async removeStaleTxSeqs(tx, txs) {
|
|
1188
|
+
if (!txs.length)
|
|
1189
|
+
return;
|
|
1190
|
+
const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
1191
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
|
|
1192
|
+
.where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
|
|
1193
|
+
const ours = new Set(txs.map(t => t.hash));
|
|
1194
|
+
const stale = (rows ?? []).filter(r => !ours.has(r.hash));
|
|
1195
|
+
if (!stale.length)
|
|
1196
|
+
return;
|
|
1197
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
|
|
1198
|
+
logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
|
|
1199
|
+
}
|
|
1200
|
+
// Warns once when certificates are on but the source does not report them.
|
|
1201
|
+
// An empty array means none and is no warning.
|
|
1202
|
+
warnIfCertificatesUnreported(txs) {
|
|
1203
|
+
if (this.certificatesUnreportedWarned || !txs.length)
|
|
1204
|
+
return;
|
|
1205
|
+
if (txs.some(t => t.certificates !== undefined))
|
|
1206
|
+
return;
|
|
1207
|
+
this.certificatesUnreportedWarned = true;
|
|
1208
|
+
logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
|
|
1209
|
+
'(Blockfrost pagination). TransactionCertificates/TransactionWithdrawals stay empty until ' +
|
|
1210
|
+
'the crawl runs on Ogmios chain-sync or Koios');
|
|
1211
|
+
}
|
|
1212
|
+
// Fills bare chain-sync inputs from this block's outputs, then the UTxO set, then the DB.
|
|
1213
|
+
// Inputs that already carry an address are skipped.
|
|
1214
|
+
async resolveInputs(tx, txs, ledger) {
|
|
1215
|
+
// 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
|
|
528
1216
|
const blockOutputs = new Map();
|
|
1217
|
+
const blockSeqs = new Map();
|
|
529
1218
|
for (const t of txs) {
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
1219
|
+
blockSeqs.set(t.hash, (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
1220
|
+
for (const o of t.outputs ?? [])
|
|
1221
|
+
blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
|
|
533
1222
|
}
|
|
534
1223
|
// 2. Collect inputs still needing resolution after the same-block pass
|
|
535
1224
|
const unresolved = [];
|
|
536
1225
|
for (const t of txs) {
|
|
537
1226
|
for (const input of t.inputs ?? []) {
|
|
538
|
-
if (input.address)
|
|
539
|
-
continue; // already resolved by the backend (Blockfrost/Koios)
|
|
540
1227
|
const key = `${input.txHash}#${input.outputIndex}`;
|
|
541
1228
|
const local = blockOutputs.get(key);
|
|
1229
|
+
// an output of this block is stored with it
|
|
1230
|
+
if (local)
|
|
1231
|
+
input.spentTxSeq = blockSeqs.get(input.txHash) ?? null;
|
|
1232
|
+
if (input.address)
|
|
1233
|
+
continue; // already resolved by the backend (Blockfrost/Koios)
|
|
542
1234
|
if (local) {
|
|
543
1235
|
input.address = local.address;
|
|
544
|
-
input.amount = local.amount;
|
|
1236
|
+
input.amount = local.amount ?? [];
|
|
1237
|
+
copyUtxoData(input, utxoDataOf(local));
|
|
545
1238
|
}
|
|
546
1239
|
else {
|
|
547
1240
|
unresolved.push({ input, key });
|
|
@@ -550,130 +1243,522 @@ class CardanoIndexer {
|
|
|
550
1243
|
}
|
|
551
1244
|
if (!unresolved.length)
|
|
552
1245
|
return;
|
|
553
|
-
// 3.
|
|
554
|
-
//
|
|
555
|
-
|
|
1246
|
+
// 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
|
|
1247
|
+
// reuses the same lookup instead of reading these outpoints a second time.
|
|
1248
|
+
if (ledger) {
|
|
1249
|
+
await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
|
|
1250
|
+
for (let i = unresolved.length - 1; i >= 0; i--) {
|
|
1251
|
+
const row = ledger.rows.get(unresolved[i].key);
|
|
1252
|
+
if (!row)
|
|
1253
|
+
continue;
|
|
1254
|
+
unresolved[i].input.address = row.address;
|
|
1255
|
+
unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
|
|
1256
|
+
copyUtxoData(unresolved[i].input, row);
|
|
1257
|
+
unresolved.splice(i, 1);
|
|
1258
|
+
}
|
|
1259
|
+
if (!unresolved.length)
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
// 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
|
|
1263
|
+
// never exceeds a driver's bind-variable cap
|
|
556
1264
|
const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
|
|
557
|
-
const
|
|
1265
|
+
const hashBySeq = new Map();
|
|
1266
|
+
for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
|
|
1267
|
+
if (k.txSeq != null)
|
|
1268
|
+
hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
|
|
1269
|
+
}
|
|
1270
|
+
const outByKey = new Map();
|
|
558
1271
|
const amtByKey = new Map();
|
|
559
|
-
for (const
|
|
1272
|
+
for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
|
|
560
1273
|
const [outRows, assetRows] = await Promise.all([
|
|
561
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({
|
|
562
|
-
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({
|
|
1274
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
|
|
1275
|
+
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
|
|
563
1276
|
]);
|
|
564
1277
|
for (const r of outRows) {
|
|
565
|
-
|
|
1278
|
+
outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
|
|
566
1279
|
}
|
|
567
1280
|
for (const r of assetRows) {
|
|
568
|
-
const k = `${r.
|
|
1281
|
+
const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
|
|
569
1282
|
const list = amtByKey.get(k) ?? [];
|
|
570
1283
|
list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
|
|
571
1284
|
amtByKey.set(k, list);
|
|
572
1285
|
}
|
|
573
1286
|
}
|
|
574
1287
|
for (const { input, key } of unresolved) {
|
|
575
|
-
const
|
|
576
|
-
if (
|
|
577
|
-
input.address =
|
|
1288
|
+
const out = outByKey.get(key);
|
|
1289
|
+
if (out?.address_address != null)
|
|
1290
|
+
input.address = out.address_address;
|
|
1291
|
+
if (out) {
|
|
1292
|
+
copyUtxoData(input, out);
|
|
1293
|
+
input.spentTxSeq = Number(out.txSeq);
|
|
1294
|
+
}
|
|
578
1295
|
const amt = amtByKey.get(key);
|
|
579
1296
|
if (amt)
|
|
580
1297
|
input.amount = amt;
|
|
581
1298
|
}
|
|
582
1299
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
1300
|
+
// Marks the inputs whose spent output is stored from an earlier block, so they can point at it.
|
|
1301
|
+
async referenceStoredOutputs(tx, txs) {
|
|
1302
|
+
const open = txs.flatMap(t => t.inputs ?? []).filter(i => i.spentTxSeq == null && i.txHash);
|
|
1303
|
+
if (!open.length)
|
|
1304
|
+
return;
|
|
1305
|
+
const seqByHash = new Map();
|
|
1306
|
+
for (const k of await (0, transaction_rows_1.readTxKeys)(tx, [...new Set(open.map(i => i.txHash))])) {
|
|
1307
|
+
if (k.txSeq != null)
|
|
1308
|
+
seqByHash.set(k.hash, Number(k.txSeq));
|
|
1309
|
+
}
|
|
1310
|
+
const stored = new Set();
|
|
1311
|
+
for (const seqChunk of (0, collections_1.chunk)([...new Set(seqByHash.values())], collections_1.IN_CHUNK)) {
|
|
1312
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } }));
|
|
1313
|
+
for (const r of rows ?? [])
|
|
1314
|
+
stored.add(`${(0, transaction_rows_1.seqKey)(r.txSeq)}#${Number(r.outputIndex)}`);
|
|
1315
|
+
}
|
|
1316
|
+
for (const input of open) {
|
|
1317
|
+
const seq = seqByHash.get(input.txHash);
|
|
1318
|
+
if (seq != null && stored.has(`${(0, transaction_rows_1.seqKey)(seq)}#${input.outputIndex}`))
|
|
1319
|
+
input.spentTxSeq = seq;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
// Deposit of a transaction whose source left it open, from the ledger's balance: spent inputs
|
|
1323
|
+
// plus withdrawals, minus outputs, fee and treasury donation. Stays null while an input is not indexed.
|
|
1324
|
+
applyDeposits(txs) {
|
|
1325
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
1326
|
+
for (const t of txs) {
|
|
1327
|
+
if (t.deposit != null)
|
|
1328
|
+
continue;
|
|
1329
|
+
const spent = (t.inputs ?? []).filter(i => !i.isCollateral && !i.isReference);
|
|
1330
|
+
if (spent.some(i => !i.address))
|
|
1331
|
+
continue;
|
|
1332
|
+
const consumed = spent.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n)
|
|
1333
|
+
+ (t.withdrawals ?? []).reduce((sum, w) => sum + BigInt(w.amount), 0n);
|
|
1334
|
+
const produced = (t.outputs ?? []).filter(o => !o.isCollateral).reduce((sum, o) => sum + lovelaceOf(o.amount), 0n)
|
|
1335
|
+
+ BigInt(t.fee) + BigInt(t.treasuryDonation ?? '0');
|
|
1336
|
+
t.deposit = (consumed - produced).toString();
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
// Fee of a phase-2 failure is collateral inputs minus collateral return. The declared fee
|
|
1340
|
+
// stays when total_collateral set it or a collateral input is not indexed.
|
|
1341
|
+
applyCollateralFees(blockData, txs) {
|
|
1342
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
1343
|
+
let corrected = false;
|
|
1344
|
+
for (const t of txs) {
|
|
1345
|
+
// totalCollateral set = the mapper already put the charged amount in `fee`
|
|
1346
|
+
if (!t.spendsCollaterals || t.totalCollateral != null)
|
|
1347
|
+
continue;
|
|
1348
|
+
const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
|
|
1349
|
+
if (!collateral.length)
|
|
1350
|
+
continue; // nothing to derive from, keep the declared fee
|
|
1351
|
+
const unresolved = collateral.find(i => !i.address);
|
|
1352
|
+
if (unresolved) {
|
|
1353
|
+
logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
|
|
1354
|
+
`, keeping the declared fee ${t.fee}, which understates what the ledger charged`);
|
|
1355
|
+
continue;
|
|
1356
|
+
}
|
|
1357
|
+
const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
|
|
1358
|
+
const returned = (t.outputs ?? [])
|
|
1359
|
+
.filter(o => o.isCollateral)
|
|
1360
|
+
.reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
|
|
1361
|
+
const charged = consumed - returned;
|
|
1362
|
+
if (charged < 0n) {
|
|
1363
|
+
logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed}` +
|
|
1364
|
+
`, keeping the declared fee ${t.fee}`);
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
t.fee = charged.toString();
|
|
1368
|
+
corrected = true;
|
|
1369
|
+
}
|
|
1370
|
+
if (corrected) {
|
|
1371
|
+
blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
// Uses the ledger's mint field when the source reports it, else outputs minus spent inputs per unit.
|
|
1375
|
+
// A tx with an unresolvable spent input is skipped and logged.
|
|
1376
|
+
buildAssetHistoryRows(blockData, txs) {
|
|
1377
|
+
const entries = [];
|
|
1378
|
+
let skipped = 0;
|
|
1379
|
+
for (const t of txs) {
|
|
1380
|
+
let net;
|
|
1381
|
+
if (t.mint) {
|
|
1382
|
+
// A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
|
|
1383
|
+
net = new Map();
|
|
1384
|
+
for (const m of t.mint) {
|
|
1385
|
+
if (m.unit === 'lovelace')
|
|
1386
|
+
continue;
|
|
1387
|
+
net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
else {
|
|
1391
|
+
if (t.spendsCollaterals)
|
|
1392
|
+
continue; // no mint is applied when the script phase failed
|
|
1393
|
+
const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
|
|
1394
|
+
const unresolved = consumed.find(i => !i.address);
|
|
1395
|
+
if (unresolved) {
|
|
1396
|
+
logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
|
|
1397
|
+
`, skipping, mint/burn of this transaction is not recorded`);
|
|
1398
|
+
skipped++;
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
net = new Map();
|
|
1402
|
+
const add = (amount, sign) => {
|
|
1403
|
+
for (const a of amount ?? []) {
|
|
1404
|
+
if (a.unit === 'lovelace')
|
|
1405
|
+
continue;
|
|
1406
|
+
net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
|
|
1410
|
+
add(o.amount, 1n);
|
|
1411
|
+
for (const i of consumed)
|
|
1412
|
+
add(i.amount, -1n);
|
|
1413
|
+
}
|
|
1414
|
+
for (const [unit, quantity] of net) {
|
|
1415
|
+
if (quantity === 0n)
|
|
1416
|
+
continue;
|
|
1417
|
+
entries.push({
|
|
1418
|
+
unit,
|
|
1419
|
+
txHash: t.hash,
|
|
1420
|
+
action: quantity > 0n ? 'mint' : 'burn',
|
|
1421
|
+
quantity: (quantity < 0n ? -quantity : quantity).toString(),
|
|
1422
|
+
blockTime: blockData.time ?? null,
|
|
1423
|
+
blockHeight: blockData.height ?? null,
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
if (skipped) {
|
|
1428
|
+
logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
|
|
1429
|
+
}
|
|
1430
|
+
return (0, mappers_1.mapAssetHistory)(entries);
|
|
1431
|
+
}
|
|
1432
|
+
// Adds a bare Assets row for every new unit, without provider calls. Its epoch-zero key never hits
|
|
1433
|
+
// an enriched row. The existence check reads the DB entity, because the service view hides such rows.
|
|
1434
|
+
async ensureAssetRows(tx, units) {
|
|
1435
|
+
if (this.crawlAssetCatalogue === 'off' || !units.size)
|
|
1436
|
+
return 0;
|
|
1437
|
+
const unknown = [...units].filter(u => !this.assetMemo.has(u));
|
|
1438
|
+
if (!unknown.length)
|
|
1439
|
+
return 0;
|
|
1440
|
+
const missing = [];
|
|
1441
|
+
for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
|
|
1442
|
+
const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
|
|
1443
|
+
const known = new Set(rows.map(r => r.unit));
|
|
1444
|
+
for (const unit of unitChunk) {
|
|
1445
|
+
if (known.has(unit))
|
|
1446
|
+
this.noteAssetSeen(unit);
|
|
1447
|
+
else
|
|
1448
|
+
missing.push(unit);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
if (!missing.length)
|
|
1452
|
+
return 0;
|
|
1453
|
+
const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
|
|
1454
|
+
for (const row of rows)
|
|
1455
|
+
row.decimals = await (0, asset_decimals_1.cip68Decimals)(tx, row.unit);
|
|
1456
|
+
// Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
|
|
1457
|
+
for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
|
|
1458
|
+
await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
|
|
1459
|
+
}
|
|
1460
|
+
// Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
|
|
1461
|
+
// the commit: a rolled-back block must write its bare rows again.
|
|
1462
|
+
this.pendingCommit.push(() => { for (const unit of missing)
|
|
1463
|
+
this.noteAssetSeen(unit); });
|
|
1464
|
+
if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
|
|
1465
|
+
for (const row of rows) {
|
|
1466
|
+
if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
|
|
1467
|
+
this.enrichQueue.shift();
|
|
1468
|
+
this.enrichQueue.push(row.unit);
|
|
1469
|
+
}
|
|
1470
|
+
this.startAssetEnrichment();
|
|
1471
|
+
}
|
|
1472
|
+
return rows.length;
|
|
1473
|
+
}
|
|
1474
|
+
// Oldest entries are evicted to keep memory flat. A lost entry costs one SELECT, never a wrong write.
|
|
1475
|
+
noteAssetSeen(unit) {
|
|
1476
|
+
if (this.assetMemo.has(unit))
|
|
1477
|
+
return;
|
|
1478
|
+
if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
|
|
1479
|
+
const oldest = this.assetMemo.values().next();
|
|
1480
|
+
if (!oldest.done)
|
|
1481
|
+
this.assetMemo.delete(oldest.value);
|
|
1482
|
+
}
|
|
1483
|
+
this.assetMemo.add(unit);
|
|
1484
|
+
}
|
|
1485
|
+
// Snapshots all pools and DReps of an epoch in its own transaction after the block commit.
|
|
1486
|
+
// Ogmios reads the ledger at the given block, Koios the current state. Source null means skipped.
|
|
1487
|
+
async snapshotEpoch(epoch, at) {
|
|
1488
|
+
const epochState = at.hash ? this.client.getEpochStateBackend() : null;
|
|
1489
|
+
if (epochState && at.hash)
|
|
1490
|
+
return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash });
|
|
1491
|
+
const backend = this.client.getEnumeratingBackend();
|
|
1492
|
+
if (!backend) {
|
|
1493
|
+
logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
|
|
1494
|
+
return { pools: 0, dreps: 0, source: null };
|
|
1495
|
+
}
|
|
1496
|
+
// Network first, DB second, so provider round trips never run under a write lock.
|
|
1497
|
+
const [poolData, drepData] = await Promise.all([
|
|
1498
|
+
backend.getPoolIds().then(ids => backend.getPools(ids)),
|
|
1499
|
+
backend.getDrepIds().then(ids => backend.getDreps(ids)),
|
|
1500
|
+
]);
|
|
1501
|
+
const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
|
|
1502
|
+
const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
|
|
1503
|
+
const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
|
|
1504
|
+
const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
|
|
1505
|
+
const ledgerRow = {
|
|
1506
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: null, source: 'koios',
|
|
1507
|
+
liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1508
|
+
poolCount: poolData.length, drepCount: drepData.length,
|
|
1509
|
+
};
|
|
1510
|
+
await cds_1.default.tx(async (tx) => {
|
|
1511
|
+
// Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
|
|
1512
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1513
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1514
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1515
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1516
|
+
for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
|
|
1517
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
|
|
1518
|
+
for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
|
|
1519
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
|
|
1520
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1521
|
+
});
|
|
1522
|
+
logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1523
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
|
|
1524
|
+
}
|
|
1525
|
+
// Live Pools and Dreps rows are not refreshed, because the ledger state may be hours old.
|
|
1526
|
+
// blocksMinted is set only when the crawl covers the chain since Shelley.
|
|
1527
|
+
async snapshotEpochFromLedger(backend, epoch, at) {
|
|
1528
|
+
const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
|
|
1529
|
+
if (state.epoch !== epoch) {
|
|
1530
|
+
logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch}, stored as ${epoch}`);
|
|
1531
|
+
}
|
|
1532
|
+
const minted = await this.crawledBlocksByPool(at.slot);
|
|
1533
|
+
const previous = await this.previousLiveStake(epoch);
|
|
1534
|
+
const activeTotal = previous ? [...previous.values()].reduce((a, b) => a + b, 0n) : 0n;
|
|
1535
|
+
const origin = { source: 'ogmios', hash: at.hash };
|
|
1536
|
+
const poolSnapshots = state.pools.map(p => {
|
|
1537
|
+
const active = previous?.get(p.poolId);
|
|
1538
|
+
return {
|
|
1539
|
+
...(0, mappers_1.mapPoolSnapshot)(p, epoch, at, origin),
|
|
1540
|
+
blocksMinted: minted ? (minted.get(p.poolId) ?? 0) : null,
|
|
1541
|
+
activeStake: active == null ? null : active.toString(),
|
|
1542
|
+
activeSize: active == null || activeTotal === 0n ? null : Number((active * 1000000n) / activeTotal) / 1_000_000,
|
|
1543
|
+
};
|
|
1544
|
+
});
|
|
1545
|
+
const drepSnapshots = state.dreps.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at, origin));
|
|
1546
|
+
const reserves = state.reserves == null ? null : BigInt(state.reserves);
|
|
1547
|
+
const ledgerRow = {
|
|
1548
|
+
epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: at.hash, source: 'ogmios',
|
|
1549
|
+
treasury: state.treasury,
|
|
1550
|
+
reserves: state.reserves,
|
|
1551
|
+
totalSupply: reserves == null ? null : (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves).toString(),
|
|
1552
|
+
liveStake: state.pools.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
|
|
1553
|
+
activeStake: previous ? activeTotal.toString() : null,
|
|
1554
|
+
poolCount: state.pools.length,
|
|
1555
|
+
drepCount: state.dreps.length,
|
|
1556
|
+
drepAbstainStake: state.drepAbstainStake,
|
|
1557
|
+
drepNoConfidenceStake: state.drepNoConfidenceStake,
|
|
1558
|
+
};
|
|
1559
|
+
await cds_1.default.tx(async (tx) => {
|
|
1560
|
+
for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
|
|
1561
|
+
await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
|
|
1562
|
+
for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
|
|
1563
|
+
await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
|
|
1564
|
+
await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
|
|
1565
|
+
});
|
|
1566
|
+
logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
|
|
1567
|
+
return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
|
|
1568
|
+
}
|
|
1569
|
+
// Active stake of epoch E is the live stake in the snapshot of epoch E-1.
|
|
1570
|
+
// Null without that snapshot.
|
|
1571
|
+
async previousLiveStake(epoch) {
|
|
1572
|
+
const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
|
|
1573
|
+
if (!rows?.length)
|
|
1574
|
+
return null;
|
|
1575
|
+
return new Map(rows.map(r => [r.poolId, BigInt(lovelaceSum(r.liveStake))]));
|
|
1576
|
+
}
|
|
1577
|
+
/** Crawled blocks per pool up to `slot`; null unless the crawl started at or before Shelley. */
|
|
1578
|
+
async crawledBlocksByPool(slot) {
|
|
1579
|
+
const db = cds_1.default.db;
|
|
1580
|
+
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
1581
|
+
const shelley = const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot;
|
|
1582
|
+
if (cursor?.startSlot == null || cursor.startSlot > shelley)
|
|
1583
|
+
return null;
|
|
1584
|
+
const rows = await db.run(SELECT.from(CardanoODataService_1.Blocks).columns('slotLeader', 'count(*) as n').where({ slot: { '<=': slot } }).groupBy('slotLeader'));
|
|
1585
|
+
const out = new Map();
|
|
1586
|
+
for (const r of rows ?? [])
|
|
1587
|
+
if (r.slotLeader)
|
|
1588
|
+
out.set(r.slotLeader, Number(r.n));
|
|
1589
|
+
return out;
|
|
1590
|
+
}
|
|
1591
|
+
/** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
|
|
1592
|
+
collectBlockUnits(txs, assetHistoryRows) {
|
|
1593
|
+
const units = new Set();
|
|
1594
|
+
for (const t of txs) {
|
|
1595
|
+
for (const o of t.outputs ?? []) {
|
|
1596
|
+
for (const a of o.amount ?? [])
|
|
1597
|
+
if (a.unit !== 'lovelace')
|
|
1598
|
+
units.add(a.unit);
|
|
1599
|
+
}
|
|
1600
|
+
for (const i of t.inputs ?? []) {
|
|
1601
|
+
for (const a of i.amount ?? [])
|
|
1602
|
+
if (a.unit !== 'lovelace')
|
|
1603
|
+
units.add(a.unit);
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
for (const row of assetHistoryRows)
|
|
1607
|
+
if (row.unit)
|
|
1608
|
+
units.add(row.unit);
|
|
1609
|
+
return units;
|
|
1610
|
+
}
|
|
1611
|
+
/** Index an epoch by number. */
|
|
589
1612
|
async indexEpoch(tx, epochNumber) {
|
|
590
|
-
|
|
591
|
-
|
|
1613
|
+
return this.storeEpoch(tx, await this.fetchEpoch(epochNumber));
|
|
1614
|
+
}
|
|
1615
|
+
/** An epoch row from the backend. */
|
|
1616
|
+
async fetchEpoch(epochNumber) {
|
|
1617
|
+
return (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
|
|
1618
|
+
}
|
|
1619
|
+
async storeEpoch(tx, epochEntity) {
|
|
592
1620
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
593
1621
|
return epochEntity;
|
|
594
1622
|
}
|
|
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
|
-
*/
|
|
1623
|
+
/** Index an account by stake address, plus its addresses when it has any. */
|
|
601
1624
|
async indexAccount(tx, stakeAddress) {
|
|
602
|
-
|
|
603
|
-
|
|
1625
|
+
return this.storeAccount(tx, await this.fetchAccount(tx, stakeAddress));
|
|
1626
|
+
}
|
|
1627
|
+
/** An account and the addresses it controls, read but not stored. */
|
|
1628
|
+
async fetchAccount(tx, stakeAddress) {
|
|
1629
|
+
const account = await this.resolveAccount(tx, stakeAddress);
|
|
1630
|
+
return { account, addresses: await this.fetchAddresses(tx, account.addresses) };
|
|
1631
|
+
}
|
|
1632
|
+
/** Stores what fetchAccount read. */
|
|
1633
|
+
async storeAccount(tx, fetched) {
|
|
1634
|
+
const accountEntity = (0, mappers_1.mapAccount)(fetched.account, this.client.max_age_ms);
|
|
604
1635
|
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
await this._ensureAddresses(tx, addresses);
|
|
608
|
-
}
|
|
1636
|
+
for (const address of fetched.addresses)
|
|
1637
|
+
await this.storeAddress(tx, address);
|
|
609
1638
|
return accountEntity;
|
|
610
1639
|
}
|
|
611
|
-
/**
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1640
|
+
/** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
|
|
1641
|
+
async resolveAccount(tx, stakeAddress) {
|
|
1642
|
+
const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
|
|
1643
|
+
const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
1644
|
+
const ledger = Boolean((await this.localCoverage(db))?.ledger);
|
|
1645
|
+
const row = ledger
|
|
1646
|
+
? await db.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }))
|
|
1647
|
+
: undefined;
|
|
1648
|
+
return {
|
|
1649
|
+
ledger,
|
|
1650
|
+
controlledAmount: row?.controlledAmount,
|
|
1651
|
+
held: ledger ? await this.ledgerAccountUtxos(db, stakeAddress) : { addresses: [], utxos: [] },
|
|
1652
|
+
withdrawalsSum: accountInfo.withdrawalsSum === '0' ? await this.localWithdrawalsSum(db, stakeAddress) : null,
|
|
1653
|
+
};
|
|
1654
|
+
});
|
|
1655
|
+
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
|
|
1656
|
+
// the addresses come from the set too (the node has no stake-key -> address index)
|
|
1657
|
+
if (local.ledger) {
|
|
1658
|
+
accountInfo.controlledAmount = (BigInt(lovelaceSum(local.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
|
|
1659
|
+
const byAddress = new Map(local.held.addresses.map(a => [a, []]));
|
|
1660
|
+
for (const u of await this.unspentAtNode(local.held.utxos))
|
|
1661
|
+
byAddress.get(u.address)?.push(u);
|
|
1662
|
+
accountInfo.addresses = local.held.addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
|
|
1663
|
+
}
|
|
1664
|
+
if (local.withdrawalsSum != null)
|
|
1665
|
+
accountInfo.withdrawalsSum = local.withdrawalsSum;
|
|
1666
|
+
return accountInfo;
|
|
1667
|
+
}
|
|
1668
|
+
/** Index a DRep by bech32 id. */
|
|
617
1669
|
async indexDrep(tx, drepId) {
|
|
618
|
-
|
|
619
|
-
|
|
1670
|
+
return this.storeDrep(tx, await this.fetchDrep(drepId));
|
|
1671
|
+
}
|
|
1672
|
+
/** A DRep row from the backend. */
|
|
1673
|
+
async fetchDrep(drepId) {
|
|
1674
|
+
return (0, mappers_1.mapDrep)(await this.client.getDrep(drepId), this.client.max_age_ms);
|
|
1675
|
+
}
|
|
1676
|
+
async storeDrep(tx, drepEntity) {
|
|
620
1677
|
await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
|
|
621
1678
|
return drepEntity;
|
|
622
1679
|
}
|
|
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
|
-
*/
|
|
1680
|
+
/** Index a pool by id. */
|
|
629
1681
|
async indexPool(tx, poolId) {
|
|
630
|
-
|
|
631
|
-
|
|
1682
|
+
return this.storePool(tx, await this.fetchPool(tx, poolId));
|
|
1683
|
+
}
|
|
1684
|
+
/** A pool row, read but not stored. */
|
|
1685
|
+
async fetchPool(tx, poolId) {
|
|
1686
|
+
return (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
|
|
1687
|
+
}
|
|
1688
|
+
async storePool(tx, poolEntity) {
|
|
632
1689
|
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
633
1690
|
return poolEntity;
|
|
634
1691
|
}
|
|
635
|
-
/**
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1692
|
+
/** Pool from the backend with crawled block counts, the snapshot's active stake and its metadata file. */
|
|
1693
|
+
async resolvePool(tx, poolId) {
|
|
1694
|
+
const backend = await this.client.getPool(poolId);
|
|
1695
|
+
const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
|
|
1696
|
+
const blocks = await this.localPoolBlocks(db, poolId);
|
|
1697
|
+
// The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
|
|
1698
|
+
return backend.activeStake === '0' ? { ...blocks, ...(await this.snapshotActiveStake(db, poolId)) } : blocks;
|
|
1699
|
+
});
|
|
1700
|
+
const poolInfo = { ...backend, ...local };
|
|
1701
|
+
Object.assign(poolInfo, await this.poolMetadataOf(poolInfo));
|
|
1702
|
+
return poolInfo;
|
|
1703
|
+
}
|
|
1704
|
+
// Name, ticker, homepage and description of a pool whose backend gave only the file's URL and hash.
|
|
1705
|
+
// Loads the file when `poolMetadataFetch` is on. A file is memoized by its hash.
|
|
1706
|
+
async poolMetadataOf(pool) {
|
|
1707
|
+
if (!this.poolMetadataFetch || pool.name != null || !pool.metadataUrl || !pool.metadataHash)
|
|
1708
|
+
return undefined;
|
|
1709
|
+
const known = this.poolMetadataByHash.get(pool.metadataHash);
|
|
1710
|
+
if (known)
|
|
1711
|
+
return known;
|
|
1712
|
+
const metadata = await (0, pool_metadata_1.fetchPoolMetadata)(pool.metadataUrl, pool.metadataHash);
|
|
1713
|
+
if (!metadata)
|
|
1714
|
+
return undefined;
|
|
1715
|
+
if (this.poolMetadataByHash.size >= CardanoIndexer.POOL_METADATA_MEMO_CAP)
|
|
1716
|
+
this.poolMetadataByHash.clear();
|
|
1717
|
+
this.poolMetadataByHash.set(pool.metadataHash, metadata);
|
|
1718
|
+
return metadata;
|
|
1719
|
+
}
|
|
1720
|
+
/** Turns the loading of pool metadata files on or off (`poolMetadataFetch`). */
|
|
1721
|
+
setPoolMetadataFetch(enabled) {
|
|
1722
|
+
this.poolMetadataFetch = enabled;
|
|
1723
|
+
}
|
|
1724
|
+
/** Index an asset by unit (policyId + assetNameHex). */
|
|
641
1725
|
async indexAsset(tx, unit) {
|
|
642
|
-
|
|
1726
|
+
return this.writeAsset(tx, unit, await this.resolveAssetInfo(tx, unit));
|
|
1727
|
+
}
|
|
1728
|
+
/** Stores an asset read with resolveAssetInfo. */
|
|
1729
|
+
async storeAsset(tx, assetInfo) {
|
|
1730
|
+
return this.writeAsset(tx, assetInfo.unit, assetInfo);
|
|
1731
|
+
}
|
|
1732
|
+
/** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
|
|
1733
|
+
async indexAssetFromBackend(tx, unit) {
|
|
1734
|
+
return this.writeAsset(tx, unit, await this.client.getAssetInfo(unit));
|
|
1735
|
+
}
|
|
1736
|
+
async writeAsset(tx, unit, assetInfo) {
|
|
643
1737
|
const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
|
|
1738
|
+
assetEntity.decimals = (await (0, asset_decimals_1.cip68Decimals)(tx, unit, assetInfo.initialMintTxHash)) ?? assetInfo.registryDecimals;
|
|
644
1739
|
await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
|
|
645
1740
|
return assetEntity;
|
|
646
1741
|
}
|
|
647
|
-
/**
|
|
648
|
-
* Index & return mint/burn history for an asset. Always-fresh from the
|
|
649
|
-
* preferred backend (Koios for block timestamps, Blockfrost as fallback).
|
|
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
|
|
656
|
-
*/
|
|
1742
|
+
/** Always fresh. Rows are keyed by unit and tx, so older cached entries persist. */
|
|
657
1743
|
async indexAssetHistory(tx, unit, limit = 100) {
|
|
1744
|
+
const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
|
|
1745
|
+
if (crawled)
|
|
1746
|
+
return crawled;
|
|
658
1747
|
const events = await this.client.getAssetHistory(unit, limit);
|
|
659
1748
|
if (events.length === 0)
|
|
660
1749
|
return [];
|
|
661
|
-
|
|
1750
|
+
// a provider can list one transaction twice; Postgres refuses an UPSERT that hits a key twice
|
|
1751
|
+
const rows = [...new Map((0, mappers_1.mapAssetHistory)(events).map(r => [`${r.unit}|${r.txHash}`, r])).values()];
|
|
662
1752
|
await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
|
|
663
1753
|
return rows;
|
|
664
1754
|
}
|
|
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
|
-
*/
|
|
1755
|
+
/** Build a transaction and persist the build result with inputs/outputs/address association. */
|
|
673
1756
|
async _indexBuildResult(tx, buildreq, buildFn) {
|
|
674
|
-
|
|
675
|
-
const
|
|
1757
|
+
// The build talks to the backend: nothing is written before it returns.
|
|
1758
|
+
const protocolParams = await this.fetchProtocolParameters(tx);
|
|
1759
|
+
const txbuildResult = await buildFn(buildreq, protocolParams.row);
|
|
676
1760
|
const buildResult = (0, mappers_1.mapBuildResult)(txbuildResult, this.client.max_age_ms);
|
|
1761
|
+
await this.storeProtocolParameters(tx, protocolParams);
|
|
677
1762
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuild).entries(buildResult));
|
|
678
1763
|
if (buildResult.id && txbuildResult.inputs && txbuildResult.inputs.length > 0) {
|
|
679
1764
|
const inputRows = (0, mappers_1.mapBuildInputs)(buildResult.id, txbuildResult.inputs);
|
|
@@ -683,6 +1768,10 @@ class CardanoIndexer {
|
|
|
683
1768
|
const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
|
|
684
1769
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
|
|
685
1770
|
}
|
|
1771
|
+
if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
|
|
1772
|
+
const buildId = buildResult.id;
|
|
1773
|
+
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) }))));
|
|
1774
|
+
}
|
|
686
1775
|
if (buildResult.id && buildreq.senderAddress) {
|
|
687
1776
|
await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
|
|
688
1777
|
}
|
|
@@ -703,52 +1792,45 @@ class CardanoIndexer {
|
|
|
703
1792
|
async indexPlutusSpendBuildResult(tx, buildreq) {
|
|
704
1793
|
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
|
|
705
1794
|
}
|
|
706
|
-
/**
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
1795
|
+
/** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
|
|
1796
|
+
async indexPlutusBuildResult(tx, buildreq) {
|
|
1797
|
+
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
|
|
1798
|
+
}
|
|
1799
|
+
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
711
1800
|
async indexProtocolParameters(tx) {
|
|
1801
|
+
return this.storeProtocolParameters(tx, await this.fetchProtocolParameters(tx));
|
|
1802
|
+
}
|
|
1803
|
+
/** The stored row within its TTL, else the parameters from the backend. Nothing is written. */
|
|
1804
|
+
async fetchProtocolParameters(tx) {
|
|
712
1805
|
const network = this.client.network;
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
if (now - this.lastParamsFetchTime < PROTOCOL_PARAMS_TTL_MS) {
|
|
717
|
-
// (network, epoch) is the composite key — old epochs accumulate as rows, so
|
|
718
|
-
// order by epoch desc to return the LATEST instead of an arbitrary row.
|
|
719
|
-
const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
|
|
1806
|
+
if (Date.now() - this.lastParamsFetchTime < const_1.PROTOCOL_PARAMS_TTL_MS) {
|
|
1807
|
+
// (network, epoch) is the key; order by epoch desc to get the latest row
|
|
1808
|
+
const existing = await (0, tx_utils_1.readOutside)(tx, (db) => db.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc')));
|
|
720
1809
|
if (existing)
|
|
721
|
-
return existing;
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
* @param params submission parameters
|
|
735
|
-
* @returns {Promise<TransactionSubmission>} persisted transaction submission entity
|
|
736
|
-
*/
|
|
1810
|
+
return { row: existing, fresh: false };
|
|
1811
|
+
}
|
|
1812
|
+
return { row: (0, mappers_1.mapProtocolParameters)(await this.client.getProtocolParameters()), fresh: true };
|
|
1813
|
+
}
|
|
1814
|
+
/** Stores parameters that came from the backend and restarts their TTL. */
|
|
1815
|
+
async storeProtocolParameters(tx, fetched) {
|
|
1816
|
+
if (fetched.fresh) {
|
|
1817
|
+
await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(fetched.row));
|
|
1818
|
+
this.lastParamsFetchTime = Date.now();
|
|
1819
|
+
}
|
|
1820
|
+
return fetched.row;
|
|
1821
|
+
}
|
|
1822
|
+
/** Persist a transaction submission and flag the build as submitted when linked. */
|
|
737
1823
|
async persistTransactionSubmission(tx, params) {
|
|
738
1824
|
const { signedTxCbor, txHash, buildId } = params;
|
|
739
|
-
// Map submission data
|
|
740
1825
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
|
|
741
|
-
// Create submission record (status: 'pending' — updated to 'submitted' after blockchain confirms)
|
|
742
1826
|
const submissionRecord = {
|
|
743
1827
|
...indexSubmission,
|
|
744
1828
|
build_id: buildId || null,
|
|
745
1829
|
backendResponse: 'Submitted successfully',
|
|
746
|
-
status: 'pending',
|
|
1830
|
+
status: params.status ?? 'pending',
|
|
747
1831
|
};
|
|
748
|
-
// Persist submission
|
|
749
1832
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
750
1833
|
logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
|
|
751
|
-
// Update build status if buildId provided
|
|
752
1834
|
if (buildId) {
|
|
753
1835
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
754
1836
|
.set({ wasSubmitted: true })
|
|
@@ -757,33 +1839,30 @@ class CardanoIndexer {
|
|
|
757
1839
|
}
|
|
758
1840
|
return submissionRecord;
|
|
759
1841
|
}
|
|
760
|
-
/**
|
|
761
|
-
|
|
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
|
-
*/
|
|
768
|
-
async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
|
|
1842
|
+
/** Update a submission's status. With onlyFrom the row changes only while it has that status. */
|
|
1843
|
+
async updateSubmissionStatus(tx, submissionId, status, errorMessage, onlyFrom) {
|
|
769
1844
|
const updateData = { status };
|
|
770
1845
|
if (errorMessage) {
|
|
771
1846
|
updateData.errorMessage = errorMessage;
|
|
772
1847
|
}
|
|
773
1848
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionSubmissions)
|
|
774
1849
|
.set(updateData)
|
|
775
|
-
.where({ id: submissionId }));
|
|
1850
|
+
.where(onlyFrom ? { id: submissionId, status: onlyFrom } : { id: submissionId }));
|
|
776
1851
|
logger.debug({ submissionId, status }, 'Updated submission status');
|
|
777
1852
|
}
|
|
778
|
-
/**
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
1853
|
+
/** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
|
|
1854
|
+
async dropDuplicateSubmission(tx, submissionId, txHash) {
|
|
1855
|
+
const existing = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionSubmissions).columns('id')
|
|
1856
|
+
.where({ txHash, status: { in: ['submitted', 'confirmed'] }, id: { '!=': submissionId } }));
|
|
1857
|
+
if (!existing)
|
|
1858
|
+
return false;
|
|
1859
|
+
await tx.run(DELETE.from(CardanoTransactionService_1.TransactionSubmissions).where({ id: submissionId }));
|
|
1860
|
+
logger.debug({ submissionId, existingId: existing.id, txHash }, 'Dropped duplicate submission row');
|
|
1861
|
+
return true;
|
|
1862
|
+
}
|
|
1863
|
+
/** Persist a new signing request and link it to the build's sender address. */
|
|
784
1864
|
async persistSigningRequest(tx, params) {
|
|
785
1865
|
const { buildId, signingPayload } = params;
|
|
786
|
-
// Create signing request record
|
|
787
1866
|
const signingRequestRecord = {
|
|
788
1867
|
id: signingPayload.signingRequestId,
|
|
789
1868
|
build_id: buildId,
|
|
@@ -796,26 +1875,17 @@ class CardanoIndexer {
|
|
|
796
1875
|
cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
|
|
797
1876
|
cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
|
|
798
1877
|
};
|
|
799
|
-
// Persist to database
|
|
800
1878
|
await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
|
|
801
1879
|
logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
|
|
802
|
-
// Index address-signing request association
|
|
803
1880
|
const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
|
|
804
1881
|
if (build?.senderAddress) {
|
|
805
1882
|
await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
|
|
806
1883
|
}
|
|
807
1884
|
return signingRequestRecord;
|
|
808
1885
|
}
|
|
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
|
-
*/
|
|
1886
|
+
/** Persist a signature verification and update the signing request status. */
|
|
816
1887
|
async persistSignatureVerification(tx, params) {
|
|
817
1888
|
const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
|
|
818
|
-
// Create verification record
|
|
819
1889
|
const verificationRecord = {
|
|
820
1890
|
id: cds_1.default.utils.uuid(),
|
|
821
1891
|
signingRequest_id: signingRequestId,
|
|
@@ -828,10 +1898,8 @@ class CardanoIndexer {
|
|
|
828
1898
|
warnings: JSON.stringify(verificationResult.warnings),
|
|
829
1899
|
verifiedAt: new Date().toISOString(),
|
|
830
1900
|
};
|
|
831
|
-
// Persist verification
|
|
832
1901
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
833
1902
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
834
|
-
// Update signing request status
|
|
835
1903
|
const newStatus = verificationResult.isValid ? 'verified' : 'failed';
|
|
836
1904
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
837
1905
|
.set({
|
|
@@ -845,16 +1913,9 @@ class CardanoIndexer {
|
|
|
845
1913
|
logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
|
|
846
1914
|
return verificationRecord;
|
|
847
1915
|
}
|
|
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
|
-
*/
|
|
1916
|
+
/** Persist a verified submission: verification, submission, signing request and build updates. */
|
|
855
1917
|
async indexVerifiedTransactionSubmission(tx, params) {
|
|
856
1918
|
const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
|
|
857
|
-
// Step 1: Create and persist verification record
|
|
858
1919
|
const verificationRecord = {
|
|
859
1920
|
id: cds_1.default.utils.uuid(),
|
|
860
1921
|
signingRequest_id: signingRequestId,
|
|
@@ -869,7 +1930,6 @@ class CardanoIndexer {
|
|
|
869
1930
|
};
|
|
870
1931
|
await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
|
|
871
1932
|
logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
|
|
872
|
-
// Step 2: Create and persist submission record
|
|
873
1933
|
const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
|
|
874
1934
|
const submissionRecord = {
|
|
875
1935
|
...indexSubmission,
|
|
@@ -879,7 +1939,6 @@ class CardanoIndexer {
|
|
|
879
1939
|
};
|
|
880
1940
|
await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
|
|
881
1941
|
logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
|
|
882
|
-
// Step 3: Update signing request metadata and status
|
|
883
1942
|
const now = new Date().toISOString();
|
|
884
1943
|
await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
|
|
885
1944
|
.set({
|
|
@@ -892,114 +1951,122 @@ class CardanoIndexer {
|
|
|
892
1951
|
})
|
|
893
1952
|
.where({ id: signingRequestId }));
|
|
894
1953
|
logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
|
|
895
|
-
// Step 4: Update build status
|
|
896
1954
|
await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
|
|
897
1955
|
.set({ wasSubmitted: true })
|
|
898
1956
|
.where({ id: buildId }));
|
|
899
1957
|
logger.debug({ buildId }, 'Updated build wasSubmitted flag');
|
|
900
1958
|
return submissionRecord;
|
|
901
1959
|
}
|
|
902
|
-
/**
|
|
903
|
-
* Index & return the latest epoch information data
|
|
904
|
-
* @param tx CAP transaction object
|
|
905
|
-
* @returns {Promise<Epoch>} epoch entity data
|
|
906
|
-
*/
|
|
1960
|
+
/** Index the latest epoch. */
|
|
907
1961
|
async indexLatestEpoch(tx) {
|
|
908
|
-
|
|
909
|
-
const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
|
|
910
|
-
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
|
|
911
|
-
return epochEntity;
|
|
1962
|
+
return this.storeEpoch(tx, (0, mappers_1.mapEpoch)(await this.client.getLatestEpoch()));
|
|
912
1963
|
}
|
|
913
|
-
/**
|
|
914
|
-
* Index & return the latest block information data
|
|
915
|
-
* @param tx CAP transaction object
|
|
916
|
-
* @returns {Promise<Block>} block entity data
|
|
917
|
-
*/
|
|
1964
|
+
/** Index the latest block, with best-effort epoch enrichment. */
|
|
918
1965
|
async indexLatestBlock(tx) {
|
|
919
|
-
const
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
1966
|
+
const fetched = await this.withEpoch(await this.client.getLatestBlock());
|
|
1967
|
+
// A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
|
|
1968
|
+
// crawled row of the same hash, or outlive the block when the tip is rolled back.
|
|
1969
|
+
if (fetched.block.headerOnly) {
|
|
1970
|
+
if (fetched.epoch)
|
|
1971
|
+
await this.storeEpoch(tx, fetched.epoch);
|
|
1972
|
+
const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: fetched.block.hash }));
|
|
1973
|
+
return stored ?? (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
|
|
926
1974
|
}
|
|
927
|
-
|
|
928
|
-
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
|
|
929
|
-
return blockEntity;
|
|
1975
|
+
return this.storeBlock(tx, fetched);
|
|
930
1976
|
}
|
|
931
1977
|
//-----------------------------------------------------------------------------
|
|
932
1978
|
// Batch Methods (N+1 Optimization)
|
|
933
1979
|
//-----------------------------------------------------------------------------
|
|
934
1980
|
/** Max addresses to index concurrently (avoid overloading backends) */
|
|
935
1981
|
static ADDR_CONCURRENCY = 5;
|
|
936
|
-
/**
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
1982
|
+
/** Block position of a transaction already in the local index (crawled or cached), or null. */
|
|
1983
|
+
async findIndexedTransaction(tx, txHash) {
|
|
1984
|
+
const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash').where({ hash: txHash }));
|
|
1985
|
+
return row ?? null;
|
|
1986
|
+
}
|
|
1987
|
+
// Confirmations including the tx's own block, 0 while not on chain. A stored row counts only inside
|
|
1988
|
+
// the crawled chain, because the crawler removes those rows on a rollback.
|
|
1989
|
+
async resolveTransactionConfirmations(tx, txHash) {
|
|
1990
|
+
const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledTransactionDepth(db, txHash));
|
|
1991
|
+
if (crawled)
|
|
1992
|
+
return { txHash, ...crawled, confirmations: crawled.tipHeight - crawled.blockHeight + 1 };
|
|
1993
|
+
let providerTx = null;
|
|
1994
|
+
try {
|
|
1995
|
+
providerTx = await this.fetchTransaction(tx, txHash);
|
|
1996
|
+
}
|
|
1997
|
+
catch (err) {
|
|
1998
|
+
if (!(0, errors_1.isNotFoundOnAllBackends)(err))
|
|
1999
|
+
throw err;
|
|
2000
|
+
}
|
|
2001
|
+
const blockHeight = providerTx?.blockHeight == null ? null : Number(providerTx.blockHeight);
|
|
2002
|
+
// The tip is read before the transaction is stored, so no write is open during that call.
|
|
2003
|
+
const tip = blockHeight == null ? null : await this.client.getLatestBlock();
|
|
2004
|
+
if (providerTx)
|
|
2005
|
+
await this.storeTransaction(tx, providerTx);
|
|
2006
|
+
if (blockHeight == null || !tip)
|
|
2007
|
+
return { txHash, blockHeight: null, tipHeight: null, confirmations: 0 };
|
|
2008
|
+
if (tip.height == null)
|
|
2009
|
+
throw new errors_1.ProviderUnavailableError('Chain tip height unknown');
|
|
2010
|
+
// a tip from a backend that lags the one that found the tx counts the tx block only
|
|
2011
|
+
const tipHeight = Math.max(tip.height, blockHeight);
|
|
2012
|
+
return { txHash, blockHeight, tipHeight, confirmations: tipHeight - blockHeight + 1 };
|
|
2013
|
+
}
|
|
2014
|
+
/** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
|
|
2015
|
+
async crawledTransactionDepth(tx, txHash) {
|
|
2016
|
+
const coverage = await this.localCoverage(tx);
|
|
2017
|
+
if (coverage?.tipHeight == null)
|
|
2018
|
+
return null;
|
|
2019
|
+
const stored = await this.findIndexedTransaction(tx, txHash);
|
|
2020
|
+
if (stored?.blockHeight == null || stored.slot == null || !stored.blockHash)
|
|
2021
|
+
return null;
|
|
2022
|
+
const slot = Number(stored.slot);
|
|
2023
|
+
if (slot < coverage.fromSlot || slot > coverage.lastSlot)
|
|
2024
|
+
return null;
|
|
2025
|
+
const block = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('hash').where({ hash: stored.blockHash }));
|
|
2026
|
+
if (!block)
|
|
2027
|
+
return null;
|
|
2028
|
+
const blockHeight = Number(stored.blockHeight);
|
|
2029
|
+
return { blockHeight, tipHeight: Math.max(coverage.tipHeight, blockHeight) };
|
|
2030
|
+
}
|
|
2031
|
+
/** Batch-fetches the missing ones, stores them and returns only those. */
|
|
947
2032
|
async ensureTransactionsIndexed(tx, txHashes) {
|
|
2033
|
+
const missing = await (0, tx_utils_1.readOutside)(tx, (db) => this.unstoredTransactionHashes(db, txHashes));
|
|
2034
|
+
const fetched = missing.length ? await this.client.getTransactionsBatch(missing) : new Map();
|
|
2035
|
+
await this.storeTransactions(tx, fetched);
|
|
2036
|
+
return fetched;
|
|
2037
|
+
}
|
|
2038
|
+
/** The hashes among the given ones that have no stored transaction. */
|
|
2039
|
+
async unstoredTransactionHashes(tx, txHashes) {
|
|
948
2040
|
const unique = [...new Set(txHashes)];
|
|
949
2041
|
if (unique.length === 0)
|
|
950
|
-
return
|
|
951
|
-
// DB check — which hashes are already indexed?
|
|
2042
|
+
return [];
|
|
952
2043
|
const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
|
|
953
2044
|
const existingSet = new Set(existingRows.map((r) => r.hash));
|
|
954
2045
|
const missing = unique.filter(h => !existingSet.has(h));
|
|
955
2046
|
logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
if (providerTx.inputs) {
|
|
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));
|
|
984
|
-
}
|
|
2047
|
+
return missing;
|
|
2048
|
+
}
|
|
2049
|
+
/** Stores transactions read from a backend, each with its inputs, outputs and metadata. */
|
|
2050
|
+
async storeTransactions(tx, fetched) {
|
|
2051
|
+
for (const [, providerTx] of fetched) {
|
|
2052
|
+
const txRow = (0, mappers_1.mapTransaction)(providerTx);
|
|
2053
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
|
|
2054
|
+
await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
|
|
985
2055
|
}
|
|
986
|
-
return fetched;
|
|
987
2056
|
}
|
|
988
2057
|
//-----------------------------------------------------------------------------
|
|
989
2058
|
// Private Helpers
|
|
990
2059
|
//-----------------------------------------------------------------------------
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
* @param bech32List array of bech32 addresses
|
|
996
|
-
*/
|
|
997
|
-
async _ensureAddresses(tx, bech32List) {
|
|
2060
|
+
// Uses the address data the account carries, so no request per address.
|
|
2061
|
+
// Only an entry without UTxOs is fetched.
|
|
2062
|
+
async fetchAddresses(tx, accountAddresses) {
|
|
2063
|
+
const fetched = [];
|
|
998
2064
|
const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
|
|
999
|
-
for (let i = 0; i <
|
|
1000
|
-
const chunk =
|
|
1001
|
-
await Promise.all(chunk.map(
|
|
2065
|
+
for (let i = 0; i < accountAddresses.length; i += concurrency) {
|
|
2066
|
+
const chunk = accountAddresses.slice(i, i + concurrency);
|
|
2067
|
+
fetched.push(...await Promise.all(chunk.map(a => this.fetchAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined))));
|
|
1002
2068
|
}
|
|
2069
|
+
return fetched;
|
|
1003
2070
|
}
|
|
1004
2071
|
}
|
|
1005
2072
|
exports.CardanoIndexer = CardanoIndexer;
|