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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) 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 +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -9,31 +9,55 @@ 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
+ /** Pause between two reads of a waiting GetLatestTransactionsByAddress call. */
18
+ const ADDRESS_WAIT_POLL_MS = 5000;
19
+ /** Newest temporal slice per key; child tables keep one row per validFrom. */
20
+ function latestSlices(rows, keyOf) {
21
+ const seen = new Map();
22
+ for (const row of rows) {
23
+ const key = keyOf(row);
24
+ const prev = seen.get(key);
25
+ if (!prev || (row.validFrom ?? '') > (prev.validFrom ?? ''))
26
+ seen.set(key, row);
27
+ }
28
+ return Array.from(seen.values());
29
+ }
12
30
  const { SELECT } = cds_1.default.ql;
13
31
  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
- */
32
+ /** Pairs a provider read with the write of its result; the result type follows from the read. */
33
+ function indexPair(fetch, store) {
34
+ return { fetch, store };
35
+ }
36
+ // Fills misses without holding the request transaction while the provider answers: every missing
37
+ // key is read from the provider first, then all are stored. A row stored in the meantime is kept.
38
+ // Returns the row found or stored per key.
39
+ async function indexMissing(db, keys, exists, index) {
40
+ const rows = await (0, tx_utils_1.readOutside)(db, async (d) => {
41
+ const found = [];
42
+ for (const key of keys)
43
+ found.push(await exists(d, key));
44
+ return found;
45
+ });
46
+ const fetched = new Map();
47
+ for (const [i, key] of keys.entries()) {
48
+ if (!rows[i])
49
+ fetched.set(i, await index.fetch(db, key));
50
+ }
51
+ for (const [i, value] of fetched) {
52
+ rows[i] = (await exists(db, keys[i])) || await index.store(db, value);
53
+ }
54
+ return rows;
55
+ }
56
+ /** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
19
57
  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
- */
58
+ // CAP's temporal window is fixed at transaction start, so a slice written by index-on-miss would be
59
+ // invisible to the re-read. This widens the upper bound unless the client set `sap-valid-*`.
60
+ // Must run before the request transaction's first statement.
37
61
  function widenTemporalWindow(req) {
38
62
  const q = req.http?.req?.query;
39
63
  if (q && (q['sap-valid-at'] || q['sap-valid-from'] || q['sap-valid-to']))
@@ -41,9 +65,7 @@ function widenTemporalWindow(req) {
41
65
  const now = Date.now();
42
66
  const from = new Date(now).toISOString();
43
67
  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.
68
+ // The DB session reads the bag of whichever context opened the transaction; stamp both.
47
69
  const r = req;
48
70
  for (const bag of new Set([r._, r.context?._])) {
49
71
  if (!bag)
@@ -52,49 +74,29 @@ function widenTemporalWindow(req) {
52
74
  bag['VALID-TO'] = to;
53
75
  }
54
76
  }
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) {
77
+ /** READ handler that indexes a missing key first, then runs the client's own query (keeps `$expand`, `$select`). */
78
+ function indexOnMissRead(entity, reqKeyField, validate, index, options) {
63
79
  const dbKey = options?.entityKeyField || reqKeyField;
64
80
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
65
81
  return async (req) => {
66
82
  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)
83
+ // Explicit null check: falsy keys such as epoch=0 or '' must still be validated.
69
84
  if (key !== undefined && key !== null && validate && !validate(key))
70
85
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
71
86
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
72
87
  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.
88
+ widenTemporalWindow(req);
89
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
90
+ await indexMissing(db, [key], (d, k) => d.run(SELECT.one.from(entity).where({ [dbKey]: k })), index);
91
+ // The client's query is the only authority on the result: never answer with the row
92
+ // found here, or an excluding $filter / second key would yield a sibling row instead of 404.
89
93
  }
90
94
  return db.run(req.query);
91
95
  });
92
96
  };
93
97
  }
