@odatano/core 2.0.0-rc.23 → 2.0.0-rc.25
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/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/CardanoODataService/index.d.ts +27 -2
- package/@cds-models/CardanoODataService/index.js +3 -0
- package/@cds-models/CardanoSignService/index.d.ts +23 -1
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +18 -0
- package/@cds-models/index.js +3 -0
- package/@cds-models/odatano/cardano/index.d.ts +49 -2
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/db/schema.cds +74 -3
- package/db/types.cds +27 -0
- package/package.json +182 -181
- package/srv/blockchain/backends/blockfrost-backend.js +4 -2
- package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
- package/srv/blockchain/backends/koios-backend.d.ts +1 -1
- package/srv/blockchain/backends/koios-backend.js +61 -14
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +166 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
- package/srv/blockchain/backends/ogmios-backend.js +91 -21
- package/srv/blockchain/cardano-client.d.ts +23 -9
- package/srv/blockchain/cardano-client.js +77 -25
- package/srv/blockchain/cardano-indexer.d.ts +61 -15
- package/srv/blockchain/cardano-indexer.js +248 -79
- package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
- package/srv/blockchain/cardano-tx-builder.js +59 -4
- package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/certificate-backfill.js +49 -30
- package/srv/blockchain/crawler/crawler.d.ts +3 -1
- package/srv/blockchain/crawler/crawler.js +12 -7
- package/srv/blockchain/crawler/sync-state.d.ts +3 -1
- package/srv/blockchain/crawler/sync-state.js +15 -2
- package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/transaction-backfill.js +283 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
- package/srv/blockchain/crawler/utxo-set-import.js +138 -47
- package/srv/blockchain/ledger-state.d.ts +16 -1
- package/srv/blockchain/ledger-state.js +38 -18
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- package/srv/blockchain/stored-chain.d.ts +33 -0
- package/srv/blockchain/stored-chain.js +234 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
- package/srv/blockchain/transaction-rows.d.ts +1 -1
- package/srv/blockchain/transaction-rows.js +2 -1
- package/srv/blockchain/wallet-worker/build-request.js +1 -1
- package/srv/cardano-backend-service.cds +52 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +244 -0
- package/srv/cardano-indexer-service.cds +201 -176
- package/srv/cardano-indexer-service.js +104 -10
- package/srv/cardano-service.cds +5 -0
- package/srv/cardano-tx-service.cds +39 -0
- package/srv/cardano-tx-service.js +88 -14
- package/srv/server.js +20 -2
- package/srv/utils/agent-grants.js +8 -0
- package/srv/utils/const.d.ts +5 -0
- package/srv/utils/const.js +6 -1
- package/srv/utils/error-codes.d.ts +2 -0
- package/srv/utils/error-codes.js +2 -0
- package/srv/utils/errors.d.ts +7 -0
- package/srv/utils/errors.js +11 -1
- package/srv/utils/mappers.d.ts +24 -2
- package/srv/utils/mappers.js +49 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +63 -0
- package/srv/utils/tx-build-helper.d.ts +2 -0
- package/srv/utils/tx-build-helper.js +12 -0
- package/srv/utils/tx-request-parsers.d.ts +46 -5
- package/srv/utils/tx-request-parsers.js +227 -16
- package/srv/utils/types.d.ts +59 -0
- package/srv/utils/validators.d.ts +5 -1
- package/srv/utils/validators.js +19 -9
|
@@ -21,12 +21,22 @@ const epoch_slots_1 = require("../utils/epoch-slots");
|
|
|
21
21
|
const const_1 = require("../utils/const");
|
|
22
22
|
const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
|
|
23
23
|
const logger = cds_1.default.log('CardanoIndexer');
|
|
24
|
-
/**
|
|
24
|
+
/** Datum hash, inline datum and reference-script hash of the spent output onto its input. */
|
|
25
|
+
function copyUtxoData(input, dataHash, inlineDatum, referenceScriptHash) {
|
|
26
|
+
input.dataHash = input.dataHash ?? dataHash ?? null;
|
|
27
|
+
input.inlineDatum = input.inlineDatum ?? inlineDatum ?? null;
|
|
28
|
+
input.referenceScriptHash = input.referenceScriptHash ?? referenceScriptHash ?? null;
|
|
29
|
+
}
|
|
25
30
|
function lovelaceSum(value) {
|
|
26
31
|
if (value === null || value === undefined || value === '')
|
|
27
32
|
return '0';
|
|
28
33
|
return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
|
|
29
34
|
}
|
|
35
|
+
/** Provider-shaped address from its unspent outputs: type and stake address decoded from the address. */
|
|
36
|
+
function addressFromUtxos(address, utxos) {
|
|
37
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
38
|
+
return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
|
|
39
|
+
}
|
|
30
40
|
/**
|
|
31
41
|
* Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
|
|
32
42
|
* to entity rows and UPSERTs them inside the caller's CAP transaction.
|
|
@@ -39,11 +49,15 @@ class CardanoIndexer {
|
|
|
39
49
|
static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
|
|
40
50
|
/**
|
|
41
51
|
* Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
|
|
42
|
-
* next one starts; holds at most the current and previous epoch.
|
|
43
|
-
* block transaction
|
|
52
|
+
* next one starts; holds at most the current and previous epoch. A row is UPSERTed until a
|
|
53
|
+
* block transaction that wrote it has committed (`confirmBlockCommit`).
|
|
44
54
|
*/
|
|
45
55
|
crawlEpochCache = new Map();
|
|
46
56
|
crawlEpochCurrent = null;
|
|
57
|
+
/** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
|
|
58
|
+
crawlEpochWritten = new WeakSet();
|
|
59
|
+
/** Memo updates of the running block transaction, applied only after its commit. */
|
|
60
|
+
pendingCommit = [];
|
|
47
61
|
crawlEpochPrevious = null;
|
|
48
62
|
/** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
|
|
49
63
|
crawlAssetHistory = true;
|
|
@@ -73,6 +87,8 @@ class CardanoIndexer {
|
|
|
73
87
|
ledgerInvalidation = null;
|
|
74
88
|
/** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
|
|
75
89
|
static ASSET_MEMO_CAP = 200_000;
|
|
90
|
+
/** Output references per node lookup when checking crawled UTxOs. */
|
|
91
|
+
static OUTREF_CHUNK = 500;
|
|
76
92
|
assetMemo = new Set();
|
|
77
93
|
/**
|
|
78
94
|
* Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
|
|
@@ -190,35 +206,77 @@ class CardanoIndexer {
|
|
|
190
206
|
registryLogo: null,
|
|
191
207
|
};
|
|
192
208
|
}
|
|
209
|
+
/** Address from the crawled UTxO set when it answers, else from the backend. */
|
|
210
|
+
async resolveAddress(tx, addr) {
|
|
211
|
+
return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
|
|
212
|
+
}
|
|
213
|
+
/** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
|
|
214
|
+
async resolveAddressUtxos(tx, addr) {
|
|
215
|
+
return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
|
|
216
|
+
}
|
|
217
|
+
/** Asset from the crawled chain when it answers, else from the backend. */
|
|
218
|
+
async resolveAssetInfo(tx, unit) {
|
|
219
|
+
return (await this.localAssetInfo(tx, unit)) ?? await this.client.getAssetInfo(unit);
|
|
220
|
+
}
|
|
221
|
+
/** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
|
|
222
|
+
async resolveAssetHistory(tx, unit, limit) {
|
|
223
|
+
if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
|
|
224
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
|
|
225
|
+
return (rows ?? []).map(r => ({
|
|
226
|
+
unit: String(r.unit),
|
|
227
|
+
txHash: String(r.txHash),
|
|
228
|
+
action: r.action === 'burn' ? 'burn' : 'mint',
|
|
229
|
+
quantity: String(r.quantity),
|
|
230
|
+
blockTime: r.blockTime == null ? null : Number(r.blockTime),
|
|
231
|
+
blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
|
|
232
|
+
}));
|
|
233
|
+
}
|
|
234
|
+
return this.client.getAssetHistory(unit, limit);
|
|
235
|
+
}
|
|
236
|
+
/** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
|
|
237
|
+
async resolveCredentialUtxos(tx, credHash) {
|
|
238
|
+
return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
|
|
239
|
+
}
|
|
240
|
+
/** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
|
|
241
|
+
async resolveAddressTransactionHashes(tx, addr, limit) {
|
|
242
|
+
const local = await this.localAddressTransactions(tx, addr, limit);
|
|
243
|
+
if (local && (local.complete || local.rows.length >= limit)) {
|
|
244
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
return await this.client.getAddressTransactionHashes(addr, limit);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
|
|
251
|
+
return local.rows.map(r => String(r.tx_hash));
|
|
252
|
+
}
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
193
256
|
/** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
|
|
194
257
|
async ledgerCoverageActive(tx) {
|
|
195
258
|
return Boolean((await this.localCoverage(tx))?.ledger);
|
|
196
259
|
}
|
|
197
260
|
/**
|
|
198
|
-
* Address from the crawled UTxO set:
|
|
199
|
-
*
|
|
261
|
+
* Address from the crawled UTxO set: the unspent `LedgerUTxOs` (see openLedgerUtxos), type and
|
|
262
|
+
* stake address decoded from the address. An address the set has never
|
|
200
263
|
* seen is an empty address, not an error. null = the set cannot answer.
|
|
201
264
|
*/
|
|
202
265
|
async localAddress(tx, addr) {
|
|
203
266
|
if (!(await this.localCoverage(tx))?.ledger)
|
|
204
267
|
return null;
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
address
|
|
216
|
-
|
|
217
|
-
type: decoded.type,
|
|
218
|
-
isScript: decoded.isScript,
|
|
219
|
-
amount: (0, mappers_1.sumUtxoAmounts)(utxos),
|
|
220
|
-
utxos,
|
|
221
|
-
};
|
|
268
|
+
return addressFromUtxos(addr, await this.openLedgerUtxos(tx, [addr]));
|
|
269
|
+
}
|
|
270
|
+
/** Addresses of a stake key from the crawled UTxO set, with their unspent outputs (one read for all). */
|
|
271
|
+
async localAccountAddresses(tx, stakeAddress) {
|
|
272
|
+
const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
|
|
273
|
+
const addresses = (rows ?? []).map(r => r.address);
|
|
274
|
+
if (addresses.length === 0)
|
|
275
|
+
return [];
|
|
276
|
+
const byAddress = new Map(addresses.map(a => [a, []]));
|
|
277
|
+
for (const u of await this.openLedgerUtxos(tx, addresses))
|
|
278
|
+
byAddress.get(u.address)?.push(u);
|
|
279
|
+
return addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
|
|
222
280
|
}
|
|
223
281
|
/**
|
|
224
282
|
* Latest transactions of an address from the crawled UTxO set: the outputs it received
|
|
@@ -335,6 +393,13 @@ class CardanoIndexer {
|
|
|
335
393
|
getUtxoAnchor() {
|
|
336
394
|
return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
|
|
337
395
|
}
|
|
396
|
+
/** Apply the memo updates of the block transaction that just committed. */
|
|
397
|
+
confirmBlockCommit() {
|
|
398
|
+
const pending = this.pendingCommit;
|
|
399
|
+
this.pendingCommit = [];
|
|
400
|
+
for (const apply of pending)
|
|
401
|
+
apply();
|
|
402
|
+
}
|
|
338
403
|
/** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
|
|
339
404
|
takeLedgerInvalidation() {
|
|
340
405
|
const reason = this.ledgerInvalidation;
|
|
@@ -471,8 +536,16 @@ class CardanoIndexer {
|
|
|
471
536
|
constructor(client, txBuilder) {
|
|
472
537
|
this.client = client;
|
|
473
538
|
this.txBuilder = txBuilder;
|
|
539
|
+
txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
|
|
474
540
|
logger.info('CardanoIndexer instance created');
|
|
475
541
|
}
|
|
542
|
+
/**
|
|
543
|
+
* Unspent outputs of an address from the crawled set for the transaction builder; null = the set
|
|
544
|
+
* cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
|
|
545
|
+
*/
|
|
546
|
+
async localAddressUtxos(address) {
|
|
547
|
+
return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
|
|
548
|
+
}
|
|
476
549
|
/**
|
|
477
550
|
* Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
|
|
478
551
|
* transaction, so either everything persists or nothing does.
|
|
@@ -511,10 +584,10 @@ class CardanoIndexer {
|
|
|
511
584
|
}
|
|
512
585
|
/**
|
|
513
586
|
* Index address data with assets and UTxOs; transactions are loaded separately via
|
|
514
|
-
* indexAddressTransactions().
|
|
587
|
+
* indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
|
|
515
588
|
*/
|
|
516
|
-
async indexAddress(tx, addr) {
|
|
517
|
-
const addrData =
|
|
589
|
+
async indexAddress(tx, addr, prefetched) {
|
|
590
|
+
const addrData = prefetched ?? await this.resolveAddress(tx, addr);
|
|
518
591
|
logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
|
|
519
592
|
const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
|
|
520
593
|
const now = new Date().toISOString();
|
|
@@ -614,8 +687,8 @@ class CardanoIndexer {
|
|
|
614
687
|
return allRows;
|
|
615
688
|
}
|
|
616
689
|
/**
|
|
617
|
-
* UTxOs of a payment credential without a provider: addresses from the crawled
|
|
618
|
-
*
|
|
690
|
+
* UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
|
|
691
|
+
* UTxO set (see openLedgerUtxos).
|
|
619
692
|
* null = the crawled set cannot answer (not synced, no set, credential column still filling).
|
|
620
693
|
* An address first used in the last `confirmationDepth` blocks is not in the set yet.
|
|
621
694
|
*/
|
|
@@ -626,15 +699,38 @@ class CardanoIndexer {
|
|
|
626
699
|
const addresses = (rows ?? []).map(r => r.address);
|
|
627
700
|
if (addresses.length === 0)
|
|
628
701
|
return [];
|
|
702
|
+
return this.openLedgerUtxos(tx, addresses);
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Unspent outputs of addresses from the crawled set, checked against the node by output reference
|
|
706
|
+
* (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
|
|
707
|
+
* the cursor. Without a usable node, or when the check fails, the set as of the cursor.
|
|
708
|
+
*/
|
|
709
|
+
async openLedgerUtxos(tx, addresses) {
|
|
710
|
+
const rows = await this.ledgerUtxosOf(tx, addresses);
|
|
711
|
+
if (rows.length === 0)
|
|
712
|
+
return rows;
|
|
629
713
|
try {
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
714
|
+
const unspent = new Map();
|
|
715
|
+
for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
|
|
716
|
+
const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
|
|
717
|
+
if (live === null)
|
|
718
|
+
return rows;
|
|
719
|
+
for (const u of live)
|
|
720
|
+
unspent.set(`${u.txHash}#${u.outputIndex}`, u);
|
|
721
|
+
}
|
|
722
|
+
// The node's answer names the reference script, which a snapshot row from a file import lacks
|
|
723
|
+
return rows.flatMap(u => {
|
|
724
|
+
const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
|
|
725
|
+
if (!live)
|
|
726
|
+
return [];
|
|
727
|
+
return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
|
|
728
|
+
});
|
|
633
729
|
}
|
|
634
730
|
catch (err) {
|
|
635
|
-
logger.warn(`
|
|
731
|
+
logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
|
|
732
|
+
return rows;
|
|
636
733
|
}
|
|
637
|
-
return this.ledgerUtxosOf(tx, addresses);
|
|
638
734
|
}
|
|
639
735
|
/** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
|
|
640
736
|
async ledgerUtxosOf(tx, addresses) {
|
|
@@ -825,13 +921,17 @@ class CardanoIndexer {
|
|
|
825
921
|
}
|
|
826
922
|
/** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
|
|
827
923
|
async indexNetworkInformation(tx) {
|
|
924
|
+
const netEntity = (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
|
|
925
|
+
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
926
|
+
return netEntity;
|
|
927
|
+
}
|
|
928
|
+
/** Network information from the backend; circulating supply from the crawled UTxO set when current. */
|
|
929
|
+
async resolveNetworkInformation(tx) {
|
|
828
930
|
const netInfo = await this.client.getNetworkInformation();
|
|
829
931
|
const circulating = (await this.localCoverage(tx))?.ledger
|
|
830
932
|
? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
|
|
831
933
|
: null;
|
|
832
|
-
|
|
833
|
-
await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
|
|
834
|
-
return netEntity;
|
|
934
|
+
return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
|
|
835
935
|
}
|
|
836
936
|
/** Index a block by hash, with best-effort epoch enrichment. */
|
|
837
937
|
async indexBlock(tx, blockHash) {
|
|
@@ -854,6 +954,8 @@ class CardanoIndexer {
|
|
|
854
954
|
* atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
|
|
855
955
|
*/
|
|
856
956
|
async indexBlockFull(tx, blockData, txs) {
|
|
957
|
+
// Memo updates of a rolled-back attempt must not survive into this one.
|
|
958
|
+
this.pendingCommit = [];
|
|
857
959
|
// Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
|
|
858
960
|
// (memoized) and accept the in-tx fetch.
|
|
859
961
|
let epoch;
|
|
@@ -862,14 +964,36 @@ class CardanoIndexer {
|
|
|
862
964
|
epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
|
|
863
965
|
const epochRows = [...this.crawlEpochCache.values()]
|
|
864
966
|
.map((entry) => entry.row)
|
|
865
|
-
.filter((row) => row !== undefined);
|
|
866
|
-
if (epochRows.length)
|
|
967
|
+
.filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
|
|
968
|
+
if (epochRows.length) {
|
|
867
969
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
970
|
+
this.pendingCommit.push(() => { for (const row of epochRows)
|
|
971
|
+
this.crawlEpochWritten.add(row); });
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
// Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
|
|
975
|
+
// Decided up front so input resolution and the ledger apply share one read of the set.
|
|
976
|
+
const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
|
|
977
|
+
const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
|
|
978
|
+
let anchorVerified = false;
|
|
979
|
+
if (ledgerDue && !priorInvalidation) {
|
|
980
|
+
anchorVerified = this.utxoAnchorVerified;
|
|
981
|
+
if (!anchorVerified) {
|
|
982
|
+
const anchor = this.utxoAnchor;
|
|
983
|
+
anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
|
|
984
|
+
// Remembered only once this transaction commits, like the other crawl memos.
|
|
985
|
+
if (anchorVerified)
|
|
986
|
+
this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
|
|
987
|
+
this.utxoAnchorVerified = true; });
|
|
988
|
+
}
|
|
868
989
|
}
|
|
990
|
+
const ledgerLookup = anchorVerified
|
|
991
|
+
? { hashes: new Set(), rows: new Map(), assets: new Map() }
|
|
992
|
+
: undefined;
|
|
869
993
|
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
870
994
|
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
871
995
|
// corrected fee changes the block's fee total.
|
|
872
|
-
await this.resolveInputs(tx, txs);
|
|
996
|
+
await this.resolveInputs(tx, txs, ledgerLookup);
|
|
873
997
|
this.applyCollateralFees(blockData, txs);
|
|
874
998
|
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
875
999
|
await this.removeSupersededBlocks(tx, blockData);
|
|
@@ -892,6 +1016,8 @@ class CardanoIndexer {
|
|
|
892
1016
|
: [];
|
|
893
1017
|
if (this.crawlCertificates)
|
|
894
1018
|
this.warnIfCertificatesUnreported(txs);
|
|
1019
|
+
// Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
|
|
1020
|
+
const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
|
|
895
1021
|
// Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
|
|
896
1022
|
// idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
|
|
897
1023
|
const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
|
|
@@ -911,16 +1037,17 @@ class CardanoIndexer {
|
|
|
911
1037
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
|
|
912
1038
|
if (withdrawalRows.length)
|
|
913
1039
|
await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
1040
|
+
if (redeemerRows.length)
|
|
1041
|
+
await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
|
|
1042
|
+
// Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
|
|
1043
|
+
if (ledgerDue) {
|
|
1044
|
+
if (priorInvalidation) {
|
|
918
1045
|
// Decided in an earlier attempt of this block whose transaction rolled back: re-write
|
|
919
1046
|
// the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
|
|
920
|
-
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error:
|
|
1047
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
|
|
921
1048
|
}
|
|
922
|
-
else if (
|
|
923
|
-
const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs);
|
|
1049
|
+
else if (ledgerLookup) {
|
|
1050
|
+
const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
|
|
924
1051
|
if (ledger.missing) {
|
|
925
1052
|
logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
|
|
926
1053
|
'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
|
|
@@ -987,16 +1114,16 @@ class CardanoIndexer {
|
|
|
987
1114
|
'the crawl runs on Ogmios chain-sync or Koios');
|
|
988
1115
|
}
|
|
989
1116
|
/**
|
|
990
|
-
* Backfill address
|
|
991
|
-
* then earlier-indexed outputs from the DB. Inputs that
|
|
1117
|
+
* Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
|
|
1118
|
+
* own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
|
|
1119
|
+
* already carry an address are skipped.
|
|
992
1120
|
*/
|
|
993
|
-
async resolveInputs(tx, txs) {
|
|
994
|
-
// 1. In-memory index of this block's outputs (txHash#outputIndex ->
|
|
1121
|
+
async resolveInputs(tx, txs, ledger) {
|
|
1122
|
+
// 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
|
|
995
1123
|
const blockOutputs = new Map();
|
|
996
1124
|
for (const t of txs) {
|
|
997
|
-
for (const o of t.outputs ?? [])
|
|
998
|
-
blockOutputs.set(`${t.hash}#${o.outputIndex}`,
|
|
999
|
-
}
|
|
1125
|
+
for (const o of t.outputs ?? [])
|
|
1126
|
+
blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
|
|
1000
1127
|
}
|
|
1001
1128
|
// 2. Collect inputs still needing resolution after the same-block pass
|
|
1002
1129
|
const unresolved = [];
|
|
@@ -1008,7 +1135,8 @@ class CardanoIndexer {
|
|
|
1008
1135
|
const local = blockOutputs.get(key);
|
|
1009
1136
|
if (local) {
|
|
1010
1137
|
input.address = local.address;
|
|
1011
|
-
input.amount = local.amount;
|
|
1138
|
+
input.amount = local.amount ?? [];
|
|
1139
|
+
copyUtxoData(input, local.dataHash, local.inlineDatum, local.referenceScriptHash);
|
|
1012
1140
|
}
|
|
1013
1141
|
else {
|
|
1014
1142
|
unresolved.push({ input, key });
|
|
@@ -1017,7 +1145,23 @@ class CardanoIndexer {
|
|
|
1017
1145
|
}
|
|
1018
1146
|
if (!unresolved.length)
|
|
1019
1147
|
return;
|
|
1020
|
-
// 3.
|
|
1148
|
+
// 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
|
|
1149
|
+
// reuses the same lookup instead of reading these outpoints a second time.
|
|
1150
|
+
if (ledger) {
|
|
1151
|
+
await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
|
|
1152
|
+
for (let i = unresolved.length - 1; i >= 0; i--) {
|
|
1153
|
+
const row = ledger.rows.get(unresolved[i].key);
|
|
1154
|
+
if (!row)
|
|
1155
|
+
continue;
|
|
1156
|
+
unresolved[i].input.address = row.address;
|
|
1157
|
+
unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
|
|
1158
|
+
copyUtxoData(unresolved[i].input, row.utxo_dataHash, row.utxo_inlineDatum, row.utxo_referenceScriptHash);
|
|
1159
|
+
unresolved.splice(i, 1);
|
|
1160
|
+
}
|
|
1161
|
+
if (!unresolved.length)
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
// 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
|
|
1021
1165
|
// never exceeds a driver's bind-variable cap
|
|
1022
1166
|
const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
|
|
1023
1167
|
const hashBySeq = new Map();
|
|
@@ -1025,7 +1169,7 @@ class CardanoIndexer {
|
|
|
1025
1169
|
if (k.txSeq != null)
|
|
1026
1170
|
hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
|
|
1027
1171
|
}
|
|
1028
|
-
const
|
|
1172
|
+
const outByKey = new Map();
|
|
1029
1173
|
const amtByKey = new Map();
|
|
1030
1174
|
for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
|
|
1031
1175
|
const [outRows, assetRows] = await Promise.all([
|
|
@@ -1033,7 +1177,7 @@ class CardanoIndexer {
|
|
|
1033
1177
|
tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
|
|
1034
1178
|
]);
|
|
1035
1179
|
for (const r of outRows) {
|
|
1036
|
-
|
|
1180
|
+
outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
|
|
1037
1181
|
}
|
|
1038
1182
|
for (const r of assetRows) {
|
|
1039
1183
|
const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
|
|
@@ -1043,9 +1187,11 @@ class CardanoIndexer {
|
|
|
1043
1187
|
}
|
|
1044
1188
|
}
|
|
1045
1189
|
for (const { input, key } of unresolved) {
|
|
1046
|
-
const
|
|
1047
|
-
if (
|
|
1048
|
-
input.address =
|
|
1190
|
+
const out = outByKey.get(key);
|
|
1191
|
+
if (out?.address_address != null)
|
|
1192
|
+
input.address = out.address_address;
|
|
1193
|
+
if (out)
|
|
1194
|
+
copyUtxoData(input, out.utxo_dataHash, out.utxo_inlineDatum, out.utxo_referenceScriptHash);
|
|
1049
1195
|
const amt = amtByKey.get(key);
|
|
1050
1196
|
if (amt)
|
|
1051
1197
|
input.amount = amt;
|
|
@@ -1180,9 +1326,10 @@ class CardanoIndexer {
|
|
|
1180
1326
|
for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
|
|
1181
1327
|
await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
|
|
1182
1328
|
}
|
|
1183
|
-
// Memoize also the units mapBareAsset rejected, so they cost no SELECT per block.
|
|
1184
|
-
|
|
1185
|
-
|
|
1329
|
+
// Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
|
|
1330
|
+
// the commit: a rolled-back block must write its bare rows again.
|
|
1331
|
+
this.pendingCommit.push(() => { for (const unit of missing)
|
|
1332
|
+
this.noteAssetSeen(unit); });
|
|
1186
1333
|
if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
|
|
1187
1334
|
for (const row of rows) {
|
|
1188
1335
|
if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
|
|
@@ -1352,24 +1499,30 @@ class CardanoIndexer {
|
|
|
1352
1499
|
}
|
|
1353
1500
|
/** Index an account by stake address, plus its addresses when it has any. */
|
|
1354
1501
|
async indexAccount(tx, stakeAddress) {
|
|
1502
|
+
const accountInfo = await this.resolveAccount(tx, stakeAddress);
|
|
1503
|
+
const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
|
|
1504
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
1505
|
+
if (accountEntity.hasAddresses) {
|
|
1506
|
+
await this._ensureAddresses(tx, accountInfo.addresses);
|
|
1507
|
+
}
|
|
1508
|
+
return accountEntity;
|
|
1509
|
+
}
|
|
1510
|
+
/** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
|
|
1511
|
+
async resolveAccount(tx, stakeAddress) {
|
|
1355
1512
|
const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
|
|
1356
|
-
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
|
|
1513
|
+
// controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
|
|
1514
|
+
// the addresses come from the set too (the node has no stake-key -> address index)
|
|
1357
1515
|
if ((await this.localCoverage(tx))?.ledger) {
|
|
1358
1516
|
const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
|
|
1359
1517
|
accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
|
|
1518
|
+
accountInfo.addresses = await this.localAccountAddresses(tx, stakeAddress);
|
|
1360
1519
|
}
|
|
1361
1520
|
if (accountInfo.withdrawalsSum === '0') {
|
|
1362
1521
|
const local = await this.localWithdrawalsSum(tx, stakeAddress);
|
|
1363
1522
|
if (local != null)
|
|
1364
1523
|
accountInfo.withdrawalsSum = local;
|
|
1365
1524
|
}
|
|
1366
|
-
|
|
1367
|
-
await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
|
|
1368
|
-
const addresses = accountInfo.addresses.map(a => a.address);
|
|
1369
|
-
if (accountEntity.hasAddresses) {
|
|
1370
|
-
await this._ensureAddresses(tx, addresses);
|
|
1371
|
-
}
|
|
1372
|
-
return accountEntity;
|
|
1525
|
+
return accountInfo;
|
|
1373
1526
|
}
|
|
1374
1527
|
/** Index a DRep by bech32 id. */
|
|
1375
1528
|
async indexDrep(tx, drepId) {
|
|
@@ -1380,17 +1533,21 @@ class CardanoIndexer {
|
|
|
1380
1533
|
}
|
|
1381
1534
|
/** Index a pool by id. */
|
|
1382
1535
|
async indexPool(tx, poolId) {
|
|
1536
|
+
const poolEntity = (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
|
|
1537
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
1538
|
+
return poolEntity;
|
|
1539
|
+
}
|
|
1540
|
+
/** Pool from the backend with crawled block counts and the snapshot's active stake. */
|
|
1541
|
+
async resolvePool(tx, poolId) {
|
|
1383
1542
|
const poolInfo = { ...(await this.client.getPool(poolId)), ...(await this.localPoolBlocks(tx, poolId)) };
|
|
1384
1543
|
// The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
|
|
1385
1544
|
if (poolInfo.activeStake === '0')
|
|
1386
1545
|
Object.assign(poolInfo, await this.snapshotActiveStake(tx, poolId));
|
|
1387
|
-
|
|
1388
|
-
await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
|
|
1389
|
-
return poolEntity;
|
|
1546
|
+
return poolInfo;
|
|
1390
1547
|
}
|
|
1391
1548
|
/** Index an asset by unit (policyId + assetNameHex). */
|
|
1392
1549
|
async indexAsset(tx, unit) {
|
|
1393
|
-
const assetInfo =
|
|
1550
|
+
const assetInfo = await this.resolveAssetInfo(tx, unit);
|
|
1394
1551
|
const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
|
|
1395
1552
|
await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
|
|
1396
1553
|
return assetEntity;
|
|
@@ -1424,6 +1581,10 @@ class CardanoIndexer {
|
|
|
1424
1581
|
const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
|
|
1425
1582
|
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
|
|
1426
1583
|
}
|
|
1584
|
+
if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
|
|
1585
|
+
const buildId = buildResult.id;
|
|
1586
|
+
await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildRedeemers).entries(txbuildResult.redeemers.map(r => ({ build_id: buildId, tag: r.tag, redeemerIndex: r.index, mem: Number(r.mem), steps: Number(r.steps) }))));
|
|
1587
|
+
}
|
|
1427
1588
|
if (buildResult.id && buildreq.senderAddress) {
|
|
1428
1589
|
await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
|
|
1429
1590
|
}
|
|
@@ -1444,6 +1605,10 @@ class CardanoIndexer {
|
|
|
1444
1605
|
async indexPlutusSpendBuildResult(tx, buildreq) {
|
|
1445
1606
|
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
|
|
1446
1607
|
}
|
|
1608
|
+
/** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
|
|
1609
|
+
async indexPlutusBuildResult(tx, buildreq) {
|
|
1610
|
+
return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
|
|
1611
|
+
}
|
|
1447
1612
|
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
1448
1613
|
async indexProtocolParameters(tx) {
|
|
1449
1614
|
const network = this.client.network;
|
|
@@ -1653,12 +1818,16 @@ class CardanoIndexer {
|
|
|
1653
1818
|
//-----------------------------------------------------------------------------
|
|
1654
1819
|
// Private Helpers
|
|
1655
1820
|
//-----------------------------------------------------------------------------
|
|
1656
|
-
/**
|
|
1657
|
-
|
|
1821
|
+
/**
|
|
1822
|
+
* Index the addresses of an account with bounded concurrency. The address data the account
|
|
1823
|
+
* carries (from the backend, or from the crawled set) is used as is, so an account costs no
|
|
1824
|
+
* request per address; an entry without UTxOs is fetched.
|
|
1825
|
+
*/
|
|
1826
|
+
async _ensureAddresses(tx, accountAddresses) {
|
|
1658
1827
|
const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
|
|
1659
|
-
for (let i = 0; i <
|
|
1660
|
-
const chunk =
|
|
1661
|
-
await Promise.all(chunk.map(
|
|
1828
|
+
for (let i = 0; i < accountAddresses.length; i += concurrency) {
|
|
1829
|
+
const chunk = accountAddresses.slice(i, i + concurrency);
|
|
1830
|
+
await Promise.all(chunk.map(a => this.indexAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined)));
|
|
1662
1831
|
}
|
|
1663
1832
|
}
|
|
1664
1833
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CardanoClient } from './cardano-client';
|
|
2
|
-
import type {
|
|
2
|
+
import type { UTxO } from '../utils/types';
|
|
3
|
+
import type { TxBuildRequest, TxBuildPlutusRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
|
|
3
4
|
import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
|
|
4
5
|
import { LedgerProtocolParameter } from '#cds-models/CardanoODataService';
|
|
5
6
|
/** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
|
|
@@ -9,6 +10,10 @@ export declare class CardanoTransactionBuilder {
|
|
|
9
10
|
private initialized;
|
|
10
11
|
/** @param client UTxO source for coin selection */
|
|
11
12
|
constructor(client: CardanoClient);
|
|
13
|
+
/** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
|
|
14
|
+
private addressUtxoSource;
|
|
15
|
+
/** Read sender UTxOs from `source` first; the node's address query is the fallback. */
|
|
16
|
+
setAddressUtxoSource(source: (address: string) => Promise<UTxO[] | null>): void;
|
|
12
17
|
/** @param protocolParams optional; fetched from the backend when omitted */
|
|
13
18
|
init(protocolParams?: LedgerProtocolParameters): Promise<void>;
|
|
14
19
|
/** Lazily initialize and return the builder. */
|
|
@@ -27,6 +32,11 @@ export declare class CardanoTransactionBuilder {
|
|
|
27
32
|
buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
|
|
28
33
|
/** Build a Plutus spending transaction (consume a UTxO at a script address). */
|
|
29
34
|
buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
|
|
35
|
+
/**
|
|
36
|
+
* Several script inputs in one transaction: resolve every script UTxO and every reference-script
|
|
37
|
+
* UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
|
|
38
|
+
*/
|
|
39
|
+
buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
|
|
30
40
|
/**
|
|
31
41
|
* Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
|
|
32
42
|
* transaction. Spending an already-consumed script UTxO is the most common replay mistake —
|