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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -9,30 +9,27 @@ 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
+ /** Newest temporal slice per key; child tables keep one row per validFrom. */
13
+ function latestSlices(rows, keyOf) {
14
+ const seen = new Map();
15
+ for (const row of rows) {
16
+ const key = keyOf(row);
17
+ const prev = seen.get(key);
18
+ if (!prev || (row.validFrom ?? '') > (prev.validFrom ?? ''))
19
+ seen.set(key, row);
20
+ }
21
+ return Array.from(seen.values());
22
+ }
12
23
  const { SELECT } = cds_1.default.ql;
13
24
  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
- */
25
+ /** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
19
26
  const TEMPORAL_WINDOW_SLACK_MS = 60 * 60 * 1000;
20
27
  /**
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.
28
+ * Let this request see the temporal slices it writes during index-on-miss: CAP's temporal
29
+ * filter (`validFrom < $valid.to`) defaults to a `now`..`now+1ms` window fixed at transaction
30
+ * start, so a slice stamped after the backend fetch would be invisible to the handler's
31
+ * re-read. Only the upper bound moves; explicit `sap-valid-*` options are left alone.
32
+ * Must run before the handler's first DB statement.
36
33
  */
37
34
  function widenTemporalWindow(req) {
38
35
  const q = req.http?.req?.query;
@@ -41,9 +38,7 @@ function widenTemporalWindow(req) {
41
38
  const now = Date.now();
42
39
  const from = new Date(now).toISOString();
43
40
  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.
41
+ // The DB session reads the bag of whichever context opened the transaction; stamp both.
47
42
  const r = req;
48
43
  for (const bag of new Set([r._, r.context?._])) {
49
44
  if (!bag)
@@ -53,47 +48,32 @@ function widenTemporalWindow(req) {
53
48
  }
54
49
  }
55
50
  /**
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.
51
+ * Factory: READ handler with index-on-miss. With a key, indexes on a cache miss and then
52
+ * runs the client's own query so `$expand` / `$select` apply; without a key, passes through.
61
53
  */
62
54
  function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
63
55
  const dbKey = options?.entityKeyField || reqKeyField;
64
56
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
65
57
  return async (req) => {
66
58
  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)
59
+ // Explicit null check: falsy keys such as epoch=0 or '' must still be validated.
69
60
  if (key !== undefined && key !== null && validate && !validate(key))
70
61
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
71
62
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
72
63
  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)
64
+ widenTemporalWindow(req); // before the first DB statement
65
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
75
66
  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
67
  if (!existing)
80
68
  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.
69
+ // The client's query is the only authority on the result: never fall back to
70
+ // `existing`, or an excluding $filter / second key would yield a sibling row instead of 404.
89
71
  }
90
72
  return db.run(req.query);
91
73
  });
92
74
  };
93
75
  }
94
- /**
95
- * Factory: Action handler with required key validation and index-on-miss.
96
- */
76
+ /** Factory: action handler with required-key validation and index-on-miss. */
97
77
  function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, options) {
98
78
  const dbKey = options?.entityKeyField || reqKeyField;
99
79
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
@@ -104,7 +84,7 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
104
84
  if (!validate(key))
105
85
  (0, errors_1.rejectInvalid)(req, actionName, errMsg, reqKeyField);
106
86
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
107
- // CAP temporal aspect auto-filters expired records (validTo < now → not returned)
87
+ // The temporal aspect hides expired rows, so a miss here triggers a re-index.
108
88
  const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
109
89
  if (!existing)
110
90
  return await indexFn(db, key);
@@ -112,26 +92,102 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
112
92
  });
113
93
  };
114
94
  }
