@odatano/core 1.11.0 → 2.0.0-rc.2

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 (111) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
  2. package/@cds-models/CardanoIndexerService/index.js +23 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  4. package/@cds-models/CardanoODataService/index.js +88 -390
  5. package/@cds-models/CardanoSignService/index.d.ts +443 -1574
  6. package/@cds-models/CardanoSignService/index.js +62 -293
  7. package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
  8. package/@cds-models/CardanoTransactionService/index.js +60 -271
  9. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  10. package/@cds-models/CardanoWorkerService/index.js +32 -0
  11. package/@cds-models/_/index.d.ts +70 -40
  12. package/@cds-models/_/index.js +17 -32
  13. package/@cds-models/cds/outbox/index.d.ts +28 -0
  14. package/@cds-models/index.d.ts +225 -522
  15. package/@cds-models/index.js +35 -218
  16. package/@cds-models/odatano/cardano/index.d.ts +896 -2947
  17. package/@cds-models/odatano/cardano/index.js +109 -536
  18. package/@cds-models/sap/common/index.d.ts +196 -600
  19. package/@cds-models/sap/common/index.js +28 -269
  20. package/README.md +36 -2
  21. package/db/schema.cds +283 -1
  22. package/db/types.cds +48 -0
  23. package/package.json +173 -164
  24. package/src/index.d.ts +1 -1
  25. package/src/index.js +10 -2
  26. package/src/plugin.js +12 -2
  27. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  28. package/srv/blockchain/backends/blockfrost-backend.js +68 -15
  29. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  30. package/srv/blockchain/backends/cardano-backend.js +13 -0
  31. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  32. package/srv/blockchain/backends/koios-backend.js +147 -15
  33. package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
  34. package/srv/blockchain/backends/ogmios-backend.js +254 -5
  35. package/srv/blockchain/cardano-client.d.ts +19 -0
  36. package/srv/blockchain/cardano-client.js +36 -0
  37. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  38. package/srv/blockchain/cardano-indexer.js +191 -0
  39. package/srv/blockchain/crawler/crawler.d.ts +151 -0
  40. package/srv/blockchain/crawler/crawler.js +677 -0
  41. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  42. package/srv/blockchain/crawler/hooks.js +62 -0
  43. package/srv/blockchain/crawler/index.d.ts +26 -0
  44. package/srv/blockchain/crawler/index.js +135 -0
  45. package/srv/blockchain/crawler/sync-state.d.ts +94 -0
  46. package/srv/blockchain/crawler/sync-state.js +265 -0
  47. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  48. package/srv/blockchain/signing/hsm-signer.js +8 -1
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  50. package/srv/blockchain/wallet-worker/build-request.js +341 -0
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
  53. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  54. package/srv/blockchain/wallet-worker/index.js +80 -0
  55. package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
  56. package/srv/blockchain/wallet-worker/job-store.js +564 -0
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  58. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  59. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  60. package/srv/blockchain/wallet-worker/signers.js +131 -0
  61. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  62. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  63. package/srv/cardano-indexer-service.cds +73 -0
  64. package/srv/cardano-indexer-service.d.ts +2 -0
  65. package/srv/cardano-indexer-service.js +76 -0
  66. package/srv/cardano-service.js +76 -5
  67. package/srv/cardano-tx-service.d.ts +1 -11
  68. package/srv/cardano-tx-service.js +11 -162
  69. package/srv/cardano-worker-service.cds +125 -0
  70. package/srv/cardano-worker-service.d.ts +2 -0
  71. package/srv/cardano-worker-service.js +199 -0
  72. package/srv/server.d.ts +32 -1
  73. package/srv/server.js +229 -36
  74. package/srv/utils/collections.d.ts +13 -0
  75. package/srv/utils/collections.js +24 -0
  76. package/srv/utils/crypto.d.ts +16 -0
  77. package/srv/utils/crypto.js +75 -0
  78. package/srv/utils/error-codes.d.ts +6 -0
  79. package/srv/utils/error-codes.js +6 -0
  80. package/srv/utils/errors.d.ts +12 -0
  81. package/srv/utils/errors.js +45 -0
  82. package/srv/utils/mappers.js +13 -3
  83. package/srv/utils/service-events.d.ts +26 -0
  84. package/srv/utils/service-events.js +46 -0
  85. package/srv/utils/tx-request-parsers.d.ts +58 -0
  86. package/srv/utils/tx-request-parsers.js +170 -0
  87. package/srv/utils/tx-utils.d.ts +2 -1
  88. package/srv/utils/tx-utils.js +3 -2
  89. package/srv/utils/types.d.ts +2 -1
  90. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  91. package/@cds-models/CardanoODataService/index.js.map +0 -1
  92. package/@cds-models/CardanoODataService/index.ts +0 -776
  93. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  94. package/@cds-models/CardanoSignService/index.js.map +0 -1
  95. package/@cds-models/CardanoSignService/index.ts +0 -569
  96. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  97. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  98. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  99. package/@cds-models/_/index.d.ts.map +0 -1
  100. package/@cds-models/_/index.js.map +0 -1
  101. package/@cds-models/_/index.ts +0 -96
  102. package/@cds-models/cds/outbox/index.ts +0 -27
  103. package/@cds-models/index.d.ts.map +0 -1
  104. package/@cds-models/index.js.map +0 -1
  105. package/@cds-models/index.ts +0 -245
  106. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  107. package/@cds-models/odatano/cardano/index.js.map +0 -1
  108. package/@cds-models/odatano/cardano/index.ts +0 -789
  109. package/@cds-models/sap/common/index.d.ts.map +0 -1
  110. package/@cds-models/sap/common/index.js.map +0 -1
  111. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cds_1 = __importDefault(require("@sap/cds"));
