@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -9,31 +9,66 @@ const validators_1 = require("./utils/validators");
9
9
  const errors_1 = require("./utils/errors");
10
10
  const backend_request_handler_1 = require("./utils/backend-request-handler");
11
11
  const cbor_1 = require("./cbor");
12
+ const paging_1 = require("./utils/paging");
13
+ const CardanoODataService_1 = require("#cds-models/CardanoODataService");
14
+ const mappers_1 = require("./utils/mappers");
15
+ const tx_utils_1 = require("./utils/tx-utils");
16
+ const result_numbers_1 = require("./utils/result-numbers");
17
+ const navigation_1 = require("./utils/navigation");
18
+ const cardano_indexer_1 = require("./blockchain/cardano-indexer");
19
+ /** Pause between two reads of a waiting GetLatestTransactionsByAddress call. */
20
+ const ADDRESS_WAIT_POLL_MS = 5000;
21
+ /** Newest temporal slice per key; child tables keep one row per validFrom. */
22
+ function latestSlices(rows, keyOf) {
23
+ const seen = new Map();
24
+ for (const row of rows) {
25
+ const key = keyOf(row);
26
+ const prev = seen.get(key);
27
+ if (!prev || (row.validFrom ?? '') > (prev.validFrom ?? ''))
28
+ seen.set(key, row);
29
+ }
30
+ return Array.from(seen.values());
31
+ }
12
32
  const { SELECT } = cds_1.default.ql;
13
33
  const logger = cds_1.default.log(`CardanoService`);
14
- /**
15
- * Upper bound of the temporal window opened by {@link widenTemporalWindow}.
16
- * Generous on purpose: it only has to outlast the slowest index-on-miss (chained
17
- * backend timeouts of several calls) within ONE request.
18
- */
34
+ /** Pairs a provider read with the write of its result; the result type follows from the read. */
35
+ function indexPair(fetch, store) {
36
+ return { fetch, store };
37
+ }
38
+ // Fills misses without holding the request transaction while the provider answers: every missing
39
+ // key is read from the provider first, then all are stored. A row stored in the meantime is kept.
40
+ // Returns the row found or stored per key.
41
+ async function indexMissing(db, keys, exists, index) {
42
+ return (await prepareMissing(db, keys, exists, index)).store();
43
+ }
44
+ // The provider half of indexMissing: reads the missing keys from the provider and returns the
45
+ // write that stores them, so a caller can collect several before its first write.
46
+ async function prepareMissing(db, keys, exists, index) {
47
+ const found = await (0, tx_utils_1.readOutside)(db, async (d) => {
48
+ const rows = [];
49
+ for (const key of keys)
50
+ rows.push(await exists(d, key));
51
+ return rows;
52
+ });
53
+ const fetched = new Map();
54
+ for (const [i, key] of keys.entries()) {
55
+ if (!found[i])
56
+ fetched.set(i, await index.fetch(db, key));
57
+ }
58
+ return {
59
+ store: async () => {
60
+ const rows = [...found];
61
+ for (const [i, value] of fetched)
62
+ rows[i] = (await exists(db, keys[i])) || await index.store(db, value);
63
+ return rows;
64
+ },
65
+ };
66
+ }
67
+ /** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
19
68
  const TEMPORAL_WINDOW_SLACK_MS = 60 * 60 * 1000;
20
- /**
21
- * Let this request see temporal slices that IT writes during index-on-miss.
22
- *
23
- * CAP filters temporal entities (Pools, Assets, Dreps, Addresses, Accounts, …)
24
- * with `validFrom < $valid.to AND validTo > $valid.from`. The DB session reads
25
- * both bounds from the request's `_` bag (`VALID-FROM` / `VALID-TO`) when the
26
- * transaction begins (HANA) or on first use (sqlite) and otherwise defaults to
27
- * `now` / `now + 1ms` — a window that is closed long before the backend fetch
28
- * returns, so a slice stamped after the fetch would be invisible to the
29
- * `req.query` re-read that honours `$expand` / `$select` (KNOWN_ISSUES #13).
30
- *
31
- * Only the UPPER bound is moved. No slice is ever future-dated (every mapper
32
- * stamps `validFrom = now`), so the only additional rows this admits are the
33
- * ones this very request writes; expired rows stay hidden (`validTo >
34
- * $valid.from` is untouched). Explicit `sap-valid-*` query options are left
35
- * alone. Must run before the handler's first DB statement.
36
- */
69
+ // CAP's temporal window is fixed at transaction start, so a slice written by index-on-miss would be
70
+ // invisible to the re-read. This widens the upper bound unless the client set `sap-valid-*`.
71
+ // Must run before the request transaction's first statement.
37
72
  function widenTemporalWindow(req) {
38
73
  const q = req.http?.req?.query;
39
74
  if (q && (q['sap-valid-at'] || q['sap-valid-from'] || q['sap-valid-to']))
@@ -41,9 +76,7 @@ function widenTemporalWindow(req) {
41
76
  const now = Date.now();
42
77
  const from = new Date(now).toISOString();
43
78
  const to = new Date(now + TEMPORAL_WINDOW_SLACK_MS).toISOString();
44
- // The DB session context is built from the context the transaction was opened
45
- // with — `req` for our `cds.tx(req)`, the root context if a generic handler got
46
- // there first — so stamp both bags.
79
+ // The DB session reads the bag of whichever context opened the transaction; stamp both.
47
80
  const r = req;
48
81
  for (const bag of new Set([r._, r.context?._])) {
49
82
  if (!bag)
@@ -52,51 +85,41 @@ function widenTemporalWindow(req) {
52
85
  bag['VALID-TO'] = to;
53
86
  }
54
87
  }
55
- /**
56
- * Factory: READ handler with index-on-miss behavior.
57
- * If a key is provided, checks cache first; indexes if missing — then runs the
58
- * client's own query so `$expand` / `$select` are honoured on the keyed branch
59
- * too (KNOWN_ISSUES #13: returning the bare row silently dropped them).
60
- * If no key, passes through to generic req.query.
61
- */
62
- function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
88
+ function indexOnMissRead(entity, reqKeyField, validate, index, options) {
63
89
  const dbKey = options?.entityKeyField || reqKeyField;
64
90
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
91
+ const exists = options?.exists ?? ((d, k) => d.run(SELECT.one.from(entity).where({ [dbKey]: k })));
65
92
  return async (req) => {
66
- const key = req.data?.[reqKeyField];
67
- // explicit null/undefined check — `key &&` skipped validation for falsy keys
68
- // like epoch=0 or an empty string (the latter then hit the backend unvalidated)
93
+ const key = (0, navigation_1.readKey)(req, reqKeyField);
94
+ // Explicit null check: falsy keys such as epoch=0 or '' must still be validated.
69
95
  if (key !== undefined && key !== null && validate && !validate(key))
70
96
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
71
97
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
72
98
  if (key !== undefined && key !== null) {
73
- widenTemporalWindow(req); // before the first DB statement — see doc comment
74
- // CAP temporal aspect auto-filters expired records (validTo < now → not returned)
75
- const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
76
- // Populate the row (+ compositions) on a miss, then let CAP run the client's
77
- // query — one extra SELECT per keyed read, but $expand/$select (and the
78
- // temporal filter of the projection) apply exactly as on the un-keyed path.
79
- if (!existing)
80
- await indexFn(db, key);
81
- // The client's query is the ONLY authority on what comes back. Falling back
82
- // to `existing` (or the indexer's return value) when it matches nothing
83
- // answers a request the client never made — a second key that does not
84
- // match, or an excluding $filter, would get a sibling row with a 200
85
- // instead of a 404 (KNOWN_ISSUES #15). Non-temporal entities always see
86
- // their fresh rows here; temporal ones rely on widenTemporalWindow above,
87
- // and if that ever stops working the failure is a loud 404 covered by
88
- // test/integration/keyed-read-expand.test.ts, not silently wrong data.
99
+ widenTemporalWindow(req);
100
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
101
+ await indexMissing(db, [key], exists, index);
102
+ // The client's query is the only authority on the result: never answer with the row
103
+ // found here, or an excluding $filter / second key would yield a sibling row instead of 404.
89
104
  }
90
105
  return db.run(req.query);
91
106
  });
92
107
  };
93
108
  }
