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

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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +23 -12
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +36 -44
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -14,6 +14,8 @@ const CardanoODataService_1 = require("#cds-models/CardanoODataService");
14
14
  const mappers_1 = require("./utils/mappers");
15
15
  const tx_utils_1 = require("./utils/tx-utils");
16
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");
17
19
  /** Pause between two reads of a waiting GetLatestTransactionsByAddress call. */
18
20
  const ADDRESS_WAIT_POLL_MS = 5000;
19
21
  /** Newest temporal slice per key; child tables keep one row per validFrom. */
@@ -37,21 +39,30 @@ function indexPair(fetch, store) {
37
39
  // key is read from the provider first, then all are stored. A row stored in the meantime is kept.
38
40
  // Returns the row found or stored per key.
39
41
  async function indexMissing(db, keys, exists, index) {
40
- const rows = await (0, tx_utils_1.readOutside)(db, async (d) => {
41
- const found = [];
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 = [];
42
49
  for (const key of keys)
43
- found.push(await exists(d, key));
44
- return found;
50
+ rows.push(await exists(d, key));
51
+ return rows;
45
52
  });
46
53
  const fetched = new Map();
47
54
  for (const [i, key] of keys.entries()) {
48
- if (!rows[i])
55
+ if (!found[i])
49
56
  fetched.set(i, await index.fetch(db, key));
50
57
  }
51
- for (const [i, value] of fetched) {
52
- rows[i] = (await exists(db, keys[i])) || await index.store(db, value);
53
- }
54
- return rows;
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
+ };
55
66
  }
56
67
  /** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
57
68
  const TEMPORAL_WINDOW_SLACK_MS = 60 * 60 * 1000;
@@ -74,12 +85,12 @@ function widenTemporalWindow(req) {
74
85
  bag['VALID-TO'] = to;
75
86
  }
76
87
  }
77
- /** READ handler that indexes a missing key first, then runs the client's own query (keeps `$expand`, `$select`). */
78
88
  function indexOnMissRead(entity, reqKeyField, validate, index, options) {
79
89
  const dbKey = options?.entityKeyField || reqKeyField;
80
90
  const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
91
+ const exists = options?.exists ?? ((d, k) => d.run(SELECT.one.from(entity).where({ [dbKey]: k })));
81
92
  return async (req) => {
82
- const key = req.data?.[reqKeyField];
93
+ const key = (0, navigation_1.readKey)(req, reqKeyField);
83
94
  // Explicit null check: falsy keys such as epoch=0 or '' must still be validated.
84
95
  if (key !== undefined && key !== null && validate && !validate(key))
85
96
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
@@ -87,7 +98,7 @@ function indexOnMissRead(entity, reqKeyField, validate, index, options) {
87
98
  if (key !== undefined && key !== null) {
88
99
  widenTemporalWindow(req);
89
100
  // 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);
101
+ await indexMissing(db, [key], exists, index);
91
102
  // The client's query is the only authority on the result: never answer with the row
92
103
  // found here, or an excluding $filter / second key would yield a sibling row instead of 404.
93
104
  }
@@ -95,10 +106,20 @@ function indexOnMissRead(entity, reqKeyField, validate, index, options) {
95
106
  });
96
107
  };
97
108
  }
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
+ }
98
117
  /** Factory: action handler with required-key validation and index-on-miss. */
99
118
  function indexOnMissAction(actionName, entity, reqKeyField, validate, index, options) {
100
119
  const dbKey = options?.entityKeyField || reqKeyField;
101
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;
102
123
  return async (req) => {
103
124
  const key = req.data?.[reqKeyField];
104
125
  if (key == null)
@@ -108,13 +129,18 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, index, opt
108
129
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
109
130
  widenTemporalWindow(req);
110
131
  // 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;
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;
113
135
  });
114
136
  };
115
137
  }
116
138
  /** Addresses one collection read may index on a miss; more is a 400. */
117
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
+ };
118
144
  const isRef = (t) => typeof t === 'object' && 'ref' in t;
119
145
  const isVal = (t) => typeof t === 'object' && 'val' in t;
120
146
  const isList = (t) => typeof t === 'object' && 'list' in t;
