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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +6 -12
  2. package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
  3. package/@cds-models/CardanoIndexerService/index.js +24 -0
  4. package/@cds-models/CardanoODataService/index.d.ts +49 -6
  5. package/@cds-models/CardanoODataService/index.js +4 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -3
  7. package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
  8. package/@cds-models/index.d.ts +9 -1
  9. package/@cds-models/index.js +2 -1
  10. package/@cds-models/odatano/cardano/index.d.ts +59 -5
  11. package/@cds-models/odatano/cardano/index.js +6 -0
  12. package/README.md +29 -17
  13. package/db/schema.cds +117 -24
  14. package/db/types.cds +8 -0
  15. package/package.json +17 -15
  16. package/scripts/migrate-schema.mjs +334 -0
  17. package/src/index.d.ts +7 -5
  18. package/src/index.js +12 -10
  19. package/src/plugin.js +6 -7
  20. package/srv/blockchain/backends/blockfrost-backend.js +9 -1
  21. package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
  22. package/srv/blockchain/backends/cardano-backend.js +5 -0
  23. package/srv/blockchain/backends/koios-backend.js +16 -10
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
  25. package/srv/blockchain/backends/ogmios-backend.js +60 -18
  26. package/srv/blockchain/cardano-client.d.ts +5 -4
  27. package/srv/blockchain/cardano-client.js +46 -13
  28. package/srv/blockchain/cardano-indexer.d.ts +116 -9
  29. package/srv/blockchain/cardano-indexer.js +436 -189
  30. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  31. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  32. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
  33. package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
  34. package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
  35. package/srv/blockchain/crawler/certificate-backfill.js +10 -3
  36. package/srv/blockchain/crawler/crawler.d.ts +15 -0
  37. package/srv/blockchain/crawler/crawler.js +68 -3
  38. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  39. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  40. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  41. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  42. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  43. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  44. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  45. package/srv/blockchain/crawler/transaction-backfill.js +12 -8
  46. package/srv/blockchain/pool-metadata.d.ts +15 -0
  47. package/srv/blockchain/pool-metadata.js +132 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
  49. package/srv/blockchain/signing/cose-verifier.js +144 -56
  50. package/srv/blockchain/signing/hsm-signer.js +2 -1
  51. package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
  52. package/srv/blockchain/signing/submission-finalizer.js +201 -69
  53. package/srv/blockchain/stored-chain.js +1 -1
  54. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
  55. package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
  56. package/srv/blockchain/transaction-presence.d.ts +5 -0
  57. package/srv/blockchain/transaction-presence.js +29 -0
  58. package/srv/blockchain/transaction-rows.js +1 -1
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
  60. package/srv/blockchain/wallet-worker/build-request.js +25 -0
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
  62. package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
  63. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  64. package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
  67. package/srv/cardano-agent-service.cds +11 -12
  68. package/srv/cardano-agent-service.js +2 -0
  69. package/srv/cardano-backend-service.cds +34 -1
  70. package/srv/cardano-backend-service.js +20 -17
  71. package/srv/cardano-indexer-service.cds +153 -12
  72. package/srv/cardano-indexer-service.js +175 -29
  73. package/srv/cardano-service.cds +67 -3
  74. package/srv/cardano-service.js +132 -67
  75. package/srv/cardano-sign-service.cds +30 -20
  76. package/srv/cardano-sign-service.js +13 -10
  77. package/srv/cardano-tx-service.cds +15 -1
  78. package/srv/cardano-tx-service.js +4 -1
  79. package/srv/cardano-worker-service.cds +16 -7
  80. package/srv/cardano-worker-service.js +31 -22
  81. package/srv/cbor/parse.js +11 -34
  82. package/srv/config.d.ts +113 -0
  83. package/srv/config.js +409 -0
  84. package/srv/server.d.ts +9 -14
  85. package/srv/server.js +32 -316
  86. package/srv/utils/agent-access.d.ts +9 -0
  87. package/srv/utils/agent-access.js +67 -0
  88. package/srv/utils/agent-grants-config.d.ts +0 -17
  89. package/srv/utils/agent-grants-config.js +6 -81
  90. package/srv/utils/agent-grants.d.ts +6 -19
  91. package/srv/utils/agent-grants.js +69 -130
  92. package/srv/utils/const.d.ts +4 -0
  93. package/srv/utils/const.js +5 -1
  94. package/srv/utils/db-indexes.js +11 -3
  95. package/srv/utils/error-codes.d.ts +4 -0
  96. package/srv/utils/error-codes.js +4 -0
  97. package/srv/utils/errors.d.ts +6 -0
  98. package/srv/utils/errors.js +23 -1
  99. package/srv/utils/liveness.js +2 -5
  100. package/srv/utils/mappers.d.ts +5 -7
  101. package/srv/utils/mappers.js +22 -9
  102. package/srv/utils/pg-order-nulls.js +4 -3
  103. package/srv/utils/readiness.d.ts +12 -0
  104. package/srv/utils/readiness.js +29 -0
  105. package/srv/utils/result-numbers.d.ts +15 -0
  106. package/srv/utils/result-numbers.js +61 -0
  107. package/srv/utils/tx-request-parsers.d.ts +1 -1
  108. package/srv/utils/tx-request-parsers.js +3 -3
  109. package/srv/utils/tx-utils.d.ts +3 -0
  110. package/srv/utils/tx-utils.js +17 -3
  111. package/srv/utils/types.d.ts +16 -3
  112. package/scripts/migrate-txseq.mjs +0 -138
  113. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
  114. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
  115. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
  116. package/srv/blockchain/transaction-building/caller-datums.js +0 -133
  117. package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
  118. package/srv/cbor/redeemer-tag-patch.js +0 -61
  119. package/srv/utils/legacy-service-paths.d.ts +0 -11
  120. package/srv/utils/legacy-service-paths.js +0 -58