94
- /**
95
- * Factory: Action handler with required key validation and index-on-miss.
96
- */
97
- function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, options) {
109
+ /** READ handler of an entity without a key in the request: stores its row on a miss, then runs the client's own query. */
110
+ function singletonRead(entity, index) {
111
+ return async (req) => (0, backend_request_handler_1.handleRequest)(req, async (db) => {
112
+ widenTemporalWindow(req);
113
+ await indexMissing(db, [null], (d) => d.run(SELECT.one.from(entity)), index);
114
+ return db.run(req.query);
115
+ });
116
+ }
117
+ /** Factory: action handler with required-key validation and index-on-miss. */
118
+ function indexOnMissAction(actionName, entity, reqKeyField, validate, index, options) {
98
119
  const dbKey = options?.entityKeyField || reqKeyField;
99
120
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
121
+ const byKey = (d, k) => d.run(SELECT.one.from(entity).where({ [dbKey]: k }));
122
+ const exists = options?.exists ?? byKey;
100
123
  return async (req) => {
101
124
  const key = req.data?.[reqKeyField];
102
125
  if (key == null)
@@ -104,260 +127,350 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
104
127
  if (!validate(key))
105
128
  (0, errors_1.rejectInvalid)(req, actionName, errMsg, reqKeyField);
106
129
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
107
- // CAP temporal aspect auto-filters expired records (validTo < now → not returned)
108
- const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
109
- if (!existing)
110
- return await indexFn(db, key);
111
- return existing;
130
+ widenTemporalWindow(req);
131
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
132
+ const [row] = await indexMissing(db, [key], exists, index);
133
+ // the stored row, as a repeated call answers it; the provider mapping may differ in shape
134
+ return (await byKey(db, key)) ?? row;
135
+ });
136
+ };
137
+ }
138
+ /** Addresses one collection read may index on a miss; more is a 400. */
139
+ const MAX_ADDRESSES_PER_READ = 10;
140
+ const numberVal = (v) => {
141
+ const n = Number(v?.val);
142
+ return Number.isInteger(n) && n >= 0 ? n : undefined;
143
+ };
144
+ const isRef = (t) => typeof t === 'object' && 'ref' in t;
145
+ const isVal = (t) => typeof t === 'object' && 'val' in t;
146
+ const isList = (t) => typeof t === 'object' && 'list' in t;
147
+ const isXpr = (t) => typeof t === 'object' && 'xpr' in t;
148
+ /** `address_address` or the association path `address/address`. */
149
+ function isAddressRef(t) {
150
+ if (!isRef(t))
151
+ return false;
152
+ const path = t.ref;
153
+ return (path.length === 1 && path[0] === 'address_address') || (path.length === 2 && path[0] === 'address' && path[1] === 'address');
154
+ }
155
+ const stringVal = (t) => t !== undefined && isVal(t) && typeof t.val === 'string' ? t.val : undefined;
156
+ /** Addresses a child-set read names: the navigation parent, or `address_address` in an `eq` or `in` filter. */
157
+ function addressesInReadQuery(req) {
158
+ const found = new Set();
159
+ const parent = req.data?.address_address;
160
+ if (typeof parent === 'string')
161
+ found.add(parent);
162
+ const walk = (tokens) => {
163
+ for (let i = 0; i < tokens.length; i++) {
164
+ const token = tokens[i];
165
+ if (typeof token === 'string')
166
+ continue;
167
+ if (isXpr(token)) {
168
+ walk(token.xpr);
169
+ continue;
170
+ }
171
+ const op = tokens[i + 1];
172
+ const right = tokens[i + 2];
173
+ if (isAddressRef(token) && op === '=') {
174
+ const value = stringVal(right);
175
+ if (value)
176
+ found.add(value);
177
+ }
178
+ else if (isAddressRef(token) && op === 'in' && right !== undefined && isList(right)) {
179
+ for (const item of right.list) {
180
+ const value = stringVal(item);
181
+ if (value)
182
+ found.add(value);
183
+ }
184
+ }
185
+ else if (right !== undefined && isAddressRef(right) && op === '=') {
186
+ const value = stringVal(token);
187
+ if (value)
188
+ found.add(value);
189
+ }
190
+ }
191
+ };
192
+ const query = req.query;
193
+ walk(('SELECT' in query && query.SELECT?.where) || []);
194
+ return Array.from(found);
195
+ }
196
+ /** READ handler for a child set of Addresses: indexes the named address on a miss, then runs the query. */
197
+ function addressChildRead(isIndexed, index) {
198
+ return async (req) => {
199
+ const addresses = addressesInReadQuery(req);
200
+ if (addresses.length > MAX_ADDRESSES_PER_READ) {
201
+ (0, errors_1.rejectInvalid)(req, 'address_address', `A read may name at most ${MAX_ADDRESSES_PER_READ} addresses`, 'address_address');
202
+ }
203
+ for (const address of addresses) {
204
+ if (!(0, validators_1.isValidBech32Address)(address))
205
+ (0, errors_1.rejectInvalid)(req, 'address_address', 'Invalid bech32 address format', 'address_address');
206
+ }
207
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
208
+ if (addresses.length) {
209
+ widenTemporalWindow(req);
210
+ await indexMissing(db, addresses, isIndexed, index);
211
+ }
212
+ return db.run(req.query);
112
213
  });
113
214
  };
114
215
  }
115
216
  // ---------------------------------------------------------------------------
116
217
  // Service Registration
117
218
  // ---------------------------------------------------------------------------