7
+ const backend_request_handler_1 = require("./utils/backend-request-handler");
8
+ const errors_1 = require("./utils/errors");
9
+ const crawler_1 = require("./blockchain/crawler");
10
+ const sync_state_1 = require("./blockchain/crawler/sync-state");
11
+ const server_1 = require("./server");
12
+ const logger = cds_1.default.log('CardanoIndexerService');
13
+ /**
14
+ * CardanoIndexerService handlers — thin control/observability surface over the crawler
15
+ * singleton (srv/blockchain/crawler). Engine logic lives there; this only reads the
16
+ * cursor and starts/stops the crawler.
17
+ */
18
+ module.exports = (srv) => {
19
+ // getStatus — live run state + sync progress (numeric fields as strings, CAP-10 aligned)
20
+ srv.on('getStatus', async (req) => {
21
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
22
+ const cursor = await (0, sync_state_1.readCursor)(db);
23
+ const lastHeight = cursor?.lastHeight ?? 0;
24
+ const tipHeight = cursor?.tipHeight ?? 0;
25
+ const progress = tipHeight > 0 ? Math.min(100, (lastHeight / tipHeight) * 100) : 0;
26
+ return {
27
+ running: (0, sync_state_1.isCrawlerLeaseActive)(cursor),
28
+ syncStatus: cursor?.syncStatus ?? 'stopped',
29
+ lastSlot: String(cursor?.lastSlot ?? 0),
30
+ lastHeight: String(lastHeight),
31
+ tipHeight: String(tipHeight),
32
+ syncProgress: progress.toFixed(2),
33
+ consecutiveErrors: cursor?.consecutiveErrors ?? 0,
34
+ };
35
+ });
36
+ });
37
+ // pauseCrawler — stop the stream; the cursor is preserved so resume continues.
38
+ srv.on('pauseCrawler', async (req) => {
39
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
40
+ await (0, crawler_1.stopCrawler)(true);
41
+ logger.info('Crawler paused via control action');
42
+ return true;
43
+ });
44
+ });
45
+ // resumeCrawler — (re)start from the persisted cursor using the configured source.
46
+ // Gated on config.enabled: the control action must not start a crawler the operator
47
+ // never configured (an unconfigured start would otherwise sync from genesis).
48
+ // NOTE: to apply CHANGED config to a running crawler, call pauseCrawler first —
49
+ // resume on a running crawler is a no-op by design.
50
+ srv.on('resumeCrawler', async (req) => {
51
+ let config;
52
+ try {
53
+ config = (0, server_1.loadCrawlerConfigFromEnv)();
54
+ }
55
+ catch (err) {
56
+ // e.g. ConfigError: enabled but no start block — a config problem is the
57
+ // caller's 400, not a raw 500 from an escaping throw
58
+ return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', err instanceof Error ? err.message : String(err));
59
+ }
60
+ if (!config.enabled) {
61
+ return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', 'Crawler is not enabled — set cds.requires.odatano-core.crawler.enabled (or CRAWLER_ENABLED=true) with a start block before resuming.');
62
+ }
63
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
64
+ const client = (0, server_1.getCardanoClient)();
65
+ await (0, crawler_1.startCrawler)({
66
+ client,
67
+ indexer: (0, server_1.getCardanoIndexer)(),
68
+ network: client.network,
69
+ config,
70
+ }, true);
71
+ logger.info('Crawler resumed via control action');
72
+ return (0, crawler_1.isCrawlerRunningInCluster)();
73
+ });
74
+ });
75
+ };
76
+ //# sourceMappingURL=cardano-indexer-service.js.map
@@ -11,9 +11,52 @@ const backend_request_handler_1 = require("./utils/backend-request-handler");
11
11
  const cbor_1 = require("./cbor");