94
- /**
95
- * Factory: Action handler with required key validation and index-on-miss.
96
- */
97
- function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, options) {
98
+ /** Factory: action handler with required-key validation and index-on-miss. */
99
+ function indexOnMissAction(actionName, entity, reqKeyField, validate, index, options) {
98
100
  const dbKey = options?.entityKeyField || reqKeyField;
99
101
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
100
102
  return async (req) => {
@@ -104,55 +106,129 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
104
106
  if (!validate(key))
105
107
  (0, errors_1.rejectInvalid)(req, actionName, errMsg, reqKeyField);
106
108
  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;
109
+ widenTemporalWindow(req);
110
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
111
+ const [row] = await indexMissing(db, [key], (d, k) => d.run(SELECT.one.from(entity).where({ [dbKey]: k })), index);
112
+ return row;
113
+ });
114
+ };
115
+ }
116
+ /** Addresses one collection read may index on a miss; more is a 400. */
117
+ const MAX_ADDRESSES_PER_READ = 10;
118
+ const isRef = (t) => typeof t === 'object' && 'ref' in t;
119
+ const isVal = (t) => typeof t === 'object' && 'val' in t;
120
+ const isList = (t) => typeof t === 'object' && 'list' in t;
121
+ const isXpr = (t) => typeof t === 'object' && 'xpr' in t;
122
+ /** `address_address` or the association path `address/address`. */
123
+ function isAddressRef(t) {
124
+ if (!isRef(t))
125
+ return false;
126
+ const path = t.ref;
127
+ return (path.length === 1 && path[0] === 'address_address') || (path.length === 2 && path[0] === 'address' && path[1] === 'address');
128
+ }
129
+ const stringVal = (t) => t !== undefined && isVal(t) && typeof t.val === 'string' ? t.val : undefined;
130
+ /** Addresses a child-set read names: the navigation parent, or `address_address` in an `eq` or `in` filter. */
131
+ function addressesInReadQuery(req) {
132
+ const found = new Set();
133
+ const parent = req.data?.address_address;
134
+ if (typeof parent === 'string')
135
+ found.add(parent);
136
+ const walk = (tokens) => {
137
+ for (let i = 0; i < tokens.length; i++) {
138
+ const token = tokens[i];
139
+ if (typeof token === 'string')
140
+ continue;
141
+ if (isXpr(token)) {
142
+ walk(token.xpr);
143
+ continue;
144
+ }
145
+ const op = tokens[i + 1];
146
+ const right = tokens[i + 2];
147
+ if (isAddressRef(token) && op === '=') {
148
+ const value = stringVal(right);
149
+ if (value)
150
+ found.add(value);
151
+ }
152
+ else if (isAddressRef(token) && op === 'in' && right !== undefined && isList(right)) {
153
+ for (const item of right.list) {
154
+ const value = stringVal(item);
155
+ if (value)
156
+ found.add(value);
157
+ }
158
+ }
159
+ else if (right !== undefined && isAddressRef(right) && op === '=') {
160
+ const value = stringVal(token);
161
+ if (value)
162
+ found.add(value);
163
+ }
164
+ }
165
+ };
166
+ const query = req.query;
167
+ walk(('SELECT' in query && query.SELECT?.where) || []);
168
+ return Array.from(found);
169
+ }
170
+ /** READ handler for a child set of Addresses: indexes the named address on a miss, then runs the query. */
171
+ function addressChildRead(isIndexed, index) {
172
+ return async (req) => {
173
+ const addresses = addressesInReadQuery(req);
174
+ if (addresses.length > MAX_ADDRESSES_PER_READ) {
175
+ (0, errors_1.rejectInvalid)(req, 'address_address', `A read may name at most ${MAX_ADDRESSES_PER_READ} addresses`, 'address_address');
176
+ }
177
+ for (const address of addresses) {
178
+ if (!(0, validators_1.isValidBech32Address)(address))
179
+ (0, errors_1.rejectInvalid)(req, 'address_address', 'Invalid bech32 address format', 'address_address');
180
+ }
181
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
182
+ if (addresses.length) {
183
+ widenTemporalWindow(req);
184
+ await indexMissing(db, addresses, isIndexed, index);
185
+ }
186
+ return db.run(req.query);
112
187
  });
113
188
  };
114
189
  }
115
190
  // ---------------------------------------------------------------------------
116
191
  // Service Registration
117
192
  // ---------------------------------------------------------------------------