@@ -7,7 +7,7 @@ using {
7
7
 
8
8
 
9
9
  // Transaction building and submission, separate from the read service.
10
- @requires: 'authenticated-user'
10
+ @requires: 'Transact'
11
11
  service CardanoTransactionService @(impl: './cardano-tx-service') {
12
12
  // ---------------------------------------------------------------------------
13
13
  // Entity Projections - Transaction Building & Submission
@@ -50,6 +50,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
50
50
  actions {
51
51
  @title : 'Check Submission Status'
52
52
  @description: 'Mark a submitted transaction confirmed once it is 3 blocks deep (its own block included); otherwise it stays submitted'
53
+ @odatano.agent: 'grant'
53
54
  action CheckSubmissionStatus() returns TransactionSubmissions;
54
55
  };
55
56
 
@@ -75,6 +76,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
75
76
 
76
77
  @title : 'Build Simple ADA Transaction'
77
78
  @description: 'Build a simple ADA transfer transaction from sender to recipient with specified amount and change address'
79
+ @odatano.agent: 'grant'
78
80
  action BuildSimpleAdaTransaction(
79
81
  @title: 'Sender Address'
80
82
  @description: 'The Bech32 encoded address of the sender'
@@ -127,6 +129,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
127
129
 
128
130
  @title : 'Build Transaction with Metadata'
129
131
  @description: 'Build a transaction with custom metadata from sender to recipient with specified amount and change address'
132
+ @odatano.agent: 'grant'
130
133
  action BuildTransactionWithMetadata(
131
134
  @title: 'Sender Address'
132
135
  @description: 'The Bech32 encoded address of the sender'
@@ -146,6 +149,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
146
149
 
147
150
  @title : 'Build Multi-Asset Transaction'
148
151
  @description: 'Build a transaction to send native assets (tokens) along with ADA'
152
+ @odatano.agent: 'grant'
149
153
  action BuildMultiAssetTransaction(
150
154
  @title: 'Sender Address'
151
155
  @description: 'The Bech32 encoded address of the sender'
@@ -183,6 +187,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
183
187
 
184
188
  @title : 'Build Minting Transaction'
185
189
  @description: 'Build a transaction to mint or burn native assets'
190
+ @odatano.agent: 'grant'
186
191
  action BuildMintTransaction(
187
192
  @title: 'Sender Address'
188
193
  @description: 'The Bech32 encoded address of the sender (pays fees)'
@@ -244,6 +249,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
244
249
 
245
250
  @title : 'Get Build Details'
246
251
  @description: 'Retrieve transaction build details using the Build Id'
252
+ @odatano.agent: 'read'
247
253
  action GetBuildDetails(
248
254
  @title: 'Build Id'
249
255
  @description: 'The unique identifier of the transaction build'
@@ -251,6 +257,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
251
257
 
252
258
  @title : 'Submit Transaction'
253
259
  @description: 'Submit a transaction to the Cardano network using a build ID and signed CBOR'
260
+ @odatano.agent: 'grant'
254
261
  action SubmitTransaction(
255
262
  @title: 'Build Id'
256
263
  @description: 'The unique identifier of the transaction build'
@@ -261,6 +268,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
261
268
 
262
269
  @title : 'Submit Signed Transaction'
263
270
  @description: 'Submit a signed transaction to the Cardano network'
271
+ @odatano.agent: 'grant'
264
272
  action SubmitSignedTransaction(
265
273
  @title: 'Signed Transaction CBOR'
266
274
  @description: 'The CBOR of the signed transaction'
@@ -272,6 +280,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
272
280
 
273
281
  @title : 'Build Plutus Spend Transaction'
274
282
  @description: 'Build a transaction to spend a UTxO locked at a Plutus script address'
283
+ @odatano.agent: 'grant'
275
284
  action BuildPlutusSpendTransaction(
276
285
  @title: 'Sender Address'
277
286
  @description: 'The Bech32 encoded address of the sender (pays fees)'
@@ -345,6 +354,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
345
354
 
346
355
  @title : 'Build Plutus Transaction'
347
356
  @description: 'Spend script UTxOs, each with its own redeemer (inline validator or a reference-script UTxO), mint, withdraw and certify in one transaction; script inputs are optional, so a mint or a withdraw-zero alone works. Collateral is added only when a script runs. The outputs are built exactly in the given order, change comes after them. The execution units of every redeemer are returned under redeemers.'
357
+ @odatano.agent: 'grant'
348
358
  action BuildPlutusTransaction(
349
359
  @title: 'Sender Address'
350
360
  @description: 'Pays the fee, funds the rest and provides the ADA-only collateral'
@@ -388,6 +398,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
388
398
 
389
399
  @title : 'Set Collateral'
390
400
  @description: 'Ensure a dedicated ADA-only collateral UTxO exists for Plutus transactions. Checks if the address has at least 2 UTxOs with >= 5 ADA each. If not, builds a self-send transaction to create a 5 ADA collateral UTxO.'
401
+ @odatano.agent: 'grant'
391
402
  action SetCollateral(
392
403
  @title: 'Address'
393
404
  @description: 'The Bech32 encoded address to check and set up collateral for'
@@ -395,6 +406,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
395
406
 
396
407
  @title : 'Address Transaction Builds'
397
408
  @description: 'Projection for retrieving transaction builds by address'
409
+ @odatano.agent: 'read'
398
410
  action GetTransactionBuildsByAddress(
399
411
  @title: 'Bech32 Address'
400
412
  @description: 'The Bech32 encoded address to retrieve transaction builds for'
@@ -410,6 +422,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
410
422
 
411
423
  @title : 'Derive Script Address'
412
424
  @description: 'Utility: Apply optional PlutusData parameters to a validator script and return its enterprise script address (bech32) and script hash (28-byte hex). Pure derivation, no transaction built, no blockchain call.'
425
+ @odatano.agent: 'read'
413
426
  action DeriveScriptAddress(
414
427
  @title: 'Validator Script'
415
428
  @description: 'The Plutus validator script in CBOR hex format'
@@ -427,6 +440,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
427
440
 
428
441
  @title : 'Extract Payment Key Hash'
429
442
  @description: 'Utility: Decode a Bech32 Cardano address and return its 28-byte payment credential hash (hex). Pure bech32 decoding, no blockchain call. Use to obtain the key hash for requiredSignersJson on Plutus actions.'
443
+ @odatano.agent: 'read'
430
444
  action ExtractPaymentKeyHash(
431
445
  @title: 'Address'
432
446
  @description: 'The Bech32 encoded Cardano address (addr / addr_test)'
@@ -18,6 +18,7 @@ const paging_1 = require("./utils/paging");
18
18
  const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
19
19
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
20
20
  const const_1 = require("./utils/const");
21
+ const result_numbers_1 = require("./utils/result-numbers");
21
22
  const tx_request_parsers_1 = require("./utils/tx-request-parsers");
22
23
  const { SELECT, UPDATE } = cds_1.default.ql;
23
24
  /** Blocks on top of a submitted transaction, its own included, before CheckSubmissionStatus confirms it. */
@@ -25,6 +26,7 @@ const SUBMISSION_CONFIRMATION_DEPTH = 3;
25
26
  const logger = cds_1.default.log('CardanoTxService');
26
27
  /** CardanoTransactionService handlers: transaction building, submission and script helpers. */
27
28
  module.exports = (srv) => {
29
+ (0, result_numbers_1.answerNumbersAsText)(srv);
28
30
  logger.debug('Module loaded - registering handlers');
29
31
  const { TransactionBuilds, TransactionSubmissions, AddressTransactionBuilds } = require('#cds-models/CardanoTransactionService');
30
32
  // BuildSimpleAdaTransaction: ADA (optionally with assets / datum) to one recipient or a script.
@@ -878,7 +880,8 @@ module.exports = (srv) => {
878
880
  logger.debug('CheckSubmissionStatus Action handler called');
879
881
  const { id: submissionId } = req.params[0];
880
882
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
881
- const submission = await db.run(SELECT.one.from(TransactionSubmissions).where({ id: submissionId }));
883
+ // read outside the request transaction: the confirmation lookup below may ask a backend
884
+ const submission = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(TransactionSubmissions).where({ id: submissionId })));
882
885
  if (!submission)
883
886
  throw new errors_1.NotFoundError(`Submission '${submissionId}'`);
884
887
  // a block this deep is not rolled back in practice; a status set here is never reverted
@@ -1,9 +1,11 @@
1
1
  using { WalletJobKind } from '../db/types';
2
2
  using {odatano.cardano as db} from '../db/schema';
3
3
 
4
- // Async wallet jobs signed with server-held keys. Control actions and foreign jobs need Admin;
5
- // jobs on HSM wallets also need hsm.requiresRole. Keys are never accepted or returned here.
6
- @requires: 'authenticated-user'
4
+ // Async wallet jobs signed with server-held keys, which are never accepted or returned here.
5
+ // Control actions and foreign jobs need Admin. A job needs the wallet's requiresRole and, on an
6
+ // HSM wallet, hsm.requiresRole. An agent token gets a 403 on every event of this service.
7
+ @requires: 'Transact'
8
+ @odatano.agent: 'closed'
7
9
  service CardanoWorkerService @(impl: './cardano-worker-service') {
8
10
 
9
11
  @readonly
@@ -53,7 +55,7 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
53
55
  pendingJobs : Integer;
54
56
  }
55
57
 
56
- /** Terminal job outcome. Subscribe instead of polling GetJobStatus. */
58
+ /** Terminal job outcome. Subscribe in process, or wait over HTTP with GetJobStatus(waitMs). */
57
59
  event jobConfirmed {
58
60
  jobId : UUID;
59
61
  walletId : String(50);
@@ -71,7 +73,8 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
71
73
  }
72
74
 
73
75
  @title : 'Submit Wallet Job'
74
- @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.'
76
+ @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. A retry with the same idempotencyKey and request returns the job that holds the key; another request under that key is a 409.'
77
+ @odatano.agent: 'operator'
75
78
  action SubmitWalletJob(
76
79
  @title: 'Wallet Id' walletId : String(50),
77
80
  @title: 'Job Kind' @assert.range kind : WalletJobKind,
@@ -83,27 +86,33 @@ service CardanoWorkerService @(impl: './cardano-worker-service') {
83
86
 
84
87
  @title : 'Cancel Job'
85
88
  @description: 'Cancel a still-pending job. Jobs that started building may already reach the chain and cannot be cancelled.'
89
+ @odatano.agent: 'operator'
86
90
  action CancelJob(
87
91
  @title: 'Job Id' jobId : UUID
88
92
  ) returns Boolean;
89
93
 
90
94
  @title : 'Get Job Status'
91
- @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only)'
95
+ @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only). With waitMs the call answers as soon as the job is confirmed, failed or cancelled, or after that time with the state it has then. Keep waitMs below the timeout of the proxies in front of the service.'
96
+ @odatano.agent: 'operator'
92
97
  function GetJobStatus(
93
- @title: 'Job Id' jobId : UUID
98
+ @title: 'Job Id' jobId : UUID,
99
+ @title: 'Wait (ms)' @assert.range: [0, 30000] waitMs : Integer
94
100
  ) returns JobStatus;
95
101
 
96
102
  @title : 'Get Worker Status'
97
103
  @description: 'Live worker summary: running state, wallets, in-flight executions, confirmation backlog, queue depth'
104
+ @odatano.agent: 'operator'
98
105
  function GetWorkerStatus() returns WorkerStatus;
99
106
 
100
107
  @title : 'Pause Worker'
101
108
  @description: 'Stop the local worker instance (finishes in-flight steps; queued jobs stay pending).'
102
109
  @requires : 'Admin'
110
+ @odatano.agent: 'operator'
103
111
  action PauseWorker() returns Boolean;
104
112
 
105
113
  @title : 'Resume Worker'
106
114
  @description: 'Start/restart the local worker instance using the configured wallets.'
107
115
  @requires : 'Admin'
116
+ @odatano.agent: 'operator'
108
117
  action ResumeWorker() returns Boolean;
109
118
  }
@@ -8,22 +8,22 @@ const backend_request_handler_1 = require("./utils/backend-request-handler");
8
8
  const errors_1 = require("./utils/errors");
9
9
  const error_codes_1 = require("./utils/error-codes");
10
10
  const validators_1 = require("./utils/validators");
11
+ const result_numbers_1 = require("./utils/result-numbers");
11
12
  const wallet_worker_1 = require("./blockchain/wallet-worker");
12
13
  const job_store_1 = require("./blockchain/wallet-worker/job-store");
13
14
  const server_1 = require("./server");
15
+ const config_1 = require("./config");
14
16
  const CardanoWorkerService_1 = require("#cds-models/CardanoWorkerService");
15
17
  const logger = cds_1.default.log('CardanoWorkerService');
18
+ const TERMINAL_JOB_STATUS = new Set(['confirmed', 'failed', 'cancelled']);
19
+ const JOB_WAIT_POLL_MS = 1000;
16
20
  function isAdmin(req) {
17
21
  return req.user?.is?.('Admin') ?? false;
18
22
  }
19
- /** The HSM role a caller lacks for an HSM-backed wallet, the same gate SignWithHsm applies; null when none is missing. */
20
- function missingHsmRole(req, signerType) {
21
- if (signerType !== 'hsm')
22
- return null;
23
- const requiresRole = (0, server_1.getHsmConfig)()?.requiresRole;
24
- if (!requiresRole || req.user?.is(requiresRole))
25
- return null;
26
- return requiresRole;
23
+ /** The first role the caller lacks for this wallet: its own requiresRole, then hsm.requiresRole on an HSM wallet. */
24
+ function missingWalletRole(req, wallet) {
25
+ const roles = [wallet?.requiresRole, wallet?.signerType === 'hsm' ? (0, server_1.getHsmConfig)()?.requiresRole : null];
26
+ return roles.find((role) => role && !req.user?.is(role)) ?? null;
27
27
  }
28
28
  function toJobStatus(job) {
29
29
  return {
@@ -43,6 +43,7 @@ function toJobStatus(job) {
43
43
  }
44
44
  /** CardanoWorkerService handlers: job submission and status, worker control. */
45
45
  module.exports = (srv) => {
46
+ (0, result_numbers_1.answerNumbersAsText)(srv);
46
47
  // SubmitWalletJob: queue an async transaction job; returns the jobId immediately.
47
48
  srv.on(CardanoWorkerService_1.SubmitWalletJob, async (req) => {
48
49
  const { walletId, kind, requestJson, idempotencyKey, priority, notBefore } = req.data;
@@ -64,7 +65,7 @@ module.exports = (srv) => {
64
65
  }
65
66
  let config;
66
67
  try {
67
- config = (0, server_1.loadWalletWorkerConfigFromEnv)();
68
+ config = (0, config_1.loadWalletWorkerConfigFromEnv)();
68
69
  }
69
70
  catch (err) {
70
71
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', err instanceof Error ? err.message : String(err));
@@ -73,9 +74,9 @@ module.exports = (srv) => {
73
74
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'Wallet worker is not enabled: set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) with configured wallets.');
74
75
  }
75
76
  // Role gate on this instance's config, mirroring the sign service's 403.
76
- const configuredRole = missingHsmRole(req, config.wallets.find((w) => w.walletId === walletId)?.signerType);
77
+ const configuredRole = missingWalletRole(req, config.wallets.find((w) => w.walletId === walletId));
77
78
  if (configuredRole) {
78
- return req.reject(403, `SubmitWalletJob on HSM-backed wallet "${walletId}" requires role '${configuredRole}'`);
79
+ return req.reject(403, `SubmitWalletJob on wallet "${walletId}" requires role '${configuredRole}'`);
79
80
  }
80
81
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
81
82
  const wallet = await (0, job_store_1.readWallet)(db, walletId);
@@ -83,10 +84,10 @@ module.exports = (srv) => {
83
84
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Unknown wallet "${walletId}": configured wallets are registered at worker start`, 'walletId');
84
85
  if (!wallet.enabled)
85
86
  return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Wallet "${walletId}" is disabled`, 'walletId');
86
- // Registered row too: another instance may run the HSM wallet this one has no config for.
87
- const registeredRole = missingHsmRole(req, wallet.signerType);
87
+ // Registered row too: another instance may run the wallet this one has no config for.
88
+ const registeredRole = missingWalletRole(req, wallet);
88
89
  if (registeredRole) {
89
- throw new errors_1.BackendError(`Wallet "${walletId}" is HSM-backed and requires role '${registeredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId');
90
+ throw new errors_1.BackendError(`SubmitWalletJob on wallet "${walletId}" requires role '${registeredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId');
90
91
  }
91
92
  const result = await (0, job_store_1.insertJob)(db, {
92
93
  walletId,
@@ -121,17 +122,25 @@ module.exports = (srv) => {
121
122
  return true;
122
123
  });
123
124
  });
124
- // GetJobStatus: scoped to the creator unless Admin.
125
+ // GetJobStatus: scoped to the creator unless Admin. With waitMs it answers once the job is
126
+ // confirmed, failed or cancelled, or when the time is up. Each read has its own transaction,
127
+ // so a waiting request holds no database connection.
125
128
  srv.on(CardanoWorkerService_1.GetJobStatus, async (req) => {
126
- const { jobId } = req.data;
129
+ const { jobId, waitMs } = req.data;
127
130
  if (!jobId)
128
131
  return (0, errors_1.rejectInvalid)(req, 'GetJobStatus', 'jobId is required', 'jobId');
129
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
130
- const job = await (0, job_store_1.getJobById)(db, jobId);
131
- if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
132
- throw new errors_1.NotFoundError(`Job ${jobId}`); // see CancelJob: reject() here becomes a 500
132
+ const deadline = Date.now() + Number(waitMs ?? 0);
133
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
134
+ for (;;) {
135
+ const job = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, jobId)));
136
+ if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
137
+ throw new errors_1.NotFoundError(`Job ${jobId}`); // see CancelJob: reject() here becomes a 500
138
+ }
139
+ const timeUp = Date.now() + JOB_WAIT_POLL_MS > deadline || req.http?.res.destroyed === true;
140
+ if (TERMINAL_JOB_STATUS.has(job.status) || timeUp)
141
+ return toJobStatus(job);
142
+ await new Promise((resolve) => setTimeout(resolve, JOB_WAIT_POLL_MS));
133
143
  }
134
- return toJobStatus(job);
135
144
  });
136
145
  });
137
146
  // GetWorkerStatus: live summary of the local worker instance.
@@ -157,7 +166,7 @@ module.exports = (srv) => {
157
166
  srv.on('ResumeWorker', async (req) => {
158
167
  let config;
159
168
  try {
160
- config = (0, server_1.loadWalletWorkerConfigFromEnv)();
169
+ config = (0, config_1.loadWalletWorkerConfigFromEnv)();
161
170
  }
162
171
  catch (err) {
163
172
  return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', err instanceof Error ? err.message : String(err));
package/srv/cbor/parse.js CHANGED
@@ -6,18 +6,16 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
6
  const cbor_1 = require("@harmoniclabs/cbor");
7
7
  const errors_1 = require("../utils/errors");
8
8
  const error_codes_1 = require("../utils/error-codes");
9
- const redeemer_tag_patch_1 = require("./redeemer-tag-patch");
10
- (0, redeemer_tag_patch_1.installRedeemerTagPatch)();
11
9
  // Pure, no network call. Callers validate size and format with `isValidTxCborHex` first.
12
10
  // Throws TX_PARSE_FAILED on malformed CBOR.
13
11
  function parseTransaction(cborHex) {
14
12
  let tx;
15
- let raw;
13
+ let networkId;
16
14
  try {
17
15
  // one decode for both readers; keepRef keeps the original bytes for the body hash and datums
18
16
  const parsed = cbor_1.Cbor.parse(Buffer.from(cborHex, 'hex'), { keepRef: true });
19
17
  tx = buildooor_1.Tx.fromCborObj(parsed);
20
- raw = readBodyFields(parsed);
18
+ networkId = readNetworkId(parsed);
21
19
  }
22
20
  catch (e) {
23
21
  const msg = e instanceof Error ? e.message : String(e);
@@ -27,7 +25,7 @@ function parseTransaction(cborHex) {
27
25
  return {
28
26
  txHash: body.hash.toString(),
29
27
  network: normalizeNetwork(body.network),
30
- networkId: raw.networkId,
28
+ networkId,
31
29
  inputs: body.inputs.map(mapInput),
32
30
  outputs: body.outputs.map(mapOutput),
33
31
  validityStart: body.validityIntervalStart != null ? body.validityIntervalStart.toString() : null,
@@ -42,10 +40,10 @@ function parseTransaction(cborHex) {
42
40
  lovelace: w.amount.toString(),
43
41
  })),
44
42
  certificates: (body.certs ?? []).map(mapCertificate),
45
- votingProcedures: raw.votingProcedures,
46
- proposalProcedures: raw.proposalProcedures,
47
- treasuryDonation: raw.treasuryDonation,
48
- currentTreasuryValue: raw.currentTreasuryValue,
43
+ votingProcedures: (body.votingProcedures?.procedures ?? []).reduce((n, voter) => n + voter.votes.length, 0),
44
+ proposalProcedures: (body.proposalProcedures ?? []).length,
45
+ treasuryDonation: body.donation?.toString() ?? null,
46
+ currentTreasuryValue: body.currentTreasuryValue?.toString() ?? null,
49
47
  requiredSigners: (body.requiredSigners ?? []).map((s) => s.toString()),
50
48
  scriptDataHash: body.scriptDataHash ? body.scriptDataHash.toString() : null,
51
49
  isValid: tx.isScriptValid,
@@ -101,32 +99,11 @@ function mapOutput(out) {
101
99
  function mapCertificate(cert, index) {
102
100
  return { index, type: (0, cardano_ledger_ts_1.certTypeToString)(cert.certType) };
103
101
  }
104
- /** Body fields 15 and 19 to 22 as they stand in the bytes. `Tx.fromCbor` drops 19 to 22 and maps any network byte other than 0 to mainnet. */
105
- function readBodyFields(parsed) {
102
+ /** Body field 15 as it stands in the bytes. `Tx.fromCbor` maps any network byte other than 0 to mainnet. */
103
+ function readNetworkId(parsed) {
106
104
  const body = parsed instanceof cbor_1.CborArray ? parsed.array[0] : undefined;
107
- const field = (key) => body instanceof cbor_1.CborMap ? body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v : undefined;
108
- const uint = (key) => {
109
- const v = field(key);
110
- return v instanceof cbor_1.CborUInt ? v.num : null;
111
- };
112
- // voting_procedures = { voter => { gov_action_id => voting_procedure } }
113
- const voting = field(19);
114
- const votes = voting instanceof cbor_1.CborMap
115
- ? voting.map.reduce((n, e) => n + (e.v instanceof cbor_1.CborMap ? e.v.map.length : 0), 0)
116
- : 0;
117
- const networkId = uint(15);
118
- return {
119
- networkId: networkId == null ? null : Number(networkId),
120
- votingProcedures: votes,
121
- proposalProcedures: setItems(field(20)).length,
122
- treasuryDonation: uint(22)?.toString() ?? null,
123
- currentTreasuryValue: uint(21)?.toString() ?? null,
124
- };
125
- }
126
- /** Items of a CBOR set, with or without the Conway set tag 258. */
127
- function setItems(obj) {
128
- const inner = obj instanceof cbor_1.CborTag ? obj.data : obj;
129
- return inner instanceof cbor_1.CborArray ? inner.array : [];
105
+ const value = body instanceof cbor_1.CborMap ? body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === 15n)?.v : undefined;
106
+ return value instanceof cbor_1.CborUInt ? Number(value.num) : null;
130
107
  }
131
108
  /** Inline datum bytes as they stand in the transaction; decoding and re-encoding may change them. */
132
109
  function inlineDatumBytes(out) {
@@ -0,0 +1,113 @@
1
+ import type { CardanoClientConfig } from './blockchain/cardano-client';
2
+ import type { CrawlerConfig } from './blockchain/crawler/crawler';
3
+ import type { WalletWorkerConfig } from './blockchain/wallet-worker';
4
+ import type { HsmConfig } from './utils/types';
5
+ /** `cds.requires.odatano-core` as the host app wrote it; nested sections stay raw and are coerced on read. */
6
+ export interface OdatanoCoreCdsConfig {
7
+ network?: string;
8
+ backends?: string[] | string;
9
+ blockfrostApiKey?: string;
10
+ blockfrostCustomBackend?: string;
11
+ koiosApiKey?: string;
12
+ ogmiosUrl?: string;
13
+ odatanoUrl?: string;
14
+ odatanoApiKey?: string;
15
+ primaryTimeoutMs?: number;
16
+ fallbackTimeoutMs?: number;
17
+ indexTtlMs?: number;
18
+ poolMetadataFetch?: CdsBoolean;
19
+ hsm?: HsmCdsSection;
20
+ crawler?: CrawlerCdsSection;
21
+ walletWorker?: WalletWorkerCdsSection;
22
+ agentGrants?: AgentGrantsCdsSection;
23
+ }
24
+ /** Numbers and booleans may arrive as strings; the loaders coerce and validate them. */
25
+ export type CdsNumber = number | string;
26
+ export type CdsBoolean = boolean | string;
27
+ export interface CrawlerCdsSection {
28
+ enabled?: CdsBoolean;
29
+ startSlot?: CdsNumber;
30
+ startHeight?: CdsNumber;
31
+ startBlockHash?: string;
32
+ source?: string;
33
+ batchSize?: CdsNumber;
34
+ confirmationDepth?: CdsNumber;
35
+ pollIntervalMs?: CdsNumber;
36
+ assetHistory?: CdsBoolean;
37
+ assetCatalogue?: string;
38
+ assetEnrichRate?: CdsNumber;
39
+ epochSnapshots?: CdsBoolean;
40
+ accountSnapshots?: CdsBoolean;
41
+ certificates?: CdsBoolean;
42
+ utxoSet?: CdsBoolean;
43
+ authoritative?: CdsBoolean;
44
+ inputAssetCopies?: CdsBoolean;
45
+ }
46
+ export interface WalletWorkerCdsSection {
47
+ enabled?: CdsBoolean;
48
+ wallets?: unknown;
49
+ maxConcurrentWallets?: CdsNumber;
50
+ confirmationDepth?: CdsNumber;
51
+ confirmationTimeoutMs?: CdsNumber;
52
+ pollIntervalMs?: CdsNumber;
53
+ defaultMaxAttempts?: CdsNumber;
54
+ resubmitOnRollback?: CdsBoolean;
55
+ }
56
+ export interface HsmCdsSection {
57
+ enabled?: boolean;
58
+ pkcs11Module?: string;
59
+ slot?: number;
60
+ pin?: string;
61
+ keyId?: string;
62
+ keyLabel?: string;
63
+ requiresRole?: string;
64
+ }
65
+ export interface AgentGrantsCdsSection {
66
+ enabled?: CdsBoolean;
67
+ delegate?: string;
68
+ adminRateLimit?: CdsNumber;
69
+ tokenCacheMs?: CdsNumber;
70
+ usageRetentionDays?: CdsNumber;
71
+ }
72
+ /** The section as configured. Every read of it goes through here. */
73
+ export declare function coreCdsConfig(): OdatanoCoreCdsConfig;
74
+ /** The network as written, unchecked: for probes that answer even when the configuration is invalid. */
75
+ export declare function configuredNetworkName(): string;
76
+ /** SKIP_AUTO_INIT=true: tests mount the services without starting backends, crawler or worker. */
77
+ export declare function autoInitSkipped(): boolean;
78
+ /** ODATANO_DETACHED_TX_TIMEOUT_MS when it is a positive number; read per call. */
79
+ export declare function detachedTxTimeoutMs(): number | undefined;
80
+ /** Blockchain components created once at bootstrap and shared across services. */
81
+ /** Backends and their credentials. Throws ConfigError for an invalid value. */
82
+ export declare function loadConfigFromEnv(): CardanoClientConfig;
83
+ /** `poolMetadataFetch` / POOL_METADATA_FETCH: load pool metadata files from their registered URL. Off by default. */
84
+ export declare function loadPoolMetadataFetchFromEnv(): boolean;
85
+ /** From cds.requires.odatano-core.hsm or HSM_* env vars. Undefined when HSM is off. */
86
+ export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
87
+ /** From cds.requires.odatano-core.crawler or CRAWLER_* env vars. Off by default. */
88
+ export declare function loadCrawlerConfigFromEnv(): CrawlerConfig;
89
+ /** From cds.requires.odatano-core.walletWorker or WALLET_WORKER_* env vars. Off by default. */
90
+ export declare function loadWalletWorkerConfigFromEnv(): WalletWorkerConfig;
91
+ /** Agent grants: `agentGrants` in the section, else AGENT_GRANT* variables. */
92
+ export interface AgentGrantsConfig {
93
+ enabled: boolean;
94
+ /** CAP auth kind the transport middleware delegates to for non-token requests. */
95
+ delegate: string;
96
+ /** Grant administration calls per principal per hour (integer >= 1). */
97
+ adminRateLimit: number;
98
+ }
99
+ export declare const AGENT_GRANTS_DELEGATES: readonly string[];
100
+ export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
101
+ export declare function loadGrantAdminRateLimit(vars?: Record<string, string | undefined>): number;
102
+ export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
103
+ export declare function loadTokenCacheMs(vars?: Record<string, string | undefined>): number;
104
+ export declare const AGENT_GRANT_USAGE_RETENTION_DAYS_DEFAULT = 400;
105
+ export declare function loadGrantUsageRetentionDays(vars?: Record<string, string | undefined>): number;
106
+ /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
107
+ export declare function configuredAuth(): Record<string, unknown>;
108
+ /** The transport middleware, recognisable in `auth.impl` so activation stays idempotent. */
109
+ export declare const AGENT_AUTH_IMPL = "cap-auth";
110
+ /** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
111
+ export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
112
+ export declare function loadAgentGrantsConfig(vars?: Record<string, string | undefined>): AgentGrantsConfig;
113
+ //# sourceMappingURL=config.d.ts.map