@@ -197,12 +223,12 @@ module.exports = (srv) => {
197
223
  // For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
198
224
  // exports the singular class under the plain name and the entity-set class with a trailing
199
225
  // underscore. Handlers must register the entity-set class; a singular one never matches under cds 10.
200
- const { NetworkInformation_: NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata_: TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory_: AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
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');
201
227
  // Fail fast on a singular class: it would silently degrade to the generic CRUD handler.
202
228
  for (const [name, entity] of Object.entries({
203
229
  NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
204
230
  Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
205
- LedgerProtocolParameters, AddressTransactions,
231
+ LedgerProtocolParameters, AddressTransactions, TransactionInputs, TransactionOutputs,
206
232
  })) {
207
233
  if (entity?.is_singular) {
208
234
  throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class: ` +
@@ -213,16 +239,13 @@ module.exports = (srv) => {
213
239
  const indexer = () => (0, server_1.getCardanoIndexer)();
214
240
  // The read and the store half of each index-on-miss; the indexer is resolved per request.
215
241
  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
242
  const poolIndex = indexPair((db, poolId) => indexer().fetchPool(db, poolId), (db, fetched) => indexer().storePool(db, fetched));
218
243
  const accountIndex = indexPair((db, stakeAddress) => indexer().fetchAccount(db, stakeAddress), (db, fetched) => indexer().storeAccount(db, fetched));
219
244
  const drepIndex = indexPair((_db, drepId) => indexer().fetchDrep(drepId), (db, fetched) => indexer().storeDrep(db, fetched));
220
245
  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
246
  const transactionIndex = indexPair((db, hash) => indexer().fetchTransaction(db, hash), (db, fetched) => indexer().storeTransaction(db, fetched));
223
247
  const metadataIndex = indexPair((db, hash) => indexer().fetchTransactionMetadata(db, hash), (db, fetched) => indexer().storeTransactionMetadata(db, fetched));
224
248
  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));
226
249
  // ---------------------------------------------------------------------------
227
250
  // Network Information (singleton - no key field)
228
251
  // ---------------------------------------------------------------------------
@@ -230,9 +253,7 @@ module.exports = (srv) => {
230
253
  const [row] = await indexMissing(db, [null], (d) => d.run(SELECT.one.from(NetworkInformation)), networkIndex);
231
254
  return row;
232
255
  }
233
- srv.on('READ', NetworkInformation, async (req) => {
234
- return (0, backend_request_handler_1.handleRequest)(req, fetchNetworkInformation);
235
- });
256
+ srv.on('READ', NetworkInformation, singletonRead(NetworkInformation, networkIndex));
236
257
  srv.on('GetNetworkInformation', async (req) => {
237
258
  return (0, backend_request_handler_1.handleRequest)(req, fetchNetworkInformation);
238
259
  });
@@ -244,11 +265,25 @@ module.exports = (srv) => {
244
265
  srv.on('GetLatestBlock', async (req) => {
245
266
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestBlock(db));
246
267
  });
247
- // ---------------------------------------------------------------------------
248
- // Epochs
249
- // ---------------------------------------------------------------------------
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' }));
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' }));
252
287
  srv.on('GetLatestEpoch', async (req) => {
253
288
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexLatestEpoch(db));
254
289
  });
@@ -293,6 +328,27 @@ module.exports = (srv) => {
293
328
  // ---------------------------------------------------------------------------
294
329
  // Addresses
295
330
  // ---------------------------------------------------------------------------
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 })));
296
352
  srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
297
353
  srv.on('GetAddressByBech32', indexOnMissAction('GetAddressByBech32', Addresses, 'address', validators_1.isValidBech32Address, addressIndex, { errorMessage: 'Invalid bech32 address format' }));
298
354
  // GetAssetsByAddress: indexes the parent address if needed, then queries child assets.
@@ -310,30 +366,6 @@ module.exports = (srv) => {
310
366
  return (0, paging_1.pageRows)((0, paging_1.byKey)(latestSlices(assets, (asset) => asset.unit ?? ''), (a) => a.unit ?? ''), page);
311
367
  });
312
368
  });
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
369
  // GetUTxOsByAddress: indexes the address if needed, then queries child UTxOs.
338
370
  srv.on(CardanoODataService_1.GetUTxOsByAddress, async (req) => {
339
371
  const { address } = req.data;
@@ -344,15 +376,16 @@ module.exports = (srv) => {
344
376
  const page = (0, paging_1.pageOf)(req.data, 1000);
345
377
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
346
378
  widenTemporalWindow(req);
347
- await indexMissing(db, [address], addressUtxosIndexed, addressOrUtxosIndex);
379
+ await indexMissing(db, [address], addressIndexed, addressIndex);
348
380
  const utxos = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
349
381
  return (0, paging_1.pageRows)((0, paging_1.byOutRef)(latestSlices(utxos, (utxo) => `${utxo.hash}#${utxo.index}`)), page);
350
382
  });
351
383
  });
352
384
  // Collection reads of the address child sets fill like the parent: an address named in the
353
385
  // navigation or the $filter is indexed on a miss, then the client's own query runs.