118
- /**
119
- * Cardano Service Implementation
120
- * Handles various Cardano blockchain data queries with index-on-miss behavior.
121
- */
193
+ /** CardanoODataService handlers: blockchain read queries with index-on-miss. */
122
194
  module.exports = (srv) => {
195
+ (0, result_numbers_1.answerNumbersAsText)(srv);
123
196
  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.
197
+ // For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
198
+ // exports the singular class under the plain name and the entity-set class with a trailing
199
+ // underscore. Handlers must register the entity-set class; a singular one never matches under cds 10.
131
200
  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.
201
+ // Fail fast on a singular class: it would silently degrade to the generic CRUD handler.
135
202
  for (const [name, entity] of Object.entries({
136
203
  NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
137
204
  Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
138
205
  LedgerProtocolParameters, AddressTransactions,
139
206
  })) {
140
207
  if (entity?.is_singular) {
141
- throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class — ` +
208
+ throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class: ` +
142
209
  `READ handlers registered with it never match under cds 10. Destructure the ` +
143
210
  `plural entity-set class instead (e.g. '${name}_ as ${name}').`);
144
211
  }
145
212
  }
146
- // Helper: shorthand for indexer access
147
213
  const indexer = () => (0, server_1.getCardanoIndexer)();
214
+ // The read and the store half of each index-on-miss; the indexer is resolved per request.
215
+ const blockIndex = indexPair((db, hash) => indexer().fetchBlock(db, hash), (db, fetched) => indexer().storeBlock(db, fetched));
216
+ const epochIndex = indexPair((_db, epoch) => indexer().fetchEpoch(epoch), (db, fetched) => indexer().storeEpoch(db, fetched));
217
+ const poolIndex = indexPair((db, poolId) => indexer().fetchPool(db, poolId), (db, fetched) => indexer().storePool(db, fetched));
218
+ const accountIndex = indexPair((db, stakeAddress) => indexer().fetchAccount(db, stakeAddress), (db, fetched) => indexer().storeAccount(db, fetched));
219
+ const drepIndex = indexPair((_db, drepId) => indexer().fetchDrep(drepId), (db, fetched) => indexer().storeDrep(db, fetched));
220
+ const assetIndex = indexPair((db, unit) => indexer().resolveAssetInfo(db, unit), (db, fetched) => indexer().storeAsset(db, fetched));
221
+ const addressIndex = indexPair((db, address) => indexer().fetchAddress(db, address), (db, fetched) => indexer().storeAddress(db, fetched));
222
+ const transactionIndex = indexPair((db, hash) => indexer().fetchTransaction(db, hash), (db, fetched) => indexer().storeTransaction(db, fetched));
223
+ const metadataIndex = indexPair((db, hash) => indexer().fetchTransactionMetadata(db, hash), (db, fetched) => indexer().storeTransactionMetadata(db, fetched));
224
+ const networkIndex = indexPair((db, _key) => indexer().fetchNetworkInformation(db), (db, fetched) => indexer().storeNetworkInformation(db, fetched));
225
+ const protocolParametersIndex = indexPair((db, _key) => indexer().fetchProtocolParameters(db), (db, fetched) => indexer().storeProtocolParameters(db, fetched));
148
226
  // ---------------------------------------------------------------------------
149
227
  // Network Information (singleton - no key field)
150
228
  // ---------------------------------------------------------------------------
151
229
  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;
230
+ const [row] = await indexMissing(db, [null], (d) => d.run(SELECT.one.from(NetworkInformation)), networkIndex);
231
+ return row;
156
232
  }
157
233
  srv.on('READ', NetworkInformation, async (req) => {
158
234
  return (0, backend_request_handler_1.handleRequest)(req, fetchNetworkInformation);
@@ -163,201 +239,193 @@ module.exports = (srv) => {
163
239
  // ---------------------------------------------------------------------------
164
240
  // Blocks
165
241
  // ---------------------------------------------------------------------------
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)));
242
+ srv.on('READ', Blocks, indexOnMissRead(Blocks, 'hash', validators_1.isBlockHash, blockIndex));
243
+ srv.on('GetBlockByHash', indexOnMissAction('GetBlockByHash', Blocks, 'hash', validators_1.isBlockHash, blockIndex));
168
244
  srv.on('GetLatestBlock', async (req) => {
169
245
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestBlock(db));
170
246
  });
171
247
  // ---------------------------------------------------------------------------
172
248
  // Epochs