95
+ /** Addresses one collection read may index on a miss; more is a 400. */
96
+ const MAX_ADDRESSES_PER_READ = 10;
97
+ const isRef = (t) => typeof t === 'object' && 'ref' in t;
98
+ const isVal = (t) => typeof t === 'object' && 'val' in t;
99
+ const isList = (t) => typeof t === 'object' && 'list' in t;
100
+ const isXpr = (t) => typeof t === 'object' && 'xpr' in t;
101
+ /** `address_address` or the association path `address/address`. */
102
+ function isAddressRef(t) {
103
+ if (!isRef(t))
104
+ return false;
105
+ const path = t.ref;
106
+ return (path.length === 1 && path[0] === 'address_address') || (path.length === 2 && path[0] === 'address' && path[1] === 'address');
107
+ }
108
+ const stringVal = (t) => t !== undefined && isVal(t) && typeof t.val === 'string' ? t.val : undefined;
109
+ /**
110
+ * Addresses a read of an address child set names: the parent of a navigation
111
+ * (`Addresses('…')/utxos`) or the `$filter` terms `address_address eq '…'` (either operand
112
+ * order) and `address_address in ('…', …)`.
113
+ */
114
+ function addressesInReadQuery(req) {
115
+ const found = new Set();
116
+ const parent = req.data?.address_address;
117
+ if (typeof parent === 'string')
118
+ found.add(parent);
119
+ const walk = (tokens) => {
120
+ for (let i = 0; i < tokens.length; i++) {
121
+ const token = tokens[i];
122
+ if (typeof token === 'string')
123
+ continue;
124
+ if (isXpr(token)) {
125
+ walk(token.xpr);
126
+ continue;
127
+ }
128
+ const op = tokens[i + 1];
129
+ const right = tokens[i + 2];
130
+ if (isAddressRef(token) && op === '=') {
131
+ const value = stringVal(right);
132
+ if (value)
133
+ found.add(value);
134
+ }
135
+ else if (isAddressRef(token) && op === 'in' && right !== undefined && isList(right)) {
136
+ for (const item of right.list) {
137
+ const value = stringVal(item);
138
+ if (value)
139
+ found.add(value);
140
+ }
141
+ }
142
+ else if (right !== undefined && isAddressRef(right) && op === '=') {
143
+ const value = stringVal(token);
144
+ if (value)
145
+ found.add(value);
146
+ }
147
+ }
148
+ };
149
+ const query = req.query;
150
+ walk(('SELECT' in query && query.SELECT?.where) || []);
151
+ return Array.from(found);
152
+ }
153
+ /**
154
+ * Factory: READ handler for a child set of Addresses with index-on-miss. The address is taken
155
+ * from the navigation parent or the `$filter`; without one the read passes through.
156
+ * `isIndexed` says whether the address needs no fetch, `indexFn` fetches it.
157
+ */
158
+ function addressChildRead(isIndexed, indexFn) {
159
+ return async (req) => {
160
+ const addresses = addressesInReadQuery(req);
161
+ if (addresses.length > MAX_ADDRESSES_PER_READ) {
162
+ (0, errors_1.rejectInvalid)(req, 'address_address', `A read may name at most ${MAX_ADDRESSES_PER_READ} addresses`, 'address_address');
163
+ }
164
+ for (const address of addresses) {
165
+ if (!(0, validators_1.isValidBech32Address)(address))
166
+ (0, errors_1.rejectInvalid)(req, 'address_address', 'Invalid bech32 address format', 'address_address');
167
+ }
168
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
169
+ if (addresses.length) {
170
+ widenTemporalWindow(req); // before the first DB statement
171
+ for (const address of addresses) {
172
+ if (!(await isIndexed(db, address)))
173
+ await indexFn(db, address);
174
+ }
175
+ }
176
+ return db.run(req.query);
177
+ });
178
+ };
179
+ }
115
180
  // ---------------------------------------------------------------------------
116
181
  // Service Registration
117
182
  // ---------------------------------------------------------------------------