12
12
  const { SELECT } = cds_1.default.ql;
13
13
  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
+ */
19
+ 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
+ */
37
+ function widenTemporalWindow(req) {
38
+ const q = req.http?.req?.query;
39
+ if (q && (q['sap-valid-at'] || q['sap-valid-from'] || q['sap-valid-to']))
40
+ return;
41
+ const now = Date.now();
42
+ const from = new Date(now).toISOString();
43
+ 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.
47
+ const r = req;
48
+ for (const bag of new Set([r._, r.context?._])) {
49
+ if (!bag)
50
+ continue;
51
+ bag['VALID-FROM'] = from;
52
+ bag['VALID-TO'] = to;
53
+ }
54
+ }
14
55
  /**
15
56
  * Factory: READ handler with index-on-miss behavior.
16
- * If a key is provided, checks cache first; indexes if missing.
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).
17
60
  * If no key, passes through to generic req.query.
18
61
  */
19
62
  function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
@@ -27,11 +70,18 @@ function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
27
70
  (0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
28
71
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
29
72
  if (key !== undefined && key !== null) {
73
+ widenTemporalWindow(req); // before the first DB statement — see doc comment
30
74
  // CAP temporal aspect auto-filters expired records (validTo < now → not returned)
31
75
  const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
32
- if (!existing)
33
- return await indexFn(db, key);
34
- return existing;
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
+ const indexed = existing ? undefined : await indexFn(db, key);
80
+ const result = await db.run(req.query);
81
+ // Safety net: if the freshly written slice is still outside the session's
82
+ // temporal window (widening had no effect, e.g. the transaction was already
83
+ // open), degrade to the pre-#13 behaviour — bare row instead of a wrong 404.
84
+ return result ?? indexed ?? existing;
35
85
  }
36
86
  return db.run(req.query);
37
87
  });
@@ -67,7 +117,28 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
67
117
  */