118
- /**
119
- * Cardano Service Implementation
120
- * Handles various Cardano blockchain data queries with index-on-miss behavior.
121
- */
219
+ /** CardanoODataService handlers: blockchain read queries with index-on-miss. */
122
220
  module.exports = (srv) => {
221
+ (0, result_numbers_1.answerNumbersAsText)(srv);
123
222
  logger.debug('Module loaded - registering handlers');
124
- // NOTE: for entities whose name is already plural-shaped (NetworkInformation,
125
- // TransactionMetadata, AssetHistory) cds-typer exports the SINGULAR class under the
126
- // plain name and the plural (entity-set) class with a trailing underscore. Handler
127
- // registration must use the plural class — under cds 10 registering `srv.on('READ',
128
- // <singular proxy>)` no longer matches incoming OData READs, so the generic CRUD
129
- // handler silently served those entities (empty results / 404 instead of
130
- // index-on-miss). All other names below already resolve to plural classes.
131
- const { NetworkInformation_: NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata_: TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory_: AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
132
- // Fail fast if a future edit reintroduces a SINGULAR class here (the cds-10 trap
133
- // above): a singular registration silently degrades to the generic CRUD handler.
134
- // Every cds-typer proxy carries an explicit is_singular marker we can assert on.
223
+ // For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
224
+ // exports the singular class under the plain name and the entity-set class with a trailing
225
+ // underscore. Handlers must register the entity-set class; a singular one never matches under cds 10.
226
+ const { NetworkInformation_: NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata_: TransactionMetadata, Pools, Accounts, Dreps, Assets, TransactionInputs, TransactionOutputs, AssetHistory_: AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
227
+ // Fail fast on a singular class: it would silently degrade to the generic CRUD handler.
135
228
  for (const [name, entity] of Object.entries({
136
229
  NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
137
230
  Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
138
- LedgerProtocolParameters, AddressTransactions,
231
+ LedgerProtocolParameters, AddressTransactions, TransactionInputs, TransactionOutputs,
139
232
  })) {
140
233
  if (entity?.is_singular) {
141
- throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class — ` +
234
+ throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class: ` +
142
235
  `READ handlers registered with it never match under cds 10. Destructure the ` +
143
236
  `plural entity-set class instead (e.g. '${name}_ as ${name}').`);
144
237
  }
145
238
  }
146
- // Helper: shorthand for indexer access
147
239
  const indexer = () => (0, server_1.getCardanoIndexer)();
240
+ // The read and the store half of each index-on-miss; the indexer is resolved per request.
241
+ const blockIndex = indexPair((db, hash) => indexer().fetchBlock(db, hash), (db, fetched) => indexer().storeBlock(db, fetched));
242
+ const poolIndex = indexPair((db, poolId) => indexer().fetchPool(db, poolId), (db, fetched) => indexer().storePool(db, fetched));
243
+ const accountIndex = indexPair((db, stakeAddress) => indexer().fetchAccount(db, stakeAddress), (db, fetched) => indexer().storeAccount(db, fetched));
244
+ const drepIndex = indexPair((_db, drepId) => indexer().fetchDrep(drepId), (db, fetched) => indexer().storeDrep(db, fetched));
245
+ const assetIndex = indexPair((db, unit) => indexer().resolveAssetInfo(db, unit), (db, fetched) => indexer().storeAsset(db, fetched));
246
+ const transactionIndex = indexPair((db, hash) => indexer().fetchTransaction(db, hash), (db, fetched) => indexer().storeTransaction(db, fetched));
247
+ const metadataIndex = indexPair((db, hash) => indexer().fetchTransactionMetadata(db, hash), (db, fetched) => indexer().storeTransactionMetadata(db, fetched));
248
+ const networkIndex = indexPair((db, _key) => indexer().fetchNetworkInformation(db), (db, fetched) => indexer().storeNetworkInformation(db, fetched));
148
249
  // ---------------------------------------------------------------------------
149
250
  // Network Information (singleton - no key field)
150
251
  // ---------------------------------------------------------------------------
151
252
  async function fetchNetworkInformation(db) {
152
- const existing = await db.run(SELECT.one.from(NetworkInformation));
153
- if (!existing)
154
- return await indexer().indexNetworkInformation(db);
155
- return existing;
253
+ const [row] = await indexMissing(db, [null], (d) => d.run(SELECT.one.from(NetworkInformation)), networkIndex);
254
+ return row;
156
255
  }
157
- srv.on('READ', NetworkInformation, async (req) => {
158
- return (0, backend_request_handler_1.handleRequest)(req, fetchNetworkInformation);
159
- });
256
+ srv.on('READ', NetworkInformation, singletonRead(NetworkInformation, networkIndex));
160
257
  srv.on('GetNetworkInformation', async (req) => {
161
258
  return (0, backend_request_handler_1.handleRequest)(req, fetchNetworkInformation);
162
259
  });
163
260
  // ---------------------------------------------------------------------------
164
261
  // Blocks
165
262
  // ---------------------------------------------------------------------------
166
- srv.on('READ', Blocks, indexOnMissRead(Blocks, 'hash', validators_1.isBlockHash, (db, h) => indexer().indexBlock(db, h)));
167
- srv.on('GetBlockByHash', indexOnMissAction('GetBlockByHash', Blocks, 'hash', validators_1.isBlockHash, (db, h) => indexer().indexBlock(db, h)));
263
+ srv.on('READ', Blocks, indexOnMissRead(Blocks, 'hash', validators_1.isBlockHash, blockIndex));
264
+ srv.on('GetBlockByHash', indexOnMissAction('GetBlockByHash', Blocks, 'hash', validators_1.isBlockHash, blockIndex));
168
265
  srv.on('GetLatestBlock', async (req) => {
169
266
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestBlock(db));
170
267
  });
171
- // ---------------------------------------------------------------------------
172
- // Epochs
173
- // ---------------------------------------------------------------------------
174
- srv.on('READ', Epochs, indexOnMissRead(Epochs, 'epoch', validators_1.isEpochNumber, (db, e) => indexer().indexEpoch(db, e), { errorMessage: 'epochNumber has invalid format' }));
175
- srv.on('GetEpochByNumber', indexOnMissAction('GetEpochByNumber', Epochs, 'epochNumber', validators_1.isEpochNumber, (db, e) => indexer().indexEpoch(db, e), { entityKeyField: 'epoch', errorMessage: 'epochNumber has invalid format' }));
268
+ const epochIndex = {
269
+ fetch: async (db, epoch) => {
270
+ try {
271
+ return { fresh: await indexer().fetchEpoch(epoch) };
272
+ }
273
+ catch (err) {
274
+ const stored = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(Epochs).where({ epoch })));
275
+ if (!stored)
276
+ throw err;
277
+ logger.debug(`epoch ${epoch} not refreshed, the stored row stands: ${err instanceof Error ? err.message : String(err)}`);
278
+ return { stored };
279
+ }
280
+ },
281
+ store: async (db, fetched) => ('fresh' in fetched ? indexer().storeEpoch(db, fetched.fresh) : fetched.stored),
282
+ };
283
+ const finalEpoch = (d, epoch) => d.run(SELECT.one.from(Epochs).where({ epoch, final: true }));
284
+ const epochOptions = { errorMessage: 'epochNumber has invalid format', exists: finalEpoch };
285
+ srv.on('READ', Epochs, indexOnMissRead(Epochs, 'epoch', validators_1.isEpochNumber, epochIndex, epochOptions));
286
+ srv.on('GetEpochByNumber', indexOnMissAction('GetEpochByNumber', Epochs, 'epochNumber', validators_1.isEpochNumber, epochIndex, { ...epochOptions, entityKeyField: 'epoch' }));
176
287
  srv.on('GetLatestEpoch', async (req) => {
177
288
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestEpoch(db));
178
289
  });
179
290
  // ---------------------------------------------------------------------------
180
291
  // Pools
181
292
  // ---------------------------------------------------------------------------
182
- srv.on('READ', Pools, indexOnMissRead(Pools, 'poolId', validators_1.isValidPoolId, (db, p) => indexer().indexPool(db, p)));
183
- srv.on('GetPoolById', indexOnMissAction('GetPoolById', Pools, 'poolId', validators_1.isValidPoolId, (db, p) => indexer().indexPool(db, p)));
293
+ srv.on('READ', Pools, indexOnMissRead(Pools, 'poolId', validators_1.isValidPoolId, poolIndex));
294
+ srv.on('GetPoolById', indexOnMissAction('GetPoolById', Pools, 'poolId', validators_1.isValidPoolId, poolIndex));
184
295
  // ---------------------------------------------------------------------------
185
296
  // Accounts
186
297
  // ---------------------------------------------------------------------------
187
- srv.on('READ', Accounts, indexOnMissRead(Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, (db, s) => indexer().indexAccount(db, s)));
188
- srv.on('GetAccountByStakeAddress', indexOnMissAction('GetAccountByStakeAddress', Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, (db, s) => indexer().indexAccount(db, s)));
298
+ srv.on('READ', Accounts, indexOnMissRead(Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, accountIndex));
299
+ srv.on('GetAccountByStakeAddress', indexOnMissAction('GetAccountByStakeAddress', Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, accountIndex));
189
300
  // ---------------------------------------------------------------------------
190
301
  // Dreps
191
302
  // ---------------------------------------------------------------------------