118
- /**
119
- * Cardano Service Implementation
120
- * Handles various Cardano blockchain data queries with index-on-miss behavior.
121
- */
183
+ /** CardanoODataService handlers: blockchain read queries with index-on-miss. */
122
184
  module.exports = (srv) => {
123
185
  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.
186
+ // For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
187
+ // exports the singular class under the plain name and the entity-set class with a trailing
188
+ // underscore. Handlers must register the entity-set class; a singular one never matches under cds 10.
131
189
  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.
190
+ // Fail fast on a singular class: it would silently degrade to the generic CRUD handler.
135
191
  for (const [name, entity] of Object.entries({
136
192
  NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
137
193
  Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
@@ -143,7 +199,6 @@ module.exports = (srv) => {
143
199
  `plural entity-set class instead (e.g. '${name}_ as ${name}').`);
144
200
  }
145
201
  }
146
- // Helper: shorthand for indexer access
147
202
  const indexer = () => (0, server_1.getCardanoIndexer)();
148
203
  // ---------------------------------------------------------------------------
149
204
  // Network Information (singleton - no key field)
@@ -197,18 +252,13 @@ module.exports = (srv) => {
197
252
  srv.on('READ', Assets, indexOnMissRead(Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
198
253
  srv.on('GetAssetInfo', indexOnMissAction('GetAssetInfo', Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
199
254
  // ---------------------------------------------------------------------------
200
- // Asset History — read-through (always-fresh)
255
+ // Asset History
201
256
  // ---------------------------------------------------------------------------
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.
257
+ // Generic READ is served from the DB only; GetAssetHistory(unit) seeds the rows.
205
258
  srv.on('READ', AssetHistory, async (req) => {
206
259
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => db.run(req.query));
207
260
  });
208
- /**
209
- * Action: GetAssetHistory - Always-fresh fetch of recent mint/burn events.
210
- * Multi-backend: Koios preferred (block timestamps), Blockfrost fallback.
211
- */
261
+ // GetAssetHistory — always-fresh fetch of recent mint/burn events.
212
262
  srv.on('GetAssetHistory', async (req) => {
213
263
  const { unit, limit } = req.data;
214
264
  if (!unit)
@@ -216,7 +266,7 @@ module.exports = (srv) => {
216
266
  if (!(0, validators_1.isAssetUnit)(unit)) {
217
267
  return (0, errors_1.rejectInvalid)(req, 'GetAssetHistory', 'Invalid asset unit format', 'unit');
218
268
  }
219
- // clamp like GetLatestTransactionsByAddress — unbounded limits page the upstream backend indefinitely
269
+ // Clamp: an unbounded limit would page the upstream backend indefinitely.
220
270
  const effectiveLimit = Math.min(Math.max(typeof limit === 'number' ? limit : 100, 1), 100);
221
271
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
222
272
  return await indexer().indexAssetHistory(db, unit, effectiveLimit);
@@ -227,9 +277,7 @@ module.exports = (srv) => {
227
277
  // ---------------------------------------------------------------------------
228
278
  srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, (db, a) => indexer().indexAddress(db, a), { errorMessage: 'Invalid bech32 address format' }));
229
279
  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
- */
280
+ // GetAssetsByAddress — indexes the parent address if needed, then queries child assets.
233
281
  srv.on('GetAssetsByAddress', async (req) => {
234
282
  const { address } = req.data;
235
283
  if (!address)
@@ -237,23 +285,36 @@ module.exports = (srv) => {
237
285
  if (!(0, validators_1.isValidBech32Address)(address))
238
286
  (0, errors_1.rejectInvalid)(req, 'GetAssetsByAddress', 'Invalid bech32 address format', 'address');
239
287
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
288
+ widenTemporalWindow(req); // before the first DB statement
240
289
  const existing = await db.run(SELECT.one.from(Addresses).where({ address }));
241
290
  if (!existing)
242
291
  await indexer().indexAddress(db, address);
243
292
  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());
293
+ return latestSlices(assets, (asset) => asset.unit ?? '');
252
294
  });
253
295
  });
254
- /**
255
- * Action: GetUTxOsByAddress - indexes parent address if needed, then queries child UTxOs.
256
- */
296
+ // Prefer the full address index; when no configured backend supports getAddress
297
+ // (AllBackendsFailedError with zero collected errors, e.g. Ogmios only), fall back to a
298
+ // UTxO-only index. getAddress is indexAddress's first call, so nothing is persisted before.
299
+ const indexAddressOrUtxos = async (db, address) => {
300
+ try {
301
+ await indexer().indexAddress(db, address);
302
+ }
303
+ catch (err) {
304
+ if (err instanceof errors_1.AllBackendsFailedError && err.errors.length === 0) {
305
+ await indexer().indexAddressUtxos(db, address);
306
+ }
307
+ else {
308
+ throw err;
309
+ }
310
+ }
311
+ };
312
+ // An address is indexed when its Addresses row is valid. The UTxO-only fallback writes no
313
+ // Addresses row, so for UTxOs a valid AddressUTxOs row counts as well.
314
+ const addressIndexed = async (db, address) => !!(await db.run(SELECT.one.from(Addresses).where({ address })));
315
+ const addressUtxosIndexed = async (db, address) => (await addressIndexed(db, address))
316
+ || !!(await db.run(SELECT.one.from(AddressUTxOs).where({ address_address: address })));
317
+ // GetUTxOsByAddress — indexes the address if needed, then queries child UTxOs.
257
318
  srv.on('GetUTxOsByAddress', async (req) => {
258
319
  const { address } = req.data;
259
320
  if (!address)
@@ -261,47 +322,19 @@ module.exports = (srv) => {
261
322
  if (!(0, validators_1.isValidBech32Address)(address))
262
323
  (0, errors_1.rejectInvalid)(req, 'GetUTxOsByAddress', 'Invalid bech32 address format', 'address');
263
324
  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());
325
+ widenTemporalWindow(req); // before the first DB statement
326
+ if (!(await addressUtxosIndexed(db, address)))
327
+ await indexAddressOrUtxos(db, address);
328
+ const utxos = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
329
+ return latestSlices(utxos, (utxo) => `${utxo.hash}#${utxo.index}`);
297
330
  });
298
331
  });
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
- */
332
+ // Collection reads of the address child sets fill like the parent: an address named in the
333
+ // navigation or the $filter is indexed on a miss, then the client's own query runs.
334
+ srv.on('READ', AddressUTxOs, addressChildRead(addressUtxosIndexed, indexAddressOrUtxos));
335
+ srv.on('READ', AddressAssets, addressChildRead(addressIndexed, (db, address) => indexer().indexAddress(db, address)));
336
+ // GetUTxOsByCredential — always-fresh credential-keyed UTxO query (dApp state reads need current
337
+ // data). Crawled UTxO set + node first, else Koios; ProviderUnavailableError without either.
305
338
  srv.on('GetUTxOsByCredential', async (req) => {
306
339
  const { credential } = req.data;
307
340
  if (!credential)
@@ -318,14 +351,19 @@ module.exports = (srv) => {
318
351
  // ---------------------------------------------------------------------------
319
352
  srv.on('READ', Transactions, indexOnMissRead(Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
320
353
  srv.on('GetTransactionByHash', indexOnMissAction('GetTransactionByHash', Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
354
+ srv.on('GetTransactionConfirmations', async (req) => {
355
+ const { txHash } = req.data;
356
+ if (!txHash)
357
+ (0, errors_1.rejectMissing)(req, 'GetTransactionConfirmations', 'txHash');
358
+ if (!(0, validators_1.isTxHash)(txHash))
359
+ (0, errors_1.rejectInvalid)(req, 'GetTransactionConfirmations', 'Invalid transaction hash format', 'txHash');
360
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().resolveTransactionConfirmations(db, txHash));
361
+ });
321
362
  // ---------------------------------------------------------------------------
322
363
  // Transaction Metadata
323
364
  // ---------------------------------------------------------------------------
324
365
  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
- */
366
+ // GetMetadataByTxHash — returns all metadata rows of a transaction.
329
367
  srv.on('GetMetadataByTxHash', async (req) => {
330
368
  const { txHash } = req.data;
331
369
  if (!txHash)
@@ -355,7 +393,7 @@ module.exports = (srv) => {
355
393
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexProtocolParameters(db));
356
394
  });
357
395
  // ---------------------------------------------------------------------------
358
- // Transaction CBOR parsing (pure utility — no backend / DB touch)
396
+ // Transaction CBOR parsing (pure; no backend or DB access)
359
397
  // ---------------------------------------------------------------------------
360
398
  srv.on('ParseTransactionCbor', async (req) => {
361
399
  const { cbor } = req.data;
@@ -377,6 +415,9 @@ module.exports = (srv) => {
377
415
  (0, errors_1.rejectInvalid)(req, 'GetLatestTransactionsByAddress', 'Invalid bech32 address format', 'address');
378
416
  const txLimit = Math.min(Math.max(limit || 10, 1), 100);
379
417
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
418
+ // The crawled UTxO set is current; the cached rows may miss the newest transactions.
419
+ if (await indexer().ledgerCoverageActive(db))
420
+ return indexer().indexAddressTransactions(db, address, txLimit);
380
421
  const existing = await db.run(SELECT.from(AddressTransactions)
381
422
  .where({ address_address: address })
382
423
  .orderBy('blockTime desc')