173
249
  // ---------------------------------------------------------------------------
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' }));
250
+ srv.on('READ', Epochs, indexOnMissRead(Epochs, 'epoch', validators_1.isEpochNumber, epochIndex, { errorMessage: 'epochNumber has invalid format' }));
251
+ srv.on('GetEpochByNumber', indexOnMissAction('GetEpochByNumber', Epochs, 'epochNumber', validators_1.isEpochNumber, epochIndex, { entityKeyField: 'epoch', errorMessage: 'epochNumber has invalid format' }));
176
252
  srv.on('GetLatestEpoch', async (req) => {
177
253
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestEpoch(db));
178
254
  });
179
255
  // ---------------------------------------------------------------------------
180
256
  // Pools
181
257
  // ---------------------------------------------------------------------------
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)));
258
+ srv.on('READ', Pools, indexOnMissRead(Pools, 'poolId', validators_1.isValidPoolId, poolIndex));
259
+ srv.on('GetPoolById', indexOnMissAction('GetPoolById', Pools, 'poolId', validators_1.isValidPoolId, poolIndex));
184
260
  // ---------------------------------------------------------------------------
185
261
  // Accounts
186
262
  // ---------------------------------------------------------------------------
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)));
263
+ srv.on('READ', Accounts, indexOnMissRead(Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, accountIndex));
264
+ srv.on('GetAccountByStakeAddress', indexOnMissAction('GetAccountByStakeAddress', Accounts, 'stakeAddress', validators_1.isValidBech32StakeAddress, accountIndex));
189
265
  // ---------------------------------------------------------------------------
190
266
  // Dreps
191
267
  // ---------------------------------------------------------------------------
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)));
268
+ srv.on('READ', Dreps, indexOnMissRead(Dreps, 'drepId', validators_1.isValidDrepId, drepIndex));
269
+ srv.on('GetDrepById', indexOnMissAction('GetDrepById', Dreps, 'drepId', validators_1.isValidDrepId, drepIndex));
194
270
  // ---------------------------------------------------------------------------
195
271
  // Assets
196
272
  // ---------------------------------------------------------------------------
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.
273
+ srv.on('READ', Assets, indexOnMissRead(Assets, 'unit', validators_1.isAssetUnit, assetIndex, { errorMessage: 'Invalid asset unit format' }));
274
+ srv.on('GetAssetInfo', indexOnMissAction('GetAssetInfo', Assets, 'unit', validators_1.isAssetUnit, assetIndex, { errorMessage: 'Invalid asset unit format' }));
275
+ // Asset history: READ serves stored rows only; GetAssetHistory fetches and stores them.
205
276
  srv.on('READ', AssetHistory, async (req) => {
206
277
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => db.run(req.query));
207
278
  });
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;
279
+ // GetAssetHistory: always-fresh fetch of recent mint/burn events.
280
+ srv.on(CardanoODataService_1.GetAssetHistory, async (req) => {
281
+ const { unit } = req.data;
214
282
  if (!unit)
215
283
  return (0, errors_1.rejectMissing)(req, 'GetAssetHistory', 'unit');
216
284
  if (!(0, validators_1.isAssetUnit)(unit)) {
217
285
  return (0, errors_1.rejectInvalid)(req, 'GetAssetHistory', 'Invalid asset unit format', 'unit');
218
286
  }
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);
287
+ const page = (0, paging_1.latestWindowPage)(req, 'GetAssetHistory', 100);
221
288
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
222
- return await indexer().indexAssetHistory(db, unit, effectiveLimit);
289
+ const events = await indexer().indexAssetHistory(db, unit, page.skip + page.limit);
290
+ return (0, paging_1.pageRows)((0, paging_1.sortAssetHistory)(events), page);
223
291
  });
224
292
  });
225
293
  // ---------------------------------------------------------------------------
226
294
  // Addresses