192
- srv.on('READ', Dreps, indexOnMissRead(Dreps, 'drepId', validators_1.isValidDrepId, (db, d) => indexer().indexDrep(db, d)));
193
- srv.on('GetDrepById', indexOnMissAction('GetDrepById', Dreps, 'drepId', validators_1.isValidDrepId, (db, d) => indexer().indexDrep(db, d)));
303
+ srv.on('READ', Dreps, indexOnMissRead(Dreps, 'drepId', validators_1.isValidDrepId, drepIndex));
304
+ srv.on('GetDrepById', indexOnMissAction('GetDrepById', Dreps, 'drepId', validators_1.isValidDrepId, drepIndex));
194
305
  // ---------------------------------------------------------------------------
195
306
  // Assets
196
307
  // ---------------------------------------------------------------------------
197
- srv.on('READ', Assets, indexOnMissRead(Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
198
- srv.on('GetAssetInfo', indexOnMissAction('GetAssetInfo', Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
199
- // ---------------------------------------------------------------------------
200
- // Asset History — read-through (always-fresh)
201
- // ---------------------------------------------------------------------------
202
- // Generic READ on AssetHistory is served from DB (no auto-index); consumers
203
- // must call GetAssetHistory(unit) first to seed entries for a given asset,
204
- // then page via $top/$skip on the AssetHistory entity.
308
+ srv.on('READ', Assets, indexOnMissRead(Assets, 'unit', validators_1.isAssetUnit, assetIndex, { errorMessage: 'Invalid asset unit format' }));
309
+ srv.on('GetAssetInfo', indexOnMissAction('GetAssetInfo', Assets, 'unit', validators_1.isAssetUnit, assetIndex, { errorMessage: 'Invalid asset unit format' }));
310
+ // Asset history: READ serves stored rows only; GetAssetHistory fetches and stores them.
205
311
  srv.on('READ', AssetHistory, async (req) => {
206
312
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => db.run(req.query));
207
313
  });
208
- /**
209
- * Action: GetAssetHistory - Always-fresh fetch of recent mint/burn events.
210
- * Multi-backend: Koios preferred (block timestamps), Blockfrost fallback.
211
- */
212
- srv.on('GetAssetHistory', async (req) => {
213
- const { unit, limit } = req.data;
314
+ // GetAssetHistory: always-fresh fetch of recent mint/burn events.
315
+ srv.on(CardanoODataService_1.GetAssetHistory, async (req) => {
316
+ const { unit } = req.data;
214
317
  if (!unit)
215
318
  return (0, errors_1.rejectMissing)(req, 'GetAssetHistory', 'unit');
216
319
  if (!(0, validators_1.isAssetUnit)(unit)) {
217
320
  return (0, errors_1.rejectInvalid)(req, 'GetAssetHistory', 'Invalid asset unit format', 'unit');
218
321
  }
219
- // clamp like GetLatestTransactionsByAddress — unbounded limits page the upstream backend indefinitely
220
- const effectiveLimit = Math.min(Math.max(typeof limit === 'number' ? limit : 100, 1), 100);
322
+ const page = (0, paging_1.latestWindowPage)(req, 'GetAssetHistory', 100);
221
323
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
222
- return await indexer().indexAssetHistory(db, unit, effectiveLimit);
324
+ const events = await indexer().indexAssetHistory(db, unit, page.skip + page.limit);
325
+ return (0, paging_1.pageRows)((0, paging_1.sortAssetHistory)(events), page);
223
326
  });
224
327
  });
225
328
  // ---------------------------------------------------------------------------
226
329
  // Addresses
227
330
  // ---------------------------------------------------------------------------
228
- srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, (db, a) => indexer().indexAddress(db, a), { errorMessage: 'Invalid bech32 address format' }));
229
- srv.on('GetAddressByBech32', indexOnMissAction('GetAddressByBech32', Addresses, 'address', validators_1.isValidBech32Address, (db, a) => indexer().indexAddress(db, a), { errorMessage: 'Invalid bech32 address format' }));
230
- /**
231
- * Action: GetAssetsByAddress - indexes parent address if needed, then queries child assets.
232
- */
233
- srv.on('GetAssetsByAddress', async (req) => {
331
+ // The full address read when a backend aggregates addresses; with none of them (Ogmios alone,
332
+ // AllBackendsFailedError without errors) the address is read from its UTxOs. Both write the
333
+ // Addresses row, so a navigation from it finds its parent.
334
+ const addressIndex = {
335
+ fetch: async (db, address) => {
336
+ try {
337
+ return await indexer().fetchAddress(db, address);
338
+ }
339
+ catch (err) {
340
+ if (err instanceof errors_1.AllBackendsFailedError && err.errors.length === 0) {
341
+ return { address, utxos: await indexer().fetchAddressUtxos(address) };
342
+ }
343
+ throw err;
344
+ }
345
+ },
346
+ store: (db, fetched) => 'utxos' in fetched
347
+ ? indexer().storeAddressFromUtxos(db, fetched.address, fetched.utxos)
348
+ : indexer().storeAddress(db, fetched),
349
+ };
350
+ /** An address is indexed when its Addresses row is valid. */
351
+ const addressIndexed = async (db, address) => !!(await db.run(SELECT.one.from(Addresses).where({ address })));
352
+ srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
353
+ srv.on('GetAddressByBech32', indexOnMissAction('GetAddressByBech32', Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
354
+ // GetAssetsByAddress: indexes the parent address if needed, then queries child assets.
355
+ srv.on(CardanoODataService_1.GetAssetsByAddress, async (req) => {
234
356
  const { address } = req.data;
235
357
  if (!address)
236
358
  (0, errors_1.rejectMissing)(req, 'GetAssetsByAddress', 'address');
237
359
  if (!(0, validators_1.isValidBech32Address)(address))
238
360
  (0, errors_1.rejectInvalid)(req, 'GetAssetsByAddress', 'Invalid bech32 address format', 'address');
361
+ const page = (0, paging_1.pageOf)(req.data, 1000);
239
362
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
240
- const existing = await db.run(SELECT.one.from(Addresses).where({ address }));
241
- if (!existing)
242
- await indexer().indexAddress(db, address);
363
+ widenTemporalWindow(req);
364
+ await indexMissing(db, [address], addressIndexed, addressIndex);
243
365
  const assets = await db.run(SELECT.from(AddressAssets).where({ address_address: address }));
244
- // Deduplicate temporal versions — keep latest validFrom per unit
245
- const seen = new Map();
246
- for (const asset of assets) {
247
- if (!seen.has(asset.unit) || asset.validFrom > seen.get(asset.unit).validFrom) {
248
- seen.set(asset.unit, asset);
249
- }
250
- }
251
- return Array.from(seen.values());
366
+ return (0, paging_1.pageRows)((0, paging_1.byKey)(latestSlices(assets, (asset) => asset.unit ?? ''), (a) => a.unit ?? ''), page);
252
367
  });
253
368
  });
254
- /**
255
- * Action: GetUTxOsByAddress - indexes parent address if needed, then queries child UTxOs.
256
- */
257
- srv.on('GetUTxOsByAddress', async (req) => {
369
+ // GetUTxOsByAddress: indexes the address if needed, then queries child UTxOs.
370
+ srv.on(CardanoODataService_1.GetUTxOsByAddress, async (req) => {
258
371
  const { address } = req.data;
259
372
  if (!address)
260
373
  (0, errors_1.rejectMissing)(req, 'GetUTxOsByAddress', 'address');
261
374
  if (!(0, validators_1.isValidBech32Address)(address))
262
375
  (0, errors_1.rejectInvalid)(req, 'GetUTxOsByAddress', 'Invalid bech32 address format', 'address');
376
+ const page = (0, paging_1.pageOf)(req.data, 1000);
263
377
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
264
- const existing = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
265
- if (!existing || existing.length === 0) {
266
- // No valid cached data — re-index fresh (UPSERT is idempotent, no DELETE needed).
267
- // Prefer getAddress-based full indexing (richer: also captures address detail and
268
- // returns NotFound for unknown addresses on Blockfrost/Koios). But GetUTxOsByAddress
269
- // only needs the UTxO set, which Ogmios serves via getAddressUtxos even though it
270
- // doesn't support getAddress — so when NO configured backend can serve getAddress
271
- // (AllBackendsFailedError with zero collected errors == every backend skipped it),
272
- // fall back to a UTxO-only index instead of failing. getAddress is indexAddress's
273
- // first call, so nothing is persisted before this throws — the fallback is clean.
274
- try {
275
- await indexer().indexAddress(db, address);
276
- }
277
- catch (err) {
278
- if (err instanceof errors_1.AllBackendsFailedError && err.errors.length === 0) {
279
- await indexer().indexAddressUtxos(db, address);
280
- }
281
- else {
282
- throw err;
283
- }
284
- }
285
- const fresh = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
286
- return fresh;
287
- }
288
- // Deduplicate temporal versions — keep latest validFrom per hash+index
289
- const seen = new Map();
290
- for (const utxo of existing) {
291
- const key = `${utxo.hash}#${utxo.index}`;
292
- if (!seen.has(key) || utxo.validFrom > seen.get(key).validFrom) {
293
- seen.set(key, utxo);
294
- }
295
- }
296
- return Array.from(seen.values());
378
+ widenTemporalWindow(req);
379
+ await indexMissing(db, [address], addressIndexed, addressIndex);
380
+ const utxos = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
381
+ return (0, paging_1.pageRows)((0, paging_1.byOutRef)(latestSlices(utxos, (utxo) => `${utxo.hash}#${utxo.index}`)), page);
297
382
  });
298
383
  });
299
- /**
300
- * Action: GetUTxOsByCredential - Koios-only credential-keyed UTxO query.
301
- * Always-fresh (no cache check) — credential queries serve dApp state-read use
302
- * cases (Indigo CDPs, Liqwid positions) that need current blockchain state.
303
- * Throws ProviderUnavailableError if Koios backend is not configured.
304
- */
305
- srv.on('GetUTxOsByCredential', async (req) => {
384
+ // Collection reads of the address child sets fill like the parent: an address named in the
385
+ // navigation or the $filter is indexed on a miss, then the client's own query runs.
386
+ srv.on('READ', AddressUTxOs, addressChildRead(addressIndexed, addressIndex));
387
+ srv.on('READ', AddressAssets, addressChildRead(addressIndexed, addressIndex));
388
+ srv.on('READ', AddressTransactions, addressChildRead(addressIndexed, addressIndex));
389
+ // GetUTxOsByCredential: always-fresh credential-keyed UTxO query (dApp state reads need current
390
+ // data). Crawled UTxO set + node first, else Koios; ProviderUnavailableError without either.
391
+ srv.on(CardanoODataService_1.GetUTxOsByCredential, async (req) => {
306
392
  const { credential } = req.data;
307
393
  if (!credential)
308
394
  return (0, errors_1.rejectMissing)(req, 'GetUTxOsByCredential', 'credential');
309
395
  if (!(0, validators_1.isValidCredential)(credential)) {
310
- return (0, errors_1.rejectInvalid)(req, 'GetUTxOsByCredential', 'Invalid payment credential — expected 56-char lowercase hex (28 bytes)', 'credential');
396
+ return (0, errors_1.rejectInvalid)(req, 'GetUTxOsByCredential', 'Invalid payment credential: expected 56-char lowercase hex (28 bytes)', 'credential');
311
397
  }
312
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
313
- return await indexer().indexCredentialUtxos(db, credential);
314
- });
398
+ const page = (0, paging_1.pageOf)(req.data, 1000);
399
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => (0, paging_1.pageRows)((0, paging_1.byOutRef)(await indexer().indexCredentialUtxos(db, credential)), page));
315
400
  });
316
401
  // ---------------------------------------------------------------------------
317
402
  // Transactions
318
403
  // ---------------------------------------------------------------------------
319
- srv.on('READ', Transactions, indexOnMissRead(Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
320
- srv.on('GetTransactionByHash', indexOnMissAction('GetTransactionByHash', Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
404
+ srv.on('READ', Transactions, indexOnMissRead(Transactions, 'hash', validators_1.isTxHash, transactionIndex, { errorMessage: 'Invalid transaction hash format' }));
405
+ srv.on('GetTransactionByHash', indexOnMissAction('GetTransactionByHash', Transactions, 'hash', validators_1.isTxHash, transactionIndex, { errorMessage: 'Invalid transaction hash format' }));
406
+ srv.on(CardanoODataService_1.GetTransactionConfirmations, async (req) => {
407
+ const { txHash } = req.data;
408
+ if (!txHash)
409
+ (0, errors_1.rejectMissing)(req, 'GetTransactionConfirmations', 'txHash');
410
+ if (!(0, validators_1.isTxHash)(txHash))
411
+ (0, errors_1.rejectInvalid)(req, 'GetTransactionConfirmations', 'Invalid transaction hash format', 'txHash');
412
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().resolveTransactionConfirmations(db, txHash));
413
+ });
321
414
  // ---------------------------------------------------------------------------
322
415
  // Transaction Metadata
323
416
  // ---------------------------------------------------------------------------
324
- srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, (db, h) => indexer().indexTransactionMetadata(db, h), { errorMessage: 'Invalid transaction hash format' }));
325
- /**
326
- * Action: GetMetadataByTxHash - returns multiple metadata rows (uses SELECT.from, not SELECT.one).
327
- * Takes camelCase `txHash` like every other action (renamed from `tx_hash` in 1.9.4).
328
- */
329
- srv.on('GetMetadataByTxHash', async (req) => {
417
+ srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, metadataIndex, { errorMessage: 'Invalid transaction hash format' }));
418
+ // GetMetadataByTxHash: returns all metadata rows of a transaction.
419
+ srv.on(CardanoODataService_1.GetMetadataByTxHash, async (req) => {
330
420
  const { txHash } = req.data;
331
421
  if (!txHash)
332
422
  (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'txHash');
333
423
  if (!(0, validators_1.isTxHash)(txHash))
334
424
  (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'txHash');
425
+ const page = (0, paging_1.pageOf)(req.data, 1000);
335
426
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
336
- const existing = await db.run(SELECT.from(TransactionMetadata).where({ tx_hash: txHash }));
337
- if (!existing || existing.length === 0) {
338
- return await indexer().indexTransactionMetadata(db, txHash);
339
- }
340
- return existing;
427
+ const stored = async (d, hash) => {
428
+ const existing = await d.run(SELECT.from(TransactionMetadata).where({ tx_hash: hash }));
429
+ return existing?.length ? existing : null;
430
+ };
431
+ const [rows] = await indexMissing(db, [txHash], stored, metadataIndex);
432
+ return (0, paging_1.pageRows)((0, paging_1.byKey)(rows, (m) => String(m.label ?? '').padStart(20, '0')), page);
341
433
  });
342
434
  });
435
+ // GetMetadataByLabel: stored metadata of one label along the chain. Reads the database only.
436
+ srv.on(CardanoODataService_1.GetMetadataByLabel, async (req) => {
437
+ const { label, fromSlot } = req.data;
438
+ if (label == null || String(label).trim() === '')
439
+ (0, errors_1.rejectMissing)(req, 'GetMetadataByLabel', 'label');
440
+ const id = (0, mappers_1.metadataIdFor)(String(label).trim());
441
+ if (id === null)
442
+ (0, errors_1.rejectInvalid)(req, 'GetMetadataByLabel', 'label must be an unsigned 64-bit integer', 'label');
443
+ const { limit, skip } = (0, paging_1.pageOf)(req.data, 100);
444
+ // NULLS LAST is the order of the (id, txSeq) index; the filter excludes NULL anyway, and a
445
+ // plain ASC on the nullable column would make PostgreSQL sort every row of the label.
446
+ const query = SELECT.from(TransactionMetadata).where({ id, txSeq: { '>=': (0, mappers_1.txSeqOf)(Number(fromSlot ?? 0), 0) } }).limit(limit, skip);
447
+ query.SELECT.orderBy = [{ ref: ['txSeq'], sort: 'asc', nulls: 'last' }];
448
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => db.run(query));
449
+ });
343
450
  // ---------------------------------------------------------------------------
