@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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.
Files changed (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -13,31 +13,15 @@ const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
13
  const external_signer_1 = require("./external-signer");
14
14
  const { SELECT, UPDATE } = cds_1.default.ql;
15
15
  const logger = cds_1.default.log('SubmissionFinalizer');
16
- // Lazy require breaks the srv/server.ts <-> this-module import cycle (the
17
- // server calls redriveInterruptedSubmissions at boot; we need its app-context
18
- // getters at runtime only). Same pattern as src/plugin.ts.
16
+ // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
17
+ // getters are only needed at runtime.
19
18
  function server() {
20
- // eslint-disable-next-line @typescript-eslint/no-var-requires
21
19
  return require('../../server');
22
20
  }
23
21
  /**
24
- * Submit a verified+claimed signing request to the blockchain and persist the
25
- * outcome — DELIBERATELY outside the caller's request transaction.
26
- *
27
- * The caller must already have durably committed `status:'submitting'` (the
28
- * claim). This function then:
29
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
30
- * submits serialized and the SQLite busy-timeout could fire mid-network),
31
- * 2. on submit failure: marks the request 'failed' in its own committed tx
32
- * and rethrows (NOT rolled back to a pre-submit status — losing the
33
- * attempt would hide a tx the node may have accepted),
34
- * 3. on success: persists the submission + 'submitted' status in a committed
35
- * transaction.
36
- *
37
- * Crash window: a process death between (1) and (3) leaves the request durably
38
- * at 'submitting'. Deferred-path requests carry their signed CBOR on the row
39
- * and are re-driven at the next boot (redriveInterruptedSubmissions); sync-path
40
- * requests are left for the operator/poller exactly as before.
22
+ * Submit a claimed signing request (status 'submitting' already committed by the caller) and
23
+ * persist the outcome in detached transactions, so no DB lock is held across the network call.
24
+ * Submit failure → 'failed' in its own tx, then rethrow. A crash before finalize leaves 'submitting'.
41
25
  */
42
26
  async function submitAndFinalize(SigningRequests, params, afterFinalize) {
43
27
  // Persist the submission + 'submitted' status in its own committed transaction.
@@ -59,10 +43,8 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
59
43
  await server().getCardanoClient().submitTransaction(params.fullSignedTxCbor);
60
44
  }
61
45
  catch (submitErr) {
62
- // Already-submitted means the tx reached the mempool — e.g. the first backend accepted
63
- // it but its response was lost and a fallback observed the duplicate. That is SUCCESS,
64
- // not failure: finalize it as 'submitted' (same as the happy path) instead of durably
65
- // recording a spurious 'failed' for a tx the node already holds.
46
+ // Already-submitted means the tx reached the mempool (e.g. first backend accepted it, response
47
+ // lost, fallback saw the duplicate): finalize as 'submitted' rather than recording a spurious 'failed'.
66
48
  if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
67
49
  logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
68
50
  return finalizeSubmitted();
@@ -78,16 +60,9 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
78
60
  return finalizeSubmitted();
79
61
  }
80
62
  /**
81
- * Deferred-submit scheduler (KNOWN_ISSUES #11, Layer 2).
82
- *
83
- * Called by an action handler AFTER verify + claim ran on the CALLER's
84
- * transaction. Hooks the request's post-commit event: only once the caller's
85
- * root transaction has committed (claim durable, pooled connection released)
86
- * does the network submit + finalize run — detached via setImmediate +
87
- * runWithoutAmbientTx, so no ambient transaction is held across it.
88
- *
89
- * If the caller's transaction rolls back instead, 'succeeded' never fires and
90
- * nothing was claimed — strictly consistent.
63
+ * Deferred submit: runs submitAndFinalize only after the caller's root transaction has committed
64
+ * (claim durable, connection released), detached via setImmediate + runWithoutAmbientTx.
65
+ * If the caller rolls back, 'succeeded' never fires and nothing was claimed.
91
66
  */
92
67
  function scheduleDeferredSubmit(req, SigningRequests, params) {
93
68
  req.on('succeeded', () => {
@@ -104,15 +79,9 @@ function scheduleDeferredSubmit(req, SigningRequests, params) {
104
79
  });
105
80
  }
106
81
  /**
107
- * Boot-time recovery: re-drive submissions that were claimed on the deferred
108
- * path (status 'submitting' WITH persisted signedTxCbor) but never finalized —
109
- * i.e. the process died between the caller's commit and the detached submit.
110
- *
111
- * Safe to repeat: a tx the node already holds finalizes as 'submitted' via the
112
- * TransactionAlreadySubmittedError path in submitAndFinalize. Rows at
113
- * 'submitting' WITHOUT signed CBOR (sync-path crash window) are deliberately
114
- * left untouched for the operator/poller, exactly as before Layer 2.
115
- *
82
+ * Boot-time recovery: re-drive rows at 'submitting' WITH persisted signedTxCbor (process died between
83
+ * the caller's commit and the detached submit). Idempotent: a tx the node already holds finalizes as
84
+ * 'submitted'. Rows without signed CBOR are left for the operator/poller.
116
85
  * @returns number of rows re-driven (attempted, not necessarily succeeded)
117
86
  */
118
87
  async function redriveInterruptedSubmissions() {
@@ -126,8 +95,7 @@ async function redriveInterruptedSubmissions() {
126
95
  let attempted = 0;
127
96
  for (const row of rows) {
128
97
  try {
129
- // Re-verify from the persisted CBOR (deterministic — it passed at claim
130
- // time; this recomputes the witness metadata the finalize step persists).
98
+ // Re-verify from the persisted CBOR to recompute the witness metadata the finalize step persists.
131
99
  const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(row.signedTxCbor, row.txBodyHash);
132
100
  attempted++;
133
101
  await submitAndFinalize(SigningRequests, {
@@ -142,9 +110,8 @@ async function redriveInterruptedSubmissions() {
142
110
  logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Interrupted submission re-driven');
143
111
  }
144
112
  catch (err) {
145
- // submitAndFinalize marked the row 'failed' on submit errors; verification
146
- // errors leave it at 'submitting' for manual inspection (should not happen
147
- // for CBOR that verified once).
113
+ // Submit errors already marked the row 'failed'; verification errors leave it at
114
+ // 'submitting' for manual inspection.
148
115
  logger.error({ err, signingRequestId: row.id }, 'Re-drive of interrupted submission failed');
149
116
  }
150
117
  }
@@ -0,0 +1,33 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
+ /**
4
+ * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
+ * serving other ODATANO instances from what this one has indexed. The rows hold the ledger view
6
+ * (see ledgerView), so the phase-2 flag follows from them: a valid transaction always spends a
7
+ * regular input. Not stored, so absent: `totalCollateral` and `outputAmount`.
8
+ */
9
+ type Row = Record<string, unknown>;
10
+ /** `Blocks` row -> BlockData. */
11
+ export declare function blockRowToData(row: Row): BlockData;
12
+ /** A stored block by hash; null when not indexed. */
13
+ export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
14
+ /** A stored block by height; null when not indexed. */
15
+ export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
16
+ /**
17
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
18
+ * the first missing height, so a caller never walks over a gap.
19
+ */
20
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
21
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
22
+ export declare function lacksOutpoints(t: ProviderTransaction): boolean;
23
+ /** Stored transactions by hash (missing hashes are absent from the map). */
24
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
25
+ /**
26
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
27
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
28
+ */
29
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
30
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
31
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
32
+ export {};
33
+ //# sourceMappingURL=stored-chain.d.ts.map
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.blockRowToData = blockRowToData;
7
+ exports.readBlock = readBlock;
8
+ exports.readBlockByHeight = readBlockByHeight;
9
+ exports.readNextBlocks = readNextBlocks;
10
+ exports.lacksOutpoints = lacksOutpoints;
11
+ exports.readTransactionsByHash = readTransactionsByHash;
12
+ exports.readBlockTransactions = readBlockTransactions;
13
+ exports.readTransactionMetadata = readTransactionMetadata;
14
+ const cds_1 = __importDefault(require("@sap/cds"));
15
+ const client_1 = require("@cardano-ogmios/client");
16
+ const cardano_1 = require("#cds-models/odatano/cardano");
17
+ const collections_1 = require("../utils/collections");
18
+ const { SELECT } = cds_1.default.ql;
19
+ const num = (v) => Number(v ?? 0);
20
+ const numOrNull = (v) => (v == null ? null : Number(v));
21
+ const str = (v) => (v == null ? '' : String(v));
22
+ /** `Blocks` row -> BlockData. */
23
+ function blockRowToData(row) {
24
+ return {
25
+ time: Math.floor(Date.parse(str(row.time)) / 1000),
26
+ height: numOrNull(row.height),
27
+ hash: str(row.hash),
28
+ slot: numOrNull(row.slot),
29
+ slotLeader: str(row.slotLeader),
30
+ epoch: numOrNull(row.epochNumber),
31
+ epochSlot: numOrNull(row.epochSlot),
32
+ size: num(row.size),
33
+ txCount: num(row.txCount),
34
+ fees: row.fees == null ? null : String(row.fees),
35
+ };
36
+ }
37
+ /** A stored block by hash; null when not indexed. */
38
+ async function readBlock(db, hash) {
39
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ hash }));
40
+ return row ? blockRowToData(row) : null;
41
+ }
42
+ /** A stored block by height; null when not indexed. */
43
+ async function readBlockByHeight(db, height) {
44
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
45
+ return row ? blockRowToData(row) : null;
46
+ }
47
+ /**
48
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
49
+ * the first missing height, so a caller never walks over a gap.
50
+ */
51
+ async function readNextBlocks(db, afterHeight, count) {
52
+ const rows = await db.run(
53
+ // one operator per column object: `{ '>': a, '<=': b }` renders as `height > a <= b`
54
+ SELECT.from(cardano_1.Blocks).where({ height: { between: afterHeight + 1, and: afterHeight + count } }).orderBy('height asc'));
55
+ const out = [];
56
+ let expected = afterHeight + 1;
57
+ for (const row of rows ?? []) {
58
+ if (num(row.height) !== expected)
59
+ break;
60
+ out.push(blockRowToData(row));
61
+ expected++;
62
+ }
63
+ return out;
64
+ }
65
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
66
+ function lacksOutpoints(t) {
67
+ return (t.inputs ?? []).some(i => i.txHash == null);
68
+ }
69
+ /** Stored transactions by hash (missing hashes are absent from the map). */
70
+ async function readTransactionsByHash(db, hashes) {
71
+ const rows = [];
72
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
73
+ rows.push(...((await db.run(SELECT.from(cardano_1.Transactions).where({ hash: { in: hashChunk } }))) ?? []));
74
+ }
75
+ const txs = await assembleTransactions(db, rows);
76
+ return new Map(txs.map(t => [t.hash, t]));
77
+ }
78
+ /**
79
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
80
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
81
+ */
82
+ async function readBlockTransactions(db, blockHash) {
83
+ const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
84
+ if (!block)
85
+ return null;
86
+ const rows = await db.run(SELECT.from(cardano_1.Transactions).where({ blockHash }).orderBy('txIndex asc'));
87
+ if ((rows ?? []).length !== num(block.txCount))
88
+ return null;
89
+ return assembleTransactions(db, rows ?? []);
90
+ }
91
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
92
+ async function readTransactionMetadata(db, txHash) {
93
+ const known = await db.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ hash: txHash }));
94
+ if (!known)
95
+ return null;
96
+ const rows = await db.run(SELECT.from(cardano_1.TransactionMetadata_).where({ tx_hash: txHash }));
97
+ return (rows ?? []).map(metadataRow);
98
+ }
99
+ function metadataRow(r) {
100
+ return {
101
+ txHash: str(r.tx_hash),
102
+ label: str(r.label),
103
+ json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
104
+ };
105
+ }
106
+ /** Amount list with lovelace first, as the providers deliver it. */
107
+ function amounts(assets) {
108
+ const list = assets.map(a => ({ unit: str(a.unit), quantity: str(a.asset_quantity) }));
109
+ return [...list.filter(a => a.unit === 'lovelace'), ...list.filter(a => a.unit !== 'lovelace')];
110
+ }
111
+ function groupBy(rows, key) {
112
+ const out = new Map();
113
+ for (const r of rows) {
114
+ const k = key(r);
115
+ const list = out.get(k);
116
+ if (list)
117
+ list.push(r);
118
+ else
119
+ out.set(k, [r]);
120
+ }
121
+ return out;
122
+ }
123
+ /** Transactions rows + their child tables -> provider transactions, in the order of `rows`. */
124
+ async function assembleTransactions(db, rows) {
125
+ if (rows.length === 0)
126
+ return [];
127
+ const seqs = rows.map(r => r.txSeq);
128
+ const hashes = rows.map(r => str(r.hash));
129
+ const fetchIn = async (entity, column, keys) => {
130
+ const out = [];
131
+ for (const c of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
132
+ out.push(...((await db.run(SELECT.from(entity).where({ [column]: { in: c } }))) ?? []));
133
+ }
134
+ return out;
135
+ };
136
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers] = await Promise.all([
137
+ fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
138
+ fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
139
+ fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
140
+ fetchIn(cardano_1.TransactionOutputAssets, 'output_txSeq', seqs),
141
+ fetchIn(cardano_1.TransactionMetadata_, 'tx_hash', hashes),
142
+ fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
143
+ fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
144
+ fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
145
+ fetchIn(cardano_1.TransactionRedeemers, 'tx_hash', hashes),
146
+ ]);
147
+ const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
148
+ const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
149
+ const outputsBySeq = groupBy(outputs, r => str(r.txSeq));
150
+ const outputAssetsByKey = groupBy(outputAssets, r => `${r.output_txSeq}#${r.output_outputIndex}`);
151
+ const metadataByHash = groupBy(metadata, r => str(r.tx_hash));
152
+ const certsByHash = groupBy(certificates, r => str(r.tx_hash));
153
+ const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
154
+ const mintsByHash = groupBy(mints, r => str(r.txHash));
155
+ const redeemersByHash = groupBy(redeemers, r => str(r.tx_hash));
156
+ return rows.map((t) => {
157
+ const seq = str(t.txSeq);
158
+ const hash = str(t.hash);
159
+ const txInputs = (inputsBySeq.get(seq) ?? [])
160
+ .sort((a, b) => num(a.inputIndex) - num(b.inputIndex))
161
+ .map(i => ({
162
+ address: str(i.address_address),
163
+ amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
164
+ // null on rows indexed before the outpoint was recorded, never a made-up reference
165
+ txHash: (i.spentTxHash ?? null),
166
+ outputIndex: numOrNull(i.spentOutputIndex),
167
+ dataHash: i.utxoData_dataHash ?? null,
168
+ inlineDatum: i.utxoData_inlineDatum ?? null,
169
+ referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
170
+ isCollateral: Boolean(i.isCollateral),
171
+ isReference: Boolean(i.isReference),
172
+ }));
173
+ // a phase-2 failure keeps only collateral and reference inputs, and its collateral return
174
+ const spendsCollaterals = txInputs.some(i => i.isCollateral) && !txInputs.some(i => !i.isCollateral && !i.isReference);
175
+ const txOutputs = (outputsBySeq.get(seq) ?? [])
176
+ .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
177
+ .map(o => ({
178
+ address: str(o.address_address),
179
+ amount: amounts(outputAssetsByKey.get(`${seq}#${o.outputIndex}`) ?? []),
180
+ txHash: hash,
181
+ outputIndex: num(o.outputIndex),
182
+ dataHash: o.utxo_dataHash ?? null,
183
+ inlineDatum: o.utxo_inlineDatum ?? null,
184
+ isCollateral: spendsCollaterals,
185
+ referenceScriptHash: o.utxo_referenceScriptHash ?? null,
186
+ }));
187
+ const certs = certsByHash.get(hash);
188
+ const withdrawn = withdrawalsByHash.get(hash);
189
+ const minted = mintsByHash.get(hash);
190
+ const redeemed = redeemersByHash.get(hash);
191
+ return {
192
+ hash,
193
+ blockHash: str(t.blockHash),
194
+ blockHeight: num(t.blockHeight),
195
+ slot: num(t.slot),
196
+ index: num(t.txIndex),
197
+ fee: str(t.fee ?? '0'),
198
+ deposit: str(t.deposit ?? '0'),
199
+ size: numOrNull(t.size),
200
+ blockTime: num(t.blockTime),
201
+ spendsCollaterals,
202
+ mint: minted?.map(m => ({
203
+ unit: str(m.unit),
204
+ quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
205
+ })),
206
+ inputs: txInputs,
207
+ outputs: txOutputs,
208
+ metadata: (metadataByHash.get(hash) ?? []).map(metadataRow),
209
+ certificates: certs?.map((c) => ({
210
+ certIndex: num(c.certIndex),
211
+ kind: str(c.kind),
212
+ stakeAddress: c.stakeAddress ?? null,
213
+ poolId: c.poolId ?? null,
214
+ drepId: c.drepId ?? null,
215
+ deposit: c.deposit == null ? null : String(c.deposit),
216
+ epoch: numOrNull(c.epoch),
217
+ })),
218
+ withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
219
+ redeemers: redeemed
220
+ ?.sort((a, b) => str(a.purpose).localeCompare(str(b.purpose)) || num(a.redeemerIndex) - num(b.redeemerIndex))
221
+ .map((r) => ({
222
+ purpose: str(r.purpose),
223
+ index: num(r.redeemerIndex),
224
+ data: str(r.data),
225
+ mem: str(r.mem),
226
+ steps: str(r.steps),
227
+ txHash: r.spentTxHash ?? null,
228
+ outputIndex: numOrNull(r.spentOutputIndex),
229
+ policyId: r.policyId ?? null,
230
+ })),
231
+ };
232
+ });
233
+ }
234
+ //# sourceMappingURL=stored-chain.js.map