354
- srv.on('READ', AddressUTxOs, addressChildRead(addressUtxosIndexed, addressOrUtxosIndex));
386
+ srv.on('READ', AddressUTxOs, addressChildRead(addressIndexed, addressIndex));
355
387
  srv.on('READ', AddressAssets, addressChildRead(addressIndexed, addressIndex));
388
+ srv.on('READ', AddressTransactions, addressChildRead(addressIndexed, addressIndex));
356
389
  // GetUTxOsByCredential: always-fresh credential-keyed UTxO query (dApp state reads need current
357
390
  // data). Crawled UTxO set + node first, else Koios; ProviderUnavailableError without either.
358
391
  srv.on(CardanoODataService_1.GetUTxOsByCredential, async (req) => {
@@ -408,17 +441,29 @@ module.exports = (srv) => {
408
441
  if (id === null)
409
442
  (0, errors_1.rejectInvalid)(req, 'GetMetadataByLabel', 'label must be an unsigned 64-bit integer', 'label');
410
443
  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)));
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));
412
449
  });
413
450
  // ---------------------------------------------------------------------------
414
451
  // Protocol Parameters (singleton)
415
452
  // ---------------------------------------------------------------------------
416
- srv.on('READ', LedgerProtocolParameters, async (req) => {
417
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
418
- const [row] = await indexMissing(db, [null], (d) => d.run(SELECT.one.from(LedgerProtocolParameters)), protocolParametersIndex);
419
- return row;
420
- });
421
- });
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
+ }));
422
467
  srv.on('GetLedgerProtocolParameters', async (req) => {
423
468
  return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexProtocolParameters(db));
424
469
  });
@@ -443,9 +488,24 @@ module.exports = (srv) => {
443
488
  }
444
489
  return (0, backend_request_handler_1.handleRequest)(req, async () => JSON.stringify((0, cbor_1.decodePlutusData)(cbor)));
445
490
  });
446
- // ---------------------------------------------------------------------------
447
- // Address Transactions
448
- // ---------------------------------------------------------------------------
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
+ };
449
509
  // GetLatestTransactionsByAddress: the newest transactions of an address. With sinceTime only
450
510
  // newer ones; with waitMs the call re-reads until one appears or the time is up.
451
511
  srv.on(CardanoODataService_1.GetLatestTransactionsByAddress, async (req) => {
@@ -465,16 +525,291 @@ module.exports = (srv) => {
465
525
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
466
526
  if (!waitMs)
467
527
  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)
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)
473
535
  return (0, paging_1.pageRows)(rows, page);
474
- await new Promise((resolve) => setTimeout(resolve, ADDRESS_WAIT_POLL_MS));
536
+ await new Promise((resolve) => setTimeout(resolve, Math.min(remaining, ADDRESS_WAIT_POLL_MS)));
475
537
  }
476
538
  });
477
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])];
717
+ }
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();
788
+ });
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
+ });
478
813
  logger.debug('All handlers registered');
479
814
  };
480
815
  //# sourceMappingURL=cardano-service.js.map
@@ -1,5 +1,5 @@
1
1
  using {odatano.cardano as db} from '../db/schema';
2
- using {Bech32} from '../db/types';
2
+ using {Bech32, ResolvedOutcome} from '../db/types';
3
3
 
4
4
  // External signing: signing requests, signature checks, submission and HSM signing.
5
5
  // The service itself is 'any': CAP checks the service before the operation, so anything stricter
@@ -186,6 +186,16 @@ service CardanoSignService @(impl: './cardano-sign-service') {
186
186
  @description: 'When true, sign + verify + claim run on the caller''s transaction and the network submit happens detached AFTER the caller''s commit (see SubmitVerifiedTransaction.deferSubmit).'
187
187
  deferSubmit: Boolean) returns TransactionSubmissions;
188
188
 
189
+ @title : 'Resolve Signing Request'
190
+ @description: 'Settle an unresolved signing request after reading the chain: confirmed when its transaction is on chain with passing scripts (the submission record is then written), failed when it is not and can no longer land; failed is refused with 409 while the transaction is not expired and an input of it is unspent. txHash, when given, must be the request transaction.'
191
+ @requires : 'Admin'
192
+ @odatano.agent: 'operator'
193
+ action ResolveSigningRequest(
194
+ @title: 'Signing Request ID' signingRequestId: UUID not null,
195
+ @title: 'Outcome' @assert.range outcome: ResolvedOutcome not null,
196
+ @title: 'Transaction Hash' txHash: String(64),
197
+ @title: 'Note' note: String(300)) returns SigningRequests;
198
+
189
199
  @title : 'Get HSM Status'
190
200
  @description: 'Check the current status of the HSM connection and key availability.'
191
201
  @requires : 'Sign'