227
295
  // ---------------------------------------------------------------------------
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) => {
296
+ srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
297
+ srv.on('GetAddressByBech32', indexOnMissAction('GetAddressByBech32', Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
298
+ // GetAssetsByAddress: indexes the parent address if needed, then queries child assets.
299
+ srv.on(CardanoODataService_1.GetAssetsByAddress, async (req) => {
234
300
  const { address } = req.data;
235
301
  if (!address)
236
302
  (0, errors_1.rejectMissing)(req, 'GetAssetsByAddress', 'address');
237
303
  if (!(0, validators_1.isValidBech32Address)(address))
238
304
  (0, errors_1.rejectInvalid)(req, 'GetAssetsByAddress', 'Invalid bech32 address format', 'address');
305
+ const page = (0, paging_1.pageOf)(req.data, 1000);
239
306
  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);
307
+ widenTemporalWindow(req);
308
+ await indexMissing(db, [address], addressIndexed, addressIndex);
243
309
  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());
310
+ return (0, paging_1.pageRows)((0, paging_1.byKey)(latestSlices(assets, (asset) => asset.unit ?? ''), (a) => a.unit ?? ''), page);
252
311
  });
253
312
  });
254
- /**
255
- * Action: GetUTxOsByAddress - indexes parent address if needed, then queries child UTxOs.
256
- */
257
- srv.on('GetUTxOsByAddress', async (req) => {
313
+ // Prefer the full address index; when no configured backend supports getAddress
314
+ // (AllBackendsFailedError with zero collected errors, e.g. Ogmios only), fall back to a
315
+ // UTxO-only index.
316
+ const addressOrUtxosIndex = {
317
+ fetch: async (db, address) => {
318
+ try {
319
+ return await indexer().fetchAddress(db, address);
320
+ }
321
+ catch (err) {
322
+ if (err instanceof errors_1.AllBackendsFailedError && err.errors.length === 0) {
323
+ return { address, utxos: await indexer().fetchAddressUtxos(address) };
324
+ }
325
+ throw err;
326
+ }
327
+ },
328
+ store: (db, fetched) => 'utxos' in fetched
329
+ ? indexer().storeAddressUtxos(db, fetched.address, fetched.utxos)
330
+ : indexer().storeAddress(db, fetched),
331
+ };
332
+ // An address is indexed when its Addresses row is valid. The UTxO-only fallback writes no
333
+ // Addresses row, so for UTxOs a valid AddressUTxOs row counts as well.
334
+ const addressIndexed = async (db, address) => !!(await db.run(SELECT.one.from(Addresses).where({ address })));
335
+ const addressUtxosIndexed = async (db, address) => (await addressIndexed(db, address))
336
+ || !!(await db.run(SELECT.one.from(AddressUTxOs).where({ address_address: address })));
337
+ // GetUTxOsByAddress: indexes the address if needed, then queries child UTxOs.
338
+ srv.on(CardanoODataService_1.GetUTxOsByAddress, async (req) => {
258
339
  const { address } = req.data;
259
340
  if (!address)
260
341
  (0, errors_1.rejectMissing)(req, 'GetUTxOsByAddress', 'address');
261
342
  if (!(0, validators_1.isValidBech32Address)(address))
262
343
  (0, errors_1.rejectInvalid)(req, 'GetUTxOsByAddress', 'Invalid bech32 address format', 'address');
344
+ const page = (0, paging_1.pageOf)(req.data, 1000);
263
345
  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());
346
+ widenTemporalWindow(req);
347
+ await indexMissing(db, [address], addressUtxosIndexed, addressOrUtxosIndex);
348
+ const utxos = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
349
+ return (0, paging_1.pageRows)((0, paging_1.byOutRef)(latestSlices(utxos, (utxo) => `${utxo.hash}#${utxo.index}`)), page);
297
350
  });
298
351
  });
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) => {
352
+ // Collection reads of the address child sets fill like the parent: an address named in the
353
+ // navigation or the $filter is indexed on a miss, then the client's own query runs.
354
+ srv.on('READ', AddressUTxOs, addressChildRead(addressUtxosIndexed, addressOrUtxosIndex));
355
+ srv.on('READ', AddressAssets, addressChildRead(addressIndexed, addressIndex));
356
+ // GetUTxOsByCredential: always-fresh credential-keyed UTxO query (dApp state reads need current
357
+ // data). Crawled UTxO set + node first, else Koios; ProviderUnavailableError without either.
358
+ srv.on(CardanoODataService_1.GetUTxOsByCredential, async (req) => {
306
359
  const { credential } = req.data;
307
360
  if (!credential)
308
361
  return (0, errors_1.rejectMissing)(req, 'GetUTxOsByCredential', 'credential');
309
362
  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');
363
+ return (0, errors_1.rejectInvalid)(req, 'GetUTxOsByCredential', 'Invalid payment credential: expected 56-char lowercase hex (28 bytes)', 'credential');
311
364
  }
312
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
313
- return await indexer().indexCredentialUtxos(db, credential);
314
- });
365
+ const page = (0, paging_1.pageOf)(req.data, 1000);
366
+ 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
367
  });