344
451
  // Protocol Parameters (singleton)
345
452
  // ---------------------------------------------------------------------------
346
- srv.on('READ', LedgerProtocolParameters, async (req) => {
347
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
348
- const existing = await db.run(SELECT.one.from(LedgerProtocolParameters));
349
- if (!existing)
350
- return indexer().indexProtocolParameters(db);
351
- return existing;
352
- });
353
- });
453
+ // One row per epoch. The read stores the current epoch's row once it is older than its TTL,
454
+ // the same rule as GetLedgerProtocolParameters, then runs the client's own query. When the
455
+ // backend cannot answer, the stored rows stand.
456
+ srv.on('READ', LedgerProtocolParameters, async (req) => (0, backend_request_handler_1.handleRequest)(req, async (db) => {
457
+ try {
458
+ await indexer().indexProtocolParameters(db);
459
+ }
460
+ catch (err) {
461
+ if (!(await db.run(SELECT.one.from(LedgerProtocolParameters))))
462
+ throw err;
463
+ logger.debug(`protocol parameters not refreshed, the stored rows stand: ${err instanceof Error ? err.message : String(err)}`);
464
+ }
465
+ return db.run(req.query);
466
+ }));
354
467
  srv.on('GetLedgerProtocolParameters', async (req) => {
355
468
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexProtocolParameters(db));
356
469
  });