68
118
  module.exports = (srv) => {
69
119
  logger.debug('Module loaded - registering handlers');
70
- const { NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
120
+ // NOTE: for entities whose name is already plural-shaped (NetworkInformation,
121
+ // TransactionMetadata, AssetHistory) cds-typer exports the SINGULAR class under the
122
+ // plain name and the plural (entity-set) class with a trailing underscore. Handler
123
+ // registration must use the plural class — under cds 10 registering `srv.on('READ',
124
+ // <singular proxy>)` no longer matches incoming OData READs, so the generic CRUD
125
+ // handler silently served those entities (empty results / 404 instead of
126
+ // index-on-miss). All other names below already resolve to plural classes.
127
+ const { NetworkInformation_: NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata_: TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory_: AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
128
+ // Fail fast if a future edit reintroduces a SINGULAR class here (the cds-10 trap
129
+ // above): a singular registration silently degrades to the generic CRUD handler.
130
+ // Every cds-typer proxy carries an explicit is_singular marker we can assert on.
131
+ for (const [name, entity] of Object.entries({
132
+ NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
133
+ Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
134
+ LedgerProtocolParameters, AddressTransactions,
135
+ })) {
136
+ if (entity?.is_singular) {
137
+ throw new Error(`CardanoODataService: '${name}' resolves to the SINGULAR cds-typer class — ` +
138
+ `READ handlers registered with it never match under cds 10. Destructure the ` +
139
+ `plural entity-set class instead (e.g. '${name}_ as ${name}').`);
140
+ }
141
+ }
71
142
  // Helper: shorthand for indexer access
72
143
  const indexer = () => (0, server_1.getCardanoIndexer)();
73
144
  // ---------------------------------------------------------------------------
@@ -1,12 +1,2 @@
1
- import type { JSONValue } from './utils/types';
2
- export interface ParsedExtraOutput {
3
- address: string;
4
- lovelaceAmount: string;
5
- assets?: Array<{
6
- unit: string;
7
- quantity: string;
8
- }>;
9
- inlineDatum?: JSONValue;
10
- referenceScript?: string;
11
- }
1
+ export {};
12
2
  //# sourceMappingURL=cardano-tx-service.d.ts.map
@@ -13,161 +13,10 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
13
13
  const mappers_1 = require("./utils/mappers");
14
14
  const server_1 = require("./server");
15
15
  const const_1 = require("./utils/const");
16
+ const tx_request_parsers_1 = require("./utils/tx-request-parsers");
16
17
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
17
18
  const { SELECT, UPDATE } = cds_1.default.ql;
18
19
  const logger = cds_1.default.log('CardanoTxService');
19
- /**
20
- * Parse and validate a JSON array of UTxO refs ({txHash, outputIndex}) — the shared
21
- * shape of forceInputsJson and referenceInputsJson (CIP-31). Returns { parsed } on
22
- * success (undefined for absent/empty input → treated as no-op) or { error } on
23
- * validation failure. Error messages reference the entry name derived from fieldName.
24
- */
25
- function parseUtxoRefArray(json, fieldName) {
26
- if (!json)
27
- return { parsed: undefined };
28
- const entryName = fieldName.replace(/Json$/, '');
29
- const jsonResult = (0, validators_1.validateJsonWithLimits)(json, fieldName);
30
- if (!jsonResult.valid)
31
- return { error: jsonResult.error };
32
- if (!Array.isArray(jsonResult.parsed))
33
- return { error: `${fieldName} must be a JSON array` };
34
- if (jsonResult.parsed.length === 0)
35
- return { parsed: undefined };
36
- const refs = [];
37
- for (const rawEntry of jsonResult.parsed) {
38
- if (!rawEntry || typeof rawEntry !== 'object') {
39
- return { error: `Each ${entryName} entry must be an object with txHash and outputIndex` };
40
- }
41
- const entry = rawEntry;
42
- if (typeof entry.txHash !== 'string' || !(0, validators_1.isTxHash)(entry.txHash)) {
43
- return { error: `Each ${entryName} entry must have a valid 64-hex txHash` };
44
- }
45
- const idx = entry.outputIndex;
46
- if (typeof idx !== 'number' || !Number.isInteger(idx) || idx < 0) {
47
- return { error: `Each ${entryName} entry must have a non-negative integer outputIndex` };
48
- }
49
- refs.push({ txHash: entry.txHash, outputIndex: idx });
50
- }
51
- return { parsed: refs };
52
- }
53
- /**
54
- * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
55
- * Same result contract as the other parse* helpers.
56
- */
57
- function parseRequiredSigners(requiredSignersJson) {
58
- if (!requiredSignersJson)
59
- return { parsed: undefined };
60
- const jsonResult = (0, validators_1.validateJsonWithLimits)(requiredSignersJson, 'requiredSignersJson');
61
- if (!jsonResult.valid)
62
- return { error: jsonResult.error };
63
- try {
64
- return { parsed: (0, validators_1.validateRequiredSigners)(jsonResult.parsed) };
65
- }
66
- catch (err) {
67
- return { error: err instanceof Error ? err.message : String(err) };
68
- }
69
- }
70
- /**
71
- * Parse and validate an assetsJson array ({unit, quantity} entries) with the same
72
- * per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
73
- * into the builder and surfaced as 500s.
74
- */
75
- function parseAssetsArray(assetsJson, fieldName) {
76
- if (!assetsJson)
77
- return { parsed: undefined };
78
- const jsonResult = (0, validators_1.validateJsonWithLimits)(assetsJson, fieldName);
79
- if (!jsonResult.valid)
80
- return { error: jsonResult.error };
81
- if (!Array.isArray(jsonResult.parsed))
82
- return { error: `${fieldName} must be a JSON array` };
83
- const out = [];
84
- for (let i = 0; i < jsonResult.parsed.length; i++) {
85
- const a = jsonResult.parsed[i];
86
- if (!a || typeof a !== 'object') {
87
- return { error: `${fieldName}[${i}] must be an object` };
88
- }
89
- if (typeof a.unit !== 'string' || a.unit.toLowerCase() === 'lovelace' || !(0, validators_1.isAssetUnit)(a.unit)) {
90
- return { error: `${fieldName}[${i}].unit must be a valid asset unit (policyId + assetName hex)` };
91
- }
92
- if (typeof a.quantity !== 'string' || !/^\d+$/.test(a.quantity) || a.quantity === '0') {
93
- return { error: `${fieldName}[${i}].quantity must be a positive integer string` };
94
- }
95
- out.push({ unit: a.unit, quantity: a.quantity });
96
- }
97
- return { parsed: out };
98
- }
99
- /** Upper bound on extra outputs per transaction (defence against tx-size blow-up). */
100
- const MAX_EXTRA_OUTPUTS = 32;
101
- /**
102
- * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
103
- * for empty array → no-op) or { error } on validation failure.
104
- */
105
- function parseExtraOutputs(extraOutputsJson) {
106
- if (!extraOutputsJson)
107
- return { parsed: undefined };
108
- const jsonResult = (0, validators_1.validateJsonWithLimits)(extraOutputsJson, 'extraOutputsJson');
109
- if (!jsonResult.valid)
110
- return { error: jsonResult.error };
111
- if (!Array.isArray(jsonResult.parsed))
112
- return { error: 'extraOutputsJson must be a JSON array' };
113
- if (jsonResult.parsed.length === 0)
114
- return { parsed: undefined };
115
- if (jsonResult.parsed.length > MAX_EXTRA_OUTPUTS) {
116
- return { error: `extraOutputsJson exceeds maximum of ${MAX_EXTRA_OUTPUTS} entries` };
117
- }
118
- const out = [];
119
- for (let i = 0; i < jsonResult.parsed.length; i++) {
120
- const entry = jsonResult.parsed[i];
121
- if (!entry || typeof entry !== 'object') {
122
- return { error: `extraOutputs[${i}] must be an object` };
123
- }
124
- if (typeof entry.address !== 'string' || !(0, validators_1.isValidBech32Address)(entry.address)) {
125
- return { error: `extraOutputs[${i}].address is not a valid Bech32 address` };
126
- }
127
- if (typeof entry.lovelaceAmount !== 'string' || !/^\d+$/.test(entry.lovelaceAmount) || entry.lovelaceAmount === '0') {
128
- return { error: `extraOutputs[${i}].lovelaceAmount must be a positive integer string` };
129
- }
130
- let assets;
131
- if (entry.assets !== undefined && entry.assets !== null) {
132
- if (!Array.isArray(entry.assets)) {
133
- return { error: `extraOutputs[${i}].assets must be an array` };
134
- }
135
- assets = [];
136
- for (let j = 0; j < entry.assets.length; j++) {
137
- const a = entry.assets[j];
138
- if (!a || typeof a !== 'object') {
139
- return { error: `extraOutputs[${i}].assets[${j}] must be an object` };
140
- }
141
- if (typeof a.unit !== 'string' || a.unit.toLowerCase() === 'lovelace' || !(0, validators_1.isAssetUnit)(a.unit)) {
142
- return { error: `extraOutputs[${i}].assets[${j}].unit must be a valid asset unit (policyId + assetName hex)` };
143
- }
144
- if (typeof a.quantity !== 'string' || !/^\d+$/.test(a.quantity) || a.quantity === '0') {
145
- return { error: `extraOutputs[${i}].assets[${j}].quantity must be a positive integer string` };
146
- }
147
- assets.push({ unit: a.unit, quantity: a.quantity });
148
- }
149
- }
150
- let inlineDatum;
151
- if (entry.inlineDatumJson !== undefined && entry.inlineDatumJson !== null) {
152
- if (typeof entry.inlineDatumJson !== 'string') {
153
- return { error: `extraOutputs[${i}].inlineDatumJson must be a JSON string` };
154
- }
155
- const datumResult = (0, validators_1.validateJsonWithLimits)(entry.inlineDatumJson, `extraOutputs[${i}].inlineDatumJson`);
156
- if (!datumResult.valid)
157
- return { error: datumResult.error };
158
- inlineDatum = datumResult.parsed;
159
- }
160
- let referenceScript;
161
- if (entry.referenceScriptHex !== undefined && entry.referenceScriptHex !== null) {
162
- if (typeof entry.referenceScriptHex !== 'string' || !(0, validators_1.isValidCbor)(entry.referenceScriptHex)) {
163
- return { error: `extraOutputs[${i}].referenceScriptHex must be even-length hex` };
164
- }
165
- referenceScript = entry.referenceScriptHex;
166
- }
167
- out.push({ address: entry.address, lovelaceAmount: entry.lovelaceAmount, assets, inlineDatum, referenceScript });
168
- }
169
- return { parsed: out };
170
- }
171
20
  /**
172
21
  * Cardano Transaction Service Implementation
173
22
  * Handles transaction building and submission operations & some additional data queries.
@@ -191,7 +40,7 @@ module.exports = (srv) => {
191
40
  // parse optional output datum
192
41
  const cleanData = { ...req.data };
193
42
  // parse optional forceInputsJson
194
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
43
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
195
44
  if (forceInputsResult.error)
196
45
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', forceInputsResult.error, 'forceInputsJson');
197
46
  cleanData.forceInputs = forceInputsResult.parsed;
@@ -204,7 +53,7 @@ module.exports = (srv) => {
204
53
  delete cleanData.outputDatumJson;
205
54
  }
206
55
  // parse optional assets JSON (for locking native assets at script addresses)
207
- const assetsResult = parseAssetsArray(assetsJson, 'assetsJson');
56
+ const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
208
57
  if (assetsResult.error)
209
58
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', assetsResult.error, 'assetsJson');
210
59
  if (assetsResult.parsed) {
@@ -301,7 +150,7 @@ module.exports = (srv) => {
301
150
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'Invalid changeAddress format', 'changeAddress');
302
151
  }
303
152
  // Parse and validate assetsJson entries (unit + quantity, like parseExtraOutputs)
304
- const assetsResult = parseAssetsArray(assetsJson, 'assetsJson');
153
+ const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
305
154
  if (assetsResult.error)
306
155
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', assetsResult.error, 'assetsJson');
307
156
  const parsedAssets = assetsResult.parsed;
@@ -379,7 +228,7 @@ module.exports = (srv) => {
379
228
  }
380
229
  });
381
230
  // Parse and validate optional requiredSignersJson
382
- const requiredSignersResult = parseRequiredSigners(requiredSignersJson);
231
+ const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
383
232
  if (requiredSignersResult.error)
384
233
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', requiredSignersResult.error, 'requiredSignersJson');
385
234
  const requiredSigners = requiredSignersResult.parsed;
@@ -415,12 +264,12 @@ module.exports = (srv) => {
415
264
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
416
265
  }
417
266
  // Parse and validate optional forceInputsJson
418
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
267
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
419
268
  if (forceInputsResult.error)
420
269
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', forceInputsResult.error, 'forceInputsJson');
421
270
  const forceInputs = forceInputsResult.parsed;
422
271
  // Parse and validate optional referenceInputsJson (CIP-31)
423
- const refInputsResult = parseUtxoRefArray(referenceInputsJson, 'referenceInputsJson');
272
+ const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
424
273
  if (refInputsResult.error)
425
274
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', refInputsResult.error, 'referenceInputsJson');
426
275
  const referenceInputs = refInputsResult.parsed;
@@ -568,7 +417,7 @@ module.exports = (srv) => {
568
417
  // Parse optional datum JSON
569
418
  const parsedDatum = datumJson ? JSON.parse(datumJson) : undefined;
570
419
  // Parse and validate optional requiredSignersJson
571
- const requiredSignersResult = parseRequiredSigners(requiredSignersJson);
420
+ const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
572
421
  if (requiredSignersResult.error)
573
422
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', requiredSignersResult.error, 'requiredSignersJson');
574
423
  const requiredSigners = requiredSignersResult.parsed;
@@ -596,17 +445,17 @@ module.exports = (srv) => {
596
445
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
597
446
  }
598
447
  // Parse and validate optional forceInputsJson
599
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
448
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
600
449
  if (forceInputsResult.error)
601
450
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', forceInputsResult.error, 'forceInputsJson');
602
451
  const forceInputs = forceInputsResult.parsed;
603
452
  // Parse and validate optional referenceInputsJson (CIP-31)
604
- const refInputsResult = parseUtxoRefArray(referenceInputsJson, 'referenceInputsJson');
453
+ const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
605
454
  if (refInputsResult.error)
606
455
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', refInputsResult.error, 'referenceInputsJson');
607
456
  const referenceInputs = refInputsResult.parsed;
608
457
  // Parse and validate optional extraOutputsJson
609
- const extraOutputsResult = parseExtraOutputs(extraOutputsJson);
458
+ const extraOutputsResult = (0, tx_request_parsers_1.parseExtraOutputs)(extraOutputsJson);
610
459
  if (extraOutputsResult.error)
611
460
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', extraOutputsResult.error, 'extraOutputsJson');
612
461
  const extraOutputs = extraOutputsResult.parsed;
@@ -0,0 +1,125 @@
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Wallet Worker Service (v2.0)
5
+ *
6
+ * Control + observability surface for the wallet worker / job engine:
7
+ * - job submission (async build → sign → submit → confirm from server-side wallets)
8
+ * - job status polling + cancellation
9
+ * - read-only projections of jobs and registered worker wallets
10
+ * - pause/resume of the local worker instance (admin)
11
+ *
12
+ * Security note: SubmitWalletJob executes value transfers with server-held keys —
13
+ * the service requires authentication throughout; control actions and foreign-job
14
+ * visibility are gated behind the Admin role. Jobs on HSM-backed wallets addition-
15
+ * ally require the configured hsm.requiresRole (HSM_REQUIRES_ROLE), the same gate
16
+ * the synchronous SignWithHsm path enforces. Keys are NEVER accepted or exposed
17
+ * through this surface.
18
+ */
19
+ @requires: 'authenticated-user'
20
+ service CardanoWorkerService @(impl: './cardano-worker-service') {
21
+
22
+ @readonly
23
+ @title : 'Wallet Jobs'
24
+ @description: 'Asynchronous wallet-worker jobs. Non-admin callers see their own jobs only.'
25
+ @restrict : [
26
+ { grant: 'READ', to: 'Admin' },
27
+ { grant: 'READ', where: 'createdBy = $user' }
28
+ ]
29
+ // dedupKey is the internal backing column of the idempotency constraint.
30
+ entity WalletJobs as projection on db.CardanoWalletJobs excluding { dedupKey };
31
+
32
+ @readonly
33
+ @title : 'Worker Wallets'
34
+ @description: 'Registered server-side worker wallets (addresses and stats only — no key material, no lease internals)'
35
+ entity WorkerWallets as projection on db.CardanoWorkerWallets excluding { leaseOwner, leaseUntil };
36
+
37
+ @title : 'Wallet Job Submission Result'
38
+ type JobSubmissionResult {
39
+ jobId : UUID;
40
+ status : String(12);
41
+ deduplicated : Boolean;
42
+ }
43
+
44
+ @title : 'Wallet Job Status'
45
+ type JobStatus {
46
+ jobId : UUID;
47
+ walletId : String(50);
48
+ kind : String(12);
49
+ status : String(12);
50
+ attempt : Integer;
51
+ txHash : String(64);
52
+ fee : String;
53
+ errorCode : String(50);
54
+ errorMessage : String(500);
55
+ submittedAt : Timestamp;
56
+ confirmedAt : Timestamp;
57
+ finishedAt : Timestamp;
58
+ }
59
+
60
+ @title : 'Worker Status'
61
+ type WorkerStatus {
62
+ running : Boolean;
63
+ wallets : many String;
64
+ executing : many String;
65
+ awaitingConfirmation : Integer;
66
+ pendingJobs : Integer;
67
+ }
68
+
69
+ /**
70
+ * Terminal job outcomes. Subscribing removes the need for a GetJobStatus poll loop:
71
+ * (await cds.connect.to('CardanoWorkerService')).on('jobConfirmed', ({ data }) => …)
72
+ */
73
+ event jobConfirmed {
74
+ jobId : UUID;
75
+ walletId : String(50);
76
+ kind : String(12);
77
+ txHash : String(64);
78
+ }
79
+
80
+ event jobFailed {
81
+ jobId : UUID;
82
+ walletId : String(50);
83
+ kind : String(12);
84
+ txHash : String(64); // null when the job never reached the chain
85
+ errorCode : String(50);
86
+ errorMessage : String(500);
87
+ }
88
+
89
+ @title : 'Submit Wallet Job'
90
+ @description: 'Queue an asynchronous transaction job for a worker wallet. Returns immediately with a jobId; poll GetJobStatus for the outcome. The request JSON is the same payload shape as the corresponding Build* action; senderAddress is always overridden with the wallet address.'
91
+ action SubmitWalletJob(
92
+ @title: 'Wallet Id' walletId : String(50),
93
+ @title: 'Job Kind' kind : String(12),
94
+ @title: 'Request JSON' requestJson : LargeString,
95
+ @title: 'Idempotency Key' idempotencyKey : String(100),
96
+ @title: 'Priority' priority : Integer,
97
+ @title: 'Not Before' notBefore : Timestamp
98
+ ) returns JobSubmissionResult;
99
+
100
+ @title : 'Cancel Job'
101
+ @description: 'Cancel a still-pending job. Jobs that started building may already reach the chain and cannot be cancelled.'
102
+ action CancelJob(
103
+ @title: 'Job Id' jobId : UUID
104
+ ) returns Boolean;
105
+
106
+ @title : 'Get Job Status'
107
+ @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only)'
108
+ function GetJobStatus(
109
+ @title: 'Job Id' jobId : UUID
110
+ ) returns JobStatus;
111
+
112
+ @title : 'Get Worker Status'
113
+ @description: 'Live worker summary: running state, wallets, in-flight executions, confirmation backlog, queue depth'
114
+ function GetWorkerStatus() returns WorkerStatus;
115
+
116
+ @title : 'Pause Worker'
117
+ @description: 'Stop the local worker instance (finishes in-flight steps; queued jobs stay pending).'
118
+ @requires : 'Admin'
119
+ action PauseWorker() returns Boolean;
120
+
121
+ @title : 'Resume Worker'
122
+ @description: 'Start/restart the local worker instance using the configured wallets.'
123
+ @requires : 'Admin'
124
+ action ResumeWorker() returns Boolean;
125
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-worker-service.d.ts.map