316
368
  // ---------------------------------------------------------------------------
317
369
  // Transactions
318
370
  // ---------------------------------------------------------------------------
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' }));
371
+ srv.on('READ', Transactions, indexOnMissRead(Transactions, 'hash', validators_1.isTxHash, transactionIndex, { errorMessage: 'Invalid transaction hash format' }));
372
+ srv.on('GetTransactionByHash', indexOnMissAction('GetTransactionByHash', Transactions, 'hash', validators_1.isTxHash, transactionIndex, { errorMessage: 'Invalid transaction hash format' }));
373
+ srv.on(CardanoODataService_1.GetTransactionConfirmations, async (req) => {
374
+ const { txHash } = req.data;
375
+ if (!txHash)
376
+ (0, errors_1.rejectMissing)(req, 'GetTransactionConfirmations', 'txHash');
377
+ if (!(0, validators_1.isTxHash)(txHash))
378
+ (0, errors_1.rejectInvalid)(req, 'GetTransactionConfirmations', 'Invalid transaction hash format', 'txHash');
379
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().resolveTransactionConfirmations(db, txHash));
380
+ });
321
381
  // ---------------------------------------------------------------------------
322
382
  // Transaction Metadata
323
383
  // ---------------------------------------------------------------------------
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) => {
384
+ srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, metadataIndex, { errorMessage: 'Invalid transaction hash format' }));
385
+ // GetMetadataByTxHash: returns all metadata rows of a transaction.
386
+ srv.on(CardanoODataService_1.GetMetadataByTxHash, async (req) => {
330
387
  const { txHash } = req.data;
331
388
  if (!txHash)
332
389
  (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'txHash');
333
390
  if (!(0, validators_1.isTxHash)(txHash))
334
391
  (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'txHash');
392
+ const page = (0, paging_1.pageOf)(req.data, 1000);
335
393
  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;
394
+ const stored = async (d, hash) => {
395
+ const existing = await d.run(SELECT.from(TransactionMetadata).where({ tx_hash: hash }));
396
+ return existing?.length ? existing : null;
397
+ };
398
+ const [rows] = await indexMissing(db, [txHash], stored, metadataIndex);
399
+ return (0, paging_1.pageRows)((0, paging_1.byKey)(rows, (m) => String(m.label ?? '').padStart(20, '0')), page);
341
400
  });
342
401
  });
402
+ // GetMetadataByLabel: stored metadata of one label along the chain. Reads the database only.
403
+ srv.on(CardanoODataService_1.GetMetadataByLabel, async (req) => {
404
+ const { label, fromSlot } = req.data;
405
+ if (label == null || String(label).trim() === '')
406
+ (0, errors_1.rejectMissing)(req, 'GetMetadataByLabel', 'label');
407
+ const id = (0, mappers_1.metadataIdFor)(String(label).trim());
408
+ if (id === null)
409
+ (0, errors_1.rejectInvalid)(req, 'GetMetadataByLabel', 'label must be an unsigned 64-bit integer', 'label');
410
+ const { limit, skip } = (0, paging_1.pageOf)(req.data, 100);
411
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => db.run(SELECT.from(TransactionMetadata).where({ id, txSeq: { '>=': (0, mappers_1.txSeqOf)(Number(fromSlot ?? 0), 0) } }).orderBy('txSeq').limit(limit, skip)));
412
+ });
343
413
  // ---------------------------------------------------------------------------
344
414
  // Protocol Parameters (singleton)
345
415
  // ---------------------------------------------------------------------------
346
416
  srv.on('READ', LedgerProtocolParameters, async (req) => {
347
417
  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;
418
+ const [row] = await indexMissing(db, [null], (d) => d.run(SELECT.one.from(LedgerProtocolParameters)), protocolParametersIndex);
419
+ return row;
352
420
  });
353
421
  });