357
470
  // ---------------------------------------------------------------------------
358
- // Transaction CBOR parsing (pure utility — no backend / DB touch)
471
+ // Transaction CBOR parsing (pure; no backend or DB access)
359
472
  // ---------------------------------------------------------------------------
360
- srv.on('ParseTransactionCbor', async (req) => {
473
+ srv.on(CardanoODataService_1.ParseTransactionCbor, async (req) => {
361
474
  const { cbor } = req.data;
362
475
  if (cbor == null || cbor === '')
363
476
  (0, errors_1.rejectMissing)(req, 'ParseTransactionCbor', 'cbor');
@@ -366,27 +479,337 @@ module.exports = (srv) => {
366
479
  }
367
480
  return (0, backend_request_handler_1.handleRequest)(req, async () => (0, cbor_1.parseTransaction)(cbor));
368
481
  });
369
- // ---------------------------------------------------------------------------
370
- // Address Transactions
371
- // ---------------------------------------------------------------------------
372
- srv.on('GetLatestTransactionsByAddress', async (req) => {
373
- const { address, limit } = req.data;
482
+ srv.on(CardanoODataService_1.DecodePlutusData, async (req) => {
483
+ const { cbor } = req.data;
484
+ if (cbor == null || cbor === '')
485
+ (0, errors_1.rejectMissing)(req, 'DecodePlutusData', 'cbor');
486
+ if (!(0, validators_1.isValidTxCborHex)(cbor)) {
487
+ (0, errors_1.rejectInvalid)(req, 'DecodePlutusData', 'Invalid CBOR hex or exceeds size limit', 'cbor');
488
+ }
489
+ return (0, backend_request_handler_1.handleRequest)(req, async () => JSON.stringify((0, cbor_1.decodePlutusData)(cbor)));
490
+ });
491
+ const watchReads = new Map();
492
+ const watchRead = (address, window, after) => {
493
+ const key = `${address}|${window}`;
494
+ const now = Date.now();
495
+ const recent = watchReads.get(key);
496
+ if (recent && recent.at > after && now - recent.at < ADDRESS_WAIT_POLL_MS)
497
+ return recent;
498
+ const read = {
499
+ at: now,
500
+ rows: (0, tx_utils_1.runWithoutAmbientTx)(async () => cds_1.default.tx((tx) => indexer().indexAddressTransactions(tx, address, window))),
501
+ };
502
+ watchReads.set(key, read);
503
+ const forget = () => { if (watchReads.get(key) === read)
504
+ watchReads.delete(key); };
505
+ read.rows.catch(forget);
506
+ setTimeout(forget, ADDRESS_WAIT_POLL_MS).unref?.();
507
+ return read;
508
+ };
509
+ // GetLatestTransactionsByAddress: the newest transactions of an address. With sinceTime only
510
+ // newer ones; with waitMs the call re-reads until one appears or the time is up.
511
+ srv.on(CardanoODataService_1.GetLatestTransactionsByAddress, async (req) => {
512
+ const { address, sinceTime, waitMs } = req.data;
374
513
  if (!address)
375
514
  (0, errors_1.rejectMissing)(req, 'GetLatestTransactionsByAddress', 'address');
376
515
  if (!(0, validators_1.isValidBech32Address)(address))
377
516
  (0, errors_1.rejectInvalid)(req, 'GetLatestTransactionsByAddress', 'Invalid bech32 address format', 'address');
378
- const txLimit = Math.min(Math.max(limit || 10, 1), 100);
517
+ if (waitMs && sinceTime == null)
518
+ (0, errors_1.rejectInvalid)(req, 'GetLatestTransactionsByAddress', 'waitMs needs sinceTime', 'waitMs');
519
+ const page = (0, paging_1.latestWindowPage)(req, 'GetLatestTransactionsByAddress', 10);
520
+ const window = page.skip + page.limit;
521
+ const since = sinceTime == null ? null : Number(sinceTime);
522
+ const newer = (rows) => since == null ? rows : rows.filter((r) => Number(r.blockTime ?? 0) > since);
523
+ const deadline = Date.now() + Number(waitMs ?? 0);
524
+ // Every call lists the newest hashes; stored rows are reused, only new ones are fetched.
379
525
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
380
- const existing = await db.run(SELECT.from(AddressTransactions)
381
- .where({ address_address: address })
382
- .orderBy('blockTime desc')
383
- .limit(txLimit));
384
- if (!existing || existing.length < txLimit) {
385
- return indexer().indexAddressTransactions(db, address, txLimit);
526
+ if (!waitMs)
527
+ return (0, paging_1.pageRows)(newer(await indexer().indexAddressTransactions(db, address, window)), page);
528
+ // the last read falls on the deadline, so a short waitMs waits as long as it says
529
+ for (let last = -Infinity;;) {
530
+ const read = watchRead(address, window, last);
531
+ last = read.at;
532
+ const rows = newer(await read.rows);
533
+ const remaining = deadline - Date.now();
534
+ if (rows.length || remaining <= 0 || req.http?.res.destroyed === true)
535
+ return (0, paging_1.pageRows)(rows, page);
536
+ await new Promise((resolve) => setTimeout(resolve, Math.min(remaining, ADDRESS_WAIT_POLL_MS)));
537
+ }
538
+ });
539
+ });
540
+ /** The table; the service projection leaves the address list out. */
541
+ const ACCOUNTS_TABLE = 'odatano.cardano.Accounts';
542
+ // The valid account row with its address list. The temporal window applies to the service
543
+ // entity, so the valid slice is found there and its list read from the table by the full key.
544
+ async function validAccountRow(d, stakeAddress) {
545
+ const row = await d.run(SELECT.one.from(Accounts).columns('validFrom', 'poolId_poolId', 'drepId_drepId').where({ stakeAddress }));
546
+ if (!row)
547
+ return undefined;
548
+ const list = await d.run(SELECT.one.from(ACCOUNTS_TABLE).columns('addressList').where({ stakeAddress, validFrom: row.validFrom }));
549
+ return { ...row, addressList: list?.addressList ?? null };
550
+ }
551
+ function accountSource(db, stakeAddress) {
552
+ let row;
553
+ let fetch;
554
+ let fetched = null;
555
+ return {
556
+ stakeAddress,
557
+ row: () => (row ??= (0, tx_utils_1.readOutside)(db, (d) => validAccountRow(d, stakeAddress))),
558
+ fetch: () => (fetch ??= accountIndex.fetch(db, stakeAddress).then((f) => (fetched = f))),
559
+ fetched: () => fetched,
560
+ };
561
+ }
562
+ // The addresses of an account, sorted and unique: the list stored with a valid account row, else
563
+ // the backend's. Only an expired or missing account asks the backend.
564
+ async function accountAddresses(account) {
565
+ const stored = (0, cardano_indexer_1.parseAccountAddressList)((await account.row())?.addressList);
566
+ return stored ?? (0, cardano_indexer_1.accountAddressList)((await account.fetch()).account.addresses);
567
+ }
568
+ /** Writes the account row when the backend was asked and no valid row exists meanwhile. */
569
+ function storeAccount(db, account) {
570
+ return async () => {
571
+ const fetched = account.fetched();
572
+ if (fetched && !(await db.run(SELECT.one.from(Accounts).where({ stakeAddress: account.stakeAddress }))))
573
+ await accountIndex.store(db, fetched);
574
+ };
575
+ }
576
+ // The addresses a read of an account's addresses needs stored. Up to MAX_ADDRESSES_PER_READ the
577
+ // read runs as written. Above that the page is chosen before the rows exist, so it can follow only
578
+ // the address order: no $filter, $orderby on address alone, $top of at most the cap.
579
+ function accountAddressPage(req, all, part, countOnly) {
580
+ if (all.length <= MAX_ADDRESSES_PER_READ)
581
+ return all;
582
+ if (countOnly)
583
+ return [];
584
+ const rule = `The account has ${all.length} addresses: read at most ${MAX_ADDRESSES_PER_READ} at a time with $top and $skip, ordered by address, without $filter`;
585
+ const order = part.orderBy ?? [];
586
+ const rows = numberVal(part.limit?.rows);
587
+ const byAddress = order.every((o) => o.ref?.length === 1 && o.ref[0] === 'address');
588
+ if (part.where?.length || order.length > 1 || !byAddress || rows == null || rows > MAX_ADDRESSES_PER_READ) {
589
+ (0, errors_1.rejectInvalid)(req, 'Address', rule, 'Address');
590
+ }
591
+ const offset = numberVal(part.limit?.offset) ?? 0;
592
+ const sorted = order[0]?.sort === 'desc' ? [...all].reverse() : all;
593
+ return sorted.slice(offset, offset + rows);
594
+ }
595
+ /** Narrows `part` to the chosen page; the offset is already in the page. */
596
+ function readPage(part, page) {
597
+ part.where = [{ ref: ['address'] }, 'in', { list: (page.length ? page : ['']).map((val) => ({ val })) }];
598
+ part.limit = { rows: { val: Math.max(page.length, 1) } };
599
+ if (!part.orderBy?.length)
600
+ part.orderBy = [{ ref: ['address'], sort: 'asc' }];
601
+ }
602
+ /** Total address count of an account read whose page was narrowed, by request, for its $count. */
603
+ const accountAddressTotals = new WeakMap();
604
+ /** The same for an `$expand=Address` page of a keyed Accounts read. */
605
+ const expandAddressTotals = new WeakMap();
606
+ // Fetches the addresses not stored yet; the returned write stores them. The addresses come from
607
+ // stored rows or the backend, which also name Byron addresses, so they are not checked as bech32.
608
+ async function prepareAddresses(db, addresses) {
609
+ const named = addresses.filter((a) => typeof a === 'string' && a.length > 0);
610
+ return (await prepareMissing(db, named, addressIndexed, addressIndex)).store;
611
+ }
612
+ // Accounts('s')/Address and $expand=Address: a plain collection read gets its page; Address('a')
613
+ // and the paths below it get that one address once it belongs to the account.
614
+ async function prepareAccountAddressRead(req, db, account, nav, part, totals) {
615
+ const all = await accountAddresses(account);
616
+ let page;
617
+ if (nav?.navKeys) {
618
+ const named = nav.navKeys.address;
619
+ page = typeof named === 'string' && all.includes(named) ? [named] : [];
620
+ }
621
+ else if (nav && nav.depth > 2) {
622
+ page = [];
623
+ }
624
+ else {
625
+ const column = part.columns?.length === 1 ? part.columns[0] : undefined;
626
+ page = accountAddressPage(req, all, part, nav !== null && column?.func === 'count' && column.as === '$count');
627
+ if (all.length > MAX_ADDRESSES_PER_READ) {
628
+ readPage(part, page);
629
+ totals.set(req, all.length);
630
+ }
631
+ }
632
+ return [await prepareAddresses(db, page), storeAccount(db, account)];
633
+ }
634
+ // Accounts('s')/poolId and /drepId, and their $expand: the pool or DRep the account names.
635
+ async function prepareAccountTarget(db, account, to) {
636
+ const row = await account.row();
637
+ const id = row ? row[to === 'poolId' ? 'poolId_poolId' : 'drepId_drepId'] : (await account.fetch()).account[to];
638
+ const stores = [storeAccount(db, account)];
639
+ if (!id)
640
+ return stores;
641
+ if (to === 'poolId')
642
+ stores.push((await prepareMissing(db, [id], (d, k) => d.run(SELECT.one.from(Pools).where({ poolId: k })), poolIndex)).store);
643
+ else
644
+ stores.push((await prepareMissing(db, [id], (d, k) => d.run(SELECT.one.from(Dreps).where({ drepId: k })), drepIndex)).store);
645
+ return stores;
646
+ }
647
+ // A block and, when asked, its epoch. Blocks.epoch joins on epochNumber, so a stored block finds
648
+ // its epoch once the epoch row exists.
649
+ async function prepareBlock(db, hash, withEpoch) {
650
+ const stored = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(Blocks).columns('epochNumber').where({ hash })));
651
+ const block = stored ? null : await blockIndex.fetch(db, hash);
652
+ // a fetched block carries its epoch when the backend had it
653
+ const epochNumber = stored ? stored.epochNumber : block?.epoch ? null : block?.block.epoch;
654
+ const epoch = withEpoch && epochNumber != null && !(await (0, tx_utils_1.readOutside)(db, (d) => finalEpoch(d, epochNumber)))
655
+ ? await epochIndex.fetch(db, epochNumber)
656
+ : null;
657
+ return [
658
+ async () => { if (block && !(await db.run(SELECT.one.from(Blocks).where({ hash }))))
659
+ await blockIndex.store(db, block); },
660
+ async () => { if (epoch)
661
+ await epochIndex.store(db, epoch); },
662
+ ];
663
+ }
664
+ // Transactions('h')/inputs(…)/address and below: the transaction, then the address of that input
665
+ // or output, from its stored row or from the fetched transaction.
666
+ async function prepareTransactionStepAddress(db, hash, step, keys) {
667
+ const indexField = step === 'inputs' ? 'inputIndex' : 'outputIndex';
668
+ const position = Number(keys[indexField]);
669
+ const stored = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(Transactions).columns('txSeq').where({ hash })));
670
+ let fetched = null;
671
+ let address;
672
+ if (stored) {
673
+ const row = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(step === 'inputs' ? TransactionInputs : TransactionOutputs)
674
+ .columns('address_address').where({ txSeq: stored.txSeq, [indexField]: position })));
675
+ address = row?.address_address;
676
+ }
677
+ else {
678
+ fetched = await transactionIndex.fetch(db, hash);
679
+ address = step === 'inputs'
680
+ ? fetched.inputs?.[position]?.address
681
+ : fetched.outputs?.find((o) => o.outputIndex === position)?.address;
682
+ }
683
+ const storeAddress = await prepareAddresses(db, [address]);
684
+ const tx = fetched;
685
+ return [
686
+ async () => { if (tx && !(await db.run(SELECT.one.from(Transactions).where({ hash }))))
687
+ await transactionIndex.store(db, tx); },
688
+ storeAddress,
689
+ ];
690
+ }
691
+ /** TransactionInputs(…)/address and TransactionOutputs(…)/address: the address of the stored row. */
692
+ async function prepareRowAddress(db, entity, keys) {
693
+ const row = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(entity).columns('address_address').where(keys)));
694
+ return [await prepareAddresses(db, [row?.address_address])];
695
+ }
696
+ /** The preparations a navigation read needs, by its parent. */
697
+ async function prepareNavigation(req, db, nav) {
698
+ const select = req.query.SELECT;
699
+ switch (nav.parent) {
700
+ case 'Transactions': {
701
+ const hash = nav.keys.hash;
702
+ if (!(0, validators_1.isTxHash)(hash))
703
+ (0, errors_1.rejectInvalid)(req, 'Transactions', 'Invalid transaction hash format', 'hash');
704
+ if ((nav.nav === 'inputs' || nav.nav === 'outputs') && nav.navKeys && nav.steps[1] === 'address') {
705
+ return prepareTransactionStepAddress(db, hash, nav.nav, nav.navKeys);
706
+ }
707
+ return [(await prepareMissing(db, [hash], (d, k) => d.run(SELECT.one.from(Transactions).where({ hash: k })), transactionIndex)).store];
708
+ }
709
+ case 'TransactionInputs':
710
+ case 'TransactionOutputs':
711
+ return nav.nav === 'address' ? prepareRowAddress(db, nav.parent === 'TransactionInputs' ? TransactionInputs : TransactionOutputs, nav.keys) : [];
712
+ case 'Addresses': {
713
+ const address = nav.keys.address;
714
+ if (!(0, validators_1.isValidBech32Address)(address))
715
+ (0, errors_1.rejectInvalid)(req, 'Addresses', 'Invalid bech32 address format', 'address');
716
+ return [await prepareAddresses(db, [address])];
386
717
  }
387
- return existing;
718
+ case 'Blocks': {
719
+ const hash = nav.keys.hash;
720
+ if (!(0, validators_1.isBlockHash)(hash))
721
+ (0, errors_1.rejectInvalid)(req, 'Blocks', 'Invalid block hash format', 'hash');
722
+ return prepareBlock(db, hash, nav.nav === 'epoch');
723
+ }
724
+ case 'Accounts': {
725
+ const stakeAddress = nav.keys.stakeAddress;
726
+ if (!(0, validators_1.isValidBech32StakeAddress)(stakeAddress))
727
+ (0, errors_1.rejectInvalid)(req, 'Accounts', 'Invalid stake address format', 'stakeAddress');
728
+ const account = accountSource(db, stakeAddress);
729
+ if (nav.nav === 'Address')
730
+ return prepareAccountAddressRead(req, db, account, nav, select, accountAddressTotals);
731
+ if (nav.nav === 'poolId' || nav.nav === 'drepId')
732
+ return prepareAccountTarget(db, account, nav.nav);
733
+ return [(await prepareMissing(db, [stakeAddress], (d, k) => d.run(SELECT.one.from(Accounts).where({ stakeAddress: k })), accountIndex)).store];
734
+ }
735
+ default:
736
+ return [];
737
+ }
738
+ }
739
+ /** The `$expand` columns of a read, by the association they expand. */
740
+ function expandsOf(req) {
741
+ const columns = req.query.SELECT?.columns ?? [];
742
+ const found = new Map();
743
+ for (const c of columns) {
744
+ const col = c;
745
+ if (col.expand !== undefined && typeof col.ref?.[0] === 'string')
746
+ found.set(col.ref[0], c);
747
+ }
748
+ return found;
749
+ }
750
+ // The preparations the $expand of a keyed Accounts or Blocks read needs. The keyed row itself is
751
+ // indexed by its own READ handler; this covers what the expand joins.
752
+ async function prepareExpands(req, db, expands) {
753
+ if (req.target?.name === Blocks.name) {
754
+ const hash = (0, navigation_1.readKey)(req, 'hash');
755
+ if (!expands.has('epoch') || typeof hash !== 'string')
756
+ return [];
757
+ if (!(0, validators_1.isBlockHash)(hash))
758
+ (0, errors_1.rejectInvalid)(req, 'Blocks', 'Invalid block hash format', 'hash');
759
+ return prepareBlock(db, hash, true);
760
+ }
761
+ const stakeAddress = (0, navigation_1.readKey)(req, 'stakeAddress');
762
+ if (typeof stakeAddress !== 'string')
763
+ return [];
764
+ if (!(0, validators_1.isValidBech32StakeAddress)(stakeAddress))
765
+ (0, errors_1.rejectInvalid)(req, 'Accounts', 'Invalid stake address format', 'stakeAddress');
766
+ const account = accountSource(db, stakeAddress);
767
+ const stores = [];
768
+ const address = expands.get('Address');
769
+ if (address)
770
+ stores.push(...await prepareAccountAddressRead(req, db, account, null, address, expandAddressTotals));
771
+ for (const to of ['poolId', 'drepId']) {
772
+ if (expands.has(to))
773
+ stores.push(...await prepareAccountTarget(db, account, to));
774
+ }
775
+ return stores;
776
+ }
777
+ srv.before('READ', async (req) => {
778
+ const nav = (0, navigation_1.navigationOf)(req);
779
+ const keyedTarget = req.target?.name === Accounts.name || req.target?.name === Blocks.name;
780
+ const expands = !nav && keyedTarget ? expandsOf(req) : new Map();
781
+ if (!nav && !expands.size)
782
+ return;
783
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
784
+ widenTemporalWindow(req);
785
+ const stores = nav ? await prepareNavigation(req, db, nav) : await prepareExpands(req, db, expands);
786
+ for (const store of stores)
787
+ await store();
388
788
  });
389
789
  });
790
+ // The $count of a narrowed account address read is the account's total, not the page's.
791
+ srv.after('READ', Addresses, (_rows, req) => {
792
+ const total = accountAddressTotals.get(req);
793
+ if (total === undefined)
794
+ return;
795
+ const result = req.results;
796
+ const columns = req.query.SELECT;
797
+ if (columns?.columns?.length === 1 && columns.columns[0].as === '$count' && result?.[0])
798
+ result[0].$count = total;
799
+ else if (columns?.count && result)
800
+ result.$count = total;
801
+ });
802
+ // The same for `$expand=Address($count=true)` of a keyed Accounts read.
803
+ srv.after('READ', Accounts, (_rows, req) => {
804
+ const total = expandAddressTotals.get(req);
805
+ if (total === undefined)
806
+ return;
807
+ const rows = req.results;
808
+ for (const row of Array.isArray(rows) ? rows : rows ? [rows] : []) {
809
+ if (row && 'Address@odata.count' in row)
810
+ row['Address@odata.count'] = String(total);
811
+ }
812
+ });
390
813
  logger.debug('All handlers registered');
391
814
  };
392
815
  //# sourceMappingURL=cardano-service.js.map