354
422
  srv.on('GetLedgerProtocolParameters', async (req) => {
355
423
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexProtocolParameters(db));
356
424
  });
357
425
  // ---------------------------------------------------------------------------
358
- // Transaction CBOR parsing (pure utility — no backend / DB touch)
426
+ // Transaction CBOR parsing (pure; no backend or DB access)
359
427
  // ---------------------------------------------------------------------------
360
- srv.on('ParseTransactionCbor', async (req) => {
428
+ srv.on(CardanoODataService_1.ParseTransactionCbor, async (req) => {
361
429
  const { cbor } = req.data;
362
430
  if (cbor == null || cbor === '')
363
431
  (0, errors_1.rejectMissing)(req, 'ParseTransactionCbor', 'cbor');
@@ -366,25 +434,45 @@ module.exports = (srv) => {
366
434
  }
367
435
  return (0, backend_request_handler_1.handleRequest)(req, async () => (0, cbor_1.parseTransaction)(cbor));
368
436
  });
437
+ srv.on(CardanoODataService_1.DecodePlutusData, async (req) => {
438
+ const { cbor } = req.data;
439
+ if (cbor == null || cbor === '')
440
+ (0, errors_1.rejectMissing)(req, 'DecodePlutusData', 'cbor');
441
+ if (!(0, validators_1.isValidTxCborHex)(cbor)) {
442
+ (0, errors_1.rejectInvalid)(req, 'DecodePlutusData', 'Invalid CBOR hex or exceeds size limit', 'cbor');
443
+ }
444
+ return (0, backend_request_handler_1.handleRequest)(req, async () => JSON.stringify((0, cbor_1.decodePlutusData)(cbor)));
445
+ });
369
446
  // ---------------------------------------------------------------------------
370
447
  // Address Transactions
371
448
  // ---------------------------------------------------------------------------
372
- srv.on('GetLatestTransactionsByAddress', async (req) => {
373
- const { address, limit } = req.data;
449
+ // GetLatestTransactionsByAddress: the newest transactions of an address. With sinceTime only
450
+ // newer ones; with waitMs the call re-reads until one appears or the time is up.
451
+ srv.on(CardanoODataService_1.GetLatestTransactionsByAddress, async (req) => {
452
+ const { address, sinceTime, waitMs } = req.data;
374
453
  if (!address)
375
454
  (0, errors_1.rejectMissing)(req, 'GetLatestTransactionsByAddress', 'address');
376
455
  if (!(0, validators_1.isValidBech32Address)(address))
377
456
  (0, errors_1.rejectInvalid)(req, 'GetLatestTransactionsByAddress', 'Invalid bech32 address format', 'address');
378
- const txLimit = Math.min(Math.max(limit || 10, 1), 100);
457
+ if (waitMs && sinceTime == null)
458
+ (0, errors_1.rejectInvalid)(req, 'GetLatestTransactionsByAddress', 'waitMs needs sinceTime', 'waitMs');
459
+ const page = (0, paging_1.latestWindowPage)(req, 'GetLatestTransactionsByAddress', 10);
460
+ const window = page.skip + page.limit;
461
+ const since = sinceTime == null ? null : Number(sinceTime);
462
+ const newer = (rows) => since == null ? rows : rows.filter((r) => Number(r.blockTime ?? 0) > since);
463
+ const deadline = Date.now() + Number(waitMs ?? 0);
464
+ // Every call lists the newest hashes; stored rows are reused, only new ones are fetched.
379
465
  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);
466
+ if (!waitMs)
467
+ return (0, paging_1.pageRows)(newer(await indexer().indexAddressTransactions(db, address, window)), page);
468
+ // each read in its own transaction: a waiting request holds no database connection
469
+ for (;;) {
470
+ const rows = newer(await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => indexer().indexAddressTransactions(tx, address, window))));
471
+ const timeUp = Date.now() + ADDRESS_WAIT_POLL_MS > deadline || req.http?.res.destroyed === true;
472
+ if (rows.length || timeUp)
473
+ return (0, paging_1.pageRows)(rows, page);
474
+ await new Promise((resolve) => setTimeout(resolve, ADDRESS_WAIT_POLL_MS));
386
475
  }
387
- return existing;
388
476
  });
389
477
  });
390
478
  logger.debug('All handlers registered');