@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51
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.
- package/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +358 -0
- package/@cds-models/CardanoBackendService/index.js +41 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
- package/@cds-models/CardanoIndexerService/index.js +74 -0
- package/@cds-models/CardanoODataService/index.d.ts +417 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +45 -19
- package/@cds-models/CardanoSignService/index.js +4 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
- package/@cds-models/CardanoTransactionService/index.js +5 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +114 -4
- package/@cds-models/index.js +20 -4
- package/@cds-models/odatano/cardano/index.d.ts +451 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +103 -167
- package/db/schema.cds +2455 -1705
- package/db/types.cds +456 -295
- package/package.json +41 -53
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +528 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
- package/srv/blockchain/backends/blockfrost-backend.js +125 -215
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +108 -170
- package/srv/blockchain/backends/koios-backend.js +488 -482
- package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
- package/srv/blockchain/backends/odatano-backend.js +211 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
- package/srv/blockchain/backends/ogmios-backend.js +683 -327
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +71 -241
- package/srv/blockchain/cardano-client.js +354 -322
- package/srv/blockchain/cardano-indexer.d.ts +295 -283
- package/srv/blockchain/cardano-indexer.js +1690 -502
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +2 -13
- package/srv/blockchain/circuit-breaker.js +11 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +173 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
- package/srv/blockchain/crawler/certificate-backfill.js +174 -0
- package/srv/blockchain/crawler/crawler.d.ts +125 -81
- package/srv/blockchain/crawler/crawler.js +738 -167
- package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
- package/srv/blockchain/crawler/credential-backfill.js +101 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +161 -0
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
- package/srv/blockchain/crawler/sync-state.d.ts +31 -47
- package/srv/blockchain/crawler/sync-state.js +135 -128
- package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/transaction-backfill.js +271 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +521 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +22 -131
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +71 -87
- package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
- package/srv/blockchain/signing/submission-finalizer.js +280 -86
- package/srv/blockchain/stored-chain.d.ts +19 -0
- package/srv/blockchain/stored-chain.js +258 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +12 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
- package/srv/blockchain/wallet-worker/build-request.js +40 -353
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
- package/srv/blockchain/wallet-worker/job-store.js +200 -273
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
- package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +12 -9
- package/srv/cardano-backend-service.cds +81 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +259 -0
- package/srv/cardano-indexer-service.cds +393 -18
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +477 -16
- package/srv/cardano-service.cds +426 -269
- package/srv/cardano-service.js +640 -217
- package/srv/cardano-sign-service.cds +211 -180
- package/srv/cardano-sign-service.js +210 -287
- package/srv/cardano-tx-service.cds +462 -370
- package/srv/cardano-tx-service.js +283 -800
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +141 -125
- package/srv/cardano-worker-service.js +104 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +117 -0
- package/srv/config.js +419 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +83 -405
- package/srv/utils/agent-access.d.ts +11 -0
- package/srv/utils/agent-access.js +86 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -237
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +62 -186
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +4 -10
- package/srv/utils/collections.js +14 -10
- package/srv/utils/const.d.ts +32 -75
- package/srv/utils/const.js +40 -80
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +11 -25
- package/srv/utils/db-indexes.d.ts +31 -0
- package/srv/utils/db-indexes.js +185 -0
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +14 -0
- package/srv/utils/epoch-slots.js +45 -0
- package/srv/utils/error-codes.d.ts +26 -75
- package/srv/utils/error-codes.js +27 -72
- package/srv/utils/errors.d.ts +55 -187
- package/srv/utils/errors.js +161 -235
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +111 -223
- package/srv/utils/mappers.js +432 -371
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +9 -15
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +25 -105
- package/srv/utils/tx-build-helper.js +108 -156
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +294 -232
- package/srv/utils/types.js +2 -22
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +60 -170
|
@@ -8,35 +8,29 @@ 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");
|
|
12
|
+
const mappers_1 = require("./utils/mappers");
|
|
11
13
|
const wallet_worker_1 = require("./blockchain/wallet-worker");
|
|
12
14
|
const job_store_1 = require("./blockchain/wallet-worker/job-store");
|
|
13
15
|
const server_1 = require("./server");
|
|
16
|
+
const config_1 = require("./config");
|
|
17
|
+
const build_request_1 = require("./blockchain/wallet-worker/build-request");
|
|
18
|
+
const network_context_1 = require("./utils/network-context");
|
|
19
|
+
const CardanoWorkerService_1 = require("#cds-models/CardanoWorkerService");
|
|
20
|
+
const resolution_1 = require("./utils/resolution");
|
|
21
|
+
const tx_utils_1 = require("./utils/tx-utils");
|
|
22
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
23
|
+
const service_events_1 = require("./utils/service-events");
|
|
14
24
|
const logger = cds_1.default.log('CardanoWorkerService');
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
* singleton (srv/blockchain/wallet-worker). Engine logic lives there; this only
|
|
18
|
-
* validates inputs, inserts/reads job rows and starts/stops the worker.
|
|
19
|
-
*
|
|
20
|
-
* Validation rejections happen BEFORE handleRequest (project convention); the
|
|
21
|
-
* job INSERT runs on the request's ambient transaction (NIGHTGATE lesson 1).
|
|
22
|
-
*/
|
|
25
|
+
const TERMINAL_JOB_STATUS = new Set(['confirmed', 'failed', 'cancelled', 'unresolved']);
|
|
26
|
+
const JOB_WAIT_POLL_MS = 1000;
|
|
23
27
|
function isAdmin(req) {
|
|
24
28
|
return req.user?.is?.('Admin') ?? false;
|
|
25
29
|
}
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
* Returns the role the caller is missing, or null when the wallet is not HSM-backed,
|
|
31
|
-
* no role is configured, or the caller holds it.
|
|
32
|
-
*/
|
|
33
|
-
function missingHsmRole(req, signerType) {
|
|
34
|
-
if (signerType !== 'hsm')
|
|
35
|
-
return null;
|
|
36
|
-
const requiresRole = (0, server_1.getHsmConfig)()?.requiresRole;
|
|
37
|
-
if (!requiresRole || req.user?.is(requiresRole))
|
|
38
|
-
return null;
|
|
39
|
-
return requiresRole;
|
|
30
|
+
/** The first role the caller lacks for this wallet: its own requiresRole, then hsm.requiresRole on an HSM wallet. */
|
|
31
|
+
function missingWalletRole(req, wallet) {
|
|
32
|
+
const roles = [wallet?.requiresRole, wallet?.signerType === 'hsm' ? (0, server_1.getHsmConfig)()?.requiresRole : null];
|
|
33
|
+
return roles.find((role) => role && !req.user?.is(role)) ?? null;
|
|
40
34
|
}
|
|
41
35
|
function toJobStatus(job) {
|
|
42
36
|
return {
|
|
@@ -52,63 +46,75 @@ function toJobStatus(job) {
|
|
|
52
46
|
submittedAt: job.submittedAt,
|
|
53
47
|
confirmedAt: job.confirmedAt,
|
|
54
48
|
finishedAt: job.finishedAt,
|
|
49
|
+
resolution: job.resolution,
|
|
50
|
+
invalidationTxHash: job.invalidationTxHash,
|
|
55
51
|
};
|
|
56
52
|
}
|
|
53
|
+
/** CardanoWorkerService handlers: job submission and status, worker control. */
|
|
57
54
|
module.exports = (srv) => {
|
|
58
|
-
|
|
59
|
-
|
|
55
|
+
(0, result_numbers_1.answerNumbersAsText)(srv);
|
|
56
|
+
// SubmitWalletJob: queue an async transaction job; returns the jobId immediately.
|
|
57
|
+
srv.on(CardanoWorkerService_1.SubmitWalletJob, async (req) => {
|
|
60
58
|
const { walletId, kind, requestJson, idempotencyKey, priority, notBefore } = req.data;
|
|
61
59
|
if (!walletId?.trim())
|
|
62
60
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'walletId is required', 'walletId');
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
// the model rejects an unknown kind and a priority outside 0..10000
|
|
62
|
+
if (!kind)
|
|
63
|
+
return (0, errors_1.rejectMissing)(req, 'SubmitWalletJob', 'kind');
|
|
66
64
|
if (!requestJson?.trim())
|
|
67
65
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'requestJson is required', 'requestJson');
|
|
68
66
|
const jsonResult = (0, validators_1.validateJsonWithLimits)(requestJson, 'requestJson');
|
|
69
67
|
if (!jsonResult.valid)
|
|
70
68
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', jsonResult.error, 'requestJson');
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
69
|
+
const request = (0, build_request_1.parseJobRequest)(requestJson);
|
|
70
|
+
if (!request)
|
|
71
|
+
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'requestJson must be a JSON object', 'requestJson');
|
|
74
72
|
if (notBefore != null && Number.isNaN(Date.parse(String(notBefore)))) {
|
|
75
73
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'notBefore must be a valid timestamp', 'notBefore');
|
|
76
74
|
}
|
|
77
75
|
if (idempotencyKey != null && String(idempotencyKey).length > 100) {
|
|
78
76
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'idempotencyKey exceeds 100 characters', 'idempotencyKey');
|
|
79
77
|
}
|
|
78
|
+
if (kind === 'submitSigned') {
|
|
79
|
+
const network = (0, network_context_1.getActiveNetwork)();
|
|
80
|
+
if (!network)
|
|
81
|
+
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'No network is configured');
|
|
82
|
+
const problem = (0, build_request_1.submitSignedProblem)(request, network);
|
|
83
|
+
if (problem)
|
|
84
|
+
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', problem, 'requestJson');
|
|
85
|
+
}
|
|
80
86
|
let config;
|
|
81
87
|
try {
|
|
82
|
-
config = (0,
|
|
88
|
+
config = (0, config_1.loadWalletWorkerConfigFromEnv)();
|
|
83
89
|
}
|
|
84
90
|
catch (err) {
|
|
85
91
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', err instanceof Error ? err.message : String(err));
|
|
86
92
|
}
|
|
87
93
|
if (!config.enabled) {
|
|
88
|
-
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'Wallet worker is not enabled
|
|
94
|
+
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.');
|
|
89
95
|
}
|
|
90
96
|
// Role gate on this instance's config, mirroring the sign service's 403.
|
|
91
|
-
const configuredRole =
|
|
97
|
+
const configuredRole = missingWalletRole(req, config.wallets.find((w) => w.walletId === walletId));
|
|
92
98
|
if (configuredRole) {
|
|
93
|
-
return
|
|
99
|
+
return (0, mappers_1.mapError)(req, new errors_1.BackendError(`SubmitWalletJob on wallet "${walletId}" requires role '${configuredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId'), 'SubmitWalletJob');
|
|
94
100
|
}
|
|
95
101
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
96
102
|
const wallet = await (0, job_store_1.readWallet)(db, walletId);
|
|
97
103
|
if (!wallet)
|
|
98
|
-
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Unknown wallet "${walletId}"
|
|
104
|
+
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Unknown wallet "${walletId}": configured wallets are registered at worker start`, 'walletId');
|
|
99
105
|
if (!wallet.enabled)
|
|
100
106
|
return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Wallet "${walletId}" is disabled`, 'walletId');
|
|
101
|
-
// Registered row too: another instance may run the
|
|
102
|
-
const registeredRole =
|
|
107
|
+
// Registered row too: another instance may run the wallet this one has no config for.
|
|
108
|
+
const registeredRole = missingWalletRole(req, wallet);
|
|
103
109
|
if (registeredRole) {
|
|
104
|
-
throw new errors_1.BackendError(`
|
|
110
|
+
throw new errors_1.BackendError(`SubmitWalletJob on wallet "${walletId}" requires role '${registeredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId');
|
|
105
111
|
}
|
|
106
112
|
const result = await (0, job_store_1.insertJob)(db, {
|
|
107
113
|
walletId,
|
|
108
114
|
kind: kind,
|
|
109
115
|
request: requestJson,
|
|
110
116
|
idempotencyKey: idempotencyKey ?? null,
|
|
111
|
-
priority,
|
|
117
|
+
priority: priority ?? undefined,
|
|
112
118
|
notBefore: notBefore ? new Date(notBefore).toISOString() : null,
|
|
113
119
|
maxAttempts: config.defaultMaxAttempts,
|
|
114
120
|
createdBy: req.user?.id ?? null,
|
|
@@ -117,52 +123,89 @@ module.exports = (srv) => {
|
|
|
117
123
|
return result;
|
|
118
124
|
});
|
|
119
125
|
});
|
|
120
|
-
// CancelJob
|
|
121
|
-
srv.on(
|
|
126
|
+
// CancelJob: pending jobs only; scoped to the creator unless Admin.
|
|
127
|
+
srv.on(CardanoWorkerService_1.CancelJob, async (req) => {
|
|
122
128
|
const { jobId } = req.data;
|
|
123
129
|
if (!jobId)
|
|
124
130
|
return (0, errors_1.rejectInvalid)(req, 'CancelJob', 'jobId is required', 'jobId');
|
|
125
131
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
126
132
|
const job = await (0, job_store_1.getJobById)(db, jobId);
|
|
127
133
|
if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
|
|
128
|
-
// Same 404 for "not found" and "not yours"
|
|
129
|
-
//
|
|
130
|
-
// see a plain CAP error and remap it to 500 (mapError). A BackendError
|
|
131
|
-
// carries its status through.
|
|
134
|
+
// Same 404 for "not found" and "not yours" (no existence oracle). Throw, don't
|
|
135
|
+
// req.reject: inside handleRequest a plain CAP error is remapped to 500.
|
|
132
136
|
throw new errors_1.NotFoundError(`Job ${jobId}`);
|
|
133
137
|
}
|
|
134
138
|
const cancelled = await (0, job_store_1.markCancelled)(db, jobId);
|
|
135
139
|
if (!cancelled) {
|
|
136
|
-
return (0, errors_1.rejectInvalid)(req, 'CancelJob', `Job ${jobId} is ${job.status}
|
|
140
|
+
return (0, errors_1.rejectInvalid)(req, 'CancelJob', `Job ${jobId} is ${job.status}: only pending jobs can be cancelled`, 'jobId');
|
|
137
141
|
}
|
|
138
142
|
return true;
|
|
139
143
|
});
|
|
140
144
|
});
|
|
141
|
-
//
|
|
142
|
-
|
|
143
|
-
|
|
145
|
+
// ResolveJob (Admin): settles an unresolved job as an operator read it on the chain. The job keeps
|
|
146
|
+
// its idempotency key, and the terminal event goes out after the commit.
|
|
147
|
+
srv.on(CardanoWorkerService_1.ResolveJob, async (req) => {
|
|
148
|
+
const { jobId, outcome, txHash, note } = req.data;
|
|
149
|
+
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
150
|
+
// read and ask the chain before the request takes its connection
|
|
151
|
+
const job = await (0, tx_utils_1.readOutside)(db, (d) => (0, job_store_1.getJobById)(d, jobId));
|
|
152
|
+
if (!job)
|
|
153
|
+
throw new errors_1.NotFoundError(`Job ${jobId}`);
|
|
154
|
+
if (job.status !== 'unresolved')
|
|
155
|
+
(0, errors_1.rejectInvalid)(req, 'ResolveJob', `Job ${jobId} is ${job.status}: only an unresolved job can be resolved`, 'jobId');
|
|
156
|
+
(0, resolution_1.checkResolvedTxHash)(req, 'ResolveJob', txHash, job.txHash);
|
|
157
|
+
const resolved = outcome === 'confirmed' ? 'confirmed' : 'failed';
|
|
158
|
+
await (0, resolution_1.refuseFailedWhileItCanLand)('ResolveJob', resolved, job.signedTxCbor, (0, server_1.getCardanoClient)());
|
|
159
|
+
if (!(await (0, job_store_1.resolveUnresolvedJob)(db, job.ID, resolved, (0, resolution_1.resolutionNote)(resolved, req.user?.id, note)))) {
|
|
160
|
+
throw (0, resolution_1.resolvedConcurrently)('ResolveJob');
|
|
161
|
+
}
|
|
162
|
+
await (0, job_store_1.bumpWalletStats)(db, job.walletId, resolved);
|
|
163
|
+
// the job's submission record follows its outcome
|
|
164
|
+
if (job.txHash) {
|
|
165
|
+
await db.run(cds_1.default.ql.UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: resolved === 'confirmed' ? 'confirmed' : 'failed' })
|
|
166
|
+
.where({ txHash: job.txHash, status: { in: ['submitted', 'pending', 'unresolved'] } }));
|
|
167
|
+
}
|
|
168
|
+
logger.warn(`Job ${job.ID}: unresolved outcome resolved as ${resolved} by ${req.user?.id ?? 'unknown'}`);
|
|
169
|
+
const after = (await (0, job_store_1.getJobById)(db, job.ID));
|
|
170
|
+
req.on('succeeded', () => (0, service_events_1.emitServiceEvent)('CardanoWorkerService', resolved === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
|
|
171
|
+
jobId: after.ID, walletId: after.walletId, kind: after.kind, txHash: after.txHash,
|
|
172
|
+
...(resolved === 'failed' ? { errorCode: after.errorCode, errorMessage: after.errorMessage } : {}),
|
|
173
|
+
}));
|
|
174
|
+
return toJobStatus(after);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
// GetJobStatus: scoped to the creator unless Admin. With waitMs it answers once the job is
|
|
178
|
+
// confirmed, failed, cancelled or unresolved, or when the time is up. Each read has its own transaction,
|
|
179
|
+
// so a waiting request holds no database connection.
|
|
180
|
+
srv.on(CardanoWorkerService_1.GetJobStatus, async (req) => {
|
|
181
|
+
const { jobId, waitMs } = req.data;
|
|
144
182
|
if (!jobId)
|
|
145
183
|
return (0, errors_1.rejectInvalid)(req, 'GetJobStatus', 'jobId is required', 'jobId');
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
184
|
+
const deadline = Date.now() + Number(waitMs ?? 0);
|
|
185
|
+
return (0, backend_request_handler_1.handleRequest)(req, async () => {
|
|
186
|
+
for (;;) {
|
|
187
|
+
const job = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, jobId)));
|
|
188
|
+
if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
|
|
189
|
+
throw new errors_1.NotFoundError(`Job ${jobId}`); // see CancelJob: reject() here becomes a 500
|
|
190
|
+
}
|
|
191
|
+
const timeUp = Date.now() + JOB_WAIT_POLL_MS > deadline || req.http?.res.destroyed === true;
|
|
192
|
+
if (TERMINAL_JOB_STATUS.has(job.status) || timeUp)
|
|
193
|
+
return toJobStatus(job);
|
|
194
|
+
await new Promise((resolve) => setTimeout(resolve, JOB_WAIT_POLL_MS));
|
|
150
195
|
}
|
|
151
|
-
return toJobStatus(job);
|
|
152
196
|
});
|
|
153
197
|
});
|
|
154
|
-
// GetWorkerStatus
|
|
198
|
+
// GetWorkerStatus: live summary of the local worker instance.
|
|
155
199
|
srv.on('GetWorkerStatus', async (req) => {
|
|
156
200
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
157
201
|
const worker = (0, wallet_worker_1.getWalletWorker)();
|
|
158
202
|
const summary = worker?.getStatusSummary() ?? {
|
|
159
203
|
running: false, wallets: [], executing: [], awaitingConfirmation: 0,
|
|
160
204
|
};
|
|
161
|
-
|
|
162
|
-
return { ...summary, pendingJobs: pending.length };
|
|
205
|
+
return { ...summary, pendingJobs: await (0, job_store_1.countPendingJobs)(db), unresolvedJobs: await (0, job_store_1.countJobs)(db, 'unresolved') };
|
|
163
206
|
});
|
|
164
207
|
});
|
|
165
|
-
// PauseWorker
|
|
208
|
+
// PauseWorker: stop the local instance; queued jobs stay pending.
|
|
166
209
|
srv.on('PauseWorker', async (req) => {
|
|
167
210
|
return (0, backend_request_handler_1.handleRequest)(req, async () => {
|
|
168
211
|
await (0, wallet_worker_1.stopWalletWorker)();
|
|
@@ -170,18 +213,18 @@ module.exports = (srv) => {
|
|
|
170
213
|
return true;
|
|
171
214
|
});
|
|
172
215
|
});
|
|
173
|
-
// ResumeWorker
|
|
216
|
+
// ResumeWorker: (re)start the local instance from config. Gated on enabled,
|
|
174
217
|
// mirroring resumeCrawler.
|
|
175
218
|
srv.on('ResumeWorker', async (req) => {
|
|
176
219
|
let config;
|
|
177
220
|
try {
|
|
178
|
-
config = (0,
|
|
221
|
+
config = (0, config_1.loadWalletWorkerConfigFromEnv)();
|
|
179
222
|
}
|
|
180
223
|
catch (err) {
|
|
181
224
|
return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', err instanceof Error ? err.message : String(err));
|
|
182
225
|
}
|
|
183
226
|
if (!config.enabled) {
|
|
184
|
-
return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', 'Wallet worker is not enabled
|
|
227
|
+
return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', 'Wallet worker is not enabled: set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) before resuming.');
|
|
185
228
|
}
|
|
186
229
|
return (0, backend_request_handler_1.handleRequest)(req, async () => {
|
|
187
230
|
const client = (0, server_1.getCardanoClient)();
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** CIP-67 asset-name labels of the CIP-68 token classes, as the first 4 bytes of the asset name. */
|
|
2
|
+
export declare const CIP68_LABEL: {
|
|
3
|
+
readonly reference: "000643b0";
|
|
4
|
+
readonly nft: "000de140";
|
|
5
|
+
readonly ft: "0014df10";
|
|
6
|
+
readonly rft: "001bc280";
|
|
7
|
+
};
|
|
8
|
+
/** Reference-NFT unit of a CIP-68 user token with label 333 or 444; null for any other unit. */
|
|
9
|
+
export declare function cip68ReferenceUnit(unit: string): string | null;
|
|
10
|
+
/** The label-333 and label-444 units a CIP-68 reference NFT describes; null for any other unit. */
|
|
11
|
+
export declare function cip68UserUnits(referenceUnit: string): string[] | null;
|
|
12
|
+
export declare function cip68DecimalsFromDatum(cborHex: string): number | null;
|
|
13
|
+
//# sourceMappingURL=cip68.d.ts.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CIP68_LABEL = void 0;
|
|
4
|
+
exports.cip68ReferenceUnit = cip68ReferenceUnit;
|
|
5
|
+
exports.cip68UserUnits = cip68UserUnits;
|
|
6
|
+
exports.cip68DecimalsFromDatum = cip68DecimalsFromDatum;
|
|
7
|
+
const plutus_data_1 = require("@harmoniclabs/plutus-data");
|
|
8
|
+
/** CIP-67 asset-name labels of the CIP-68 token classes, as the first 4 bytes of the asset name. */
|
|
9
|
+
exports.CIP68_LABEL = {
|
|
10
|
+
reference: '000643b0',
|
|
11
|
+
nft: '000de140',
|
|
12
|
+
ft: '0014df10',
|
|
13
|
+
rft: '001bc280',
|
|
14
|
+
};
|
|
15
|
+
/** Labels whose reference datum may carry `decimals`. */
|
|
16
|
+
const USER_LABELS_WITH_DECIMALS = [exports.CIP68_LABEL.ft, exports.CIP68_LABEL.rft];
|
|
17
|
+
const labelOf = (unit) => unit.slice(56, 64);
|
|
18
|
+
/** Reference-NFT unit of a CIP-68 user token with label 333 or 444; null for any other unit. */
|
|
19
|
+
function cip68ReferenceUnit(unit) {
|
|
20
|
+
if (unit.length < 64 || !USER_LABELS_WITH_DECIMALS.includes(labelOf(unit)))
|
|
21
|
+
return null;
|
|
22
|
+
return unit.slice(0, 56) + exports.CIP68_LABEL.reference + unit.slice(64);
|
|
23
|
+
}
|
|
24
|
+
/** The label-333 and label-444 units a CIP-68 reference NFT describes; null for any other unit. */
|
|
25
|
+
function cip68UserUnits(referenceUnit) {
|
|
26
|
+
if (referenceUnit.length < 64 || labelOf(referenceUnit) !== exports.CIP68_LABEL.reference)
|
|
27
|
+
return null;
|
|
28
|
+
return USER_LABELS_WITH_DECIMALS.map((label) => referenceUnit.slice(0, 56) + label + referenceUnit.slice(64));
|
|
29
|
+
}
|
|
30
|
+
const DECIMALS_KEY = Buffer.from('decimals');
|
|
31
|
+
// The datum is Constr 0 with the metadata map, keyed by UTF-8 bytes, as first field.
|
|
32
|
+
// Null when the shape differs or decimals is not an integer in 0..255.
|
|
33
|
+
function cip68DecimalsFromDatum(cborHex) {
|
|
34
|
+
let data;
|
|
35
|
+
try {
|
|
36
|
+
data = (0, plutus_data_1.dataFromCbor)(cborHex);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
if (!(data instanceof plutus_data_1.DataConstr) || data.constr !== 0n)
|
|
42
|
+
return null;
|
|
43
|
+
const metadata = data.fields[0];
|
|
44
|
+
if (!(metadata instanceof plutus_data_1.DataMap))
|
|
45
|
+
return null;
|
|
46
|
+
for (const kv of metadata.map) {
|
|
47
|
+
if (!(kv.fst instanceof plutus_data_1.DataB) || !DECIMALS_KEY.equals(Buffer.from(kv.fst.bytes)))
|
|
48
|
+
continue;
|
|
49
|
+
if (!(kv.snd instanceof plutus_data_1.DataI))
|
|
50
|
+
return null;
|
|
51
|
+
const n = kv.snd.int;
|
|
52
|
+
return n >= 0n && n <= 255n ? Number(n) : null;
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=cip68.js.map
|
package/srv/cbor/index.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
export { parseTransaction, type ParsedTransaction, type ParsedInput, type ParsedOutput, type ParsedAsset, type ParsedWitnesses, } from './parse';
|
|
1
|
+
export { parseTransaction, type ParsedTransaction, type ParsedInput, type ParsedOutput, type ParsedAsset, type ParsedWitnesses, type ParsedWithdrawal, type ParsedCertificate, } from './parse';
|
|
2
|
+
export { decodePlutusData, plutusDataToJson, type PlutusDataJson } from './plutus-data-json';
|
|
3
|
+
export { CIP68_LABEL, cip68ReferenceUnit, cip68UserUnits, cip68DecimalsFromDatum } from './cip68';
|
|
2
4
|
//# sourceMappingURL=index.d.ts.map
|
package/srv/cbor/index.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.parseTransaction = void 0;
|
|
3
|
+
exports.cip68DecimalsFromDatum = exports.cip68UserUnits = exports.cip68ReferenceUnit = exports.CIP68_LABEL = exports.plutusDataToJson = exports.decodePlutusData = exports.parseTransaction = void 0;
|
|
4
4
|
var parse_1 = require("./parse");
|
|
5
5
|
Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return parse_1.parseTransaction; } });
|
|
6
|
+
var plutus_data_json_1 = require("./plutus-data-json");
|
|
7
|
+
Object.defineProperty(exports, "decodePlutusData", { enumerable: true, get: function () { return plutus_data_json_1.decodePlutusData; } });
|
|
8
|
+
Object.defineProperty(exports, "plutusDataToJson", { enumerable: true, get: function () { return plutus_data_json_1.plutusDataToJson; } });
|
|
9
|
+
var cip68_1 = require("./cip68");
|
|
10
|
+
Object.defineProperty(exports, "CIP68_LABEL", { enumerable: true, get: function () { return cip68_1.CIP68_LABEL; } });
|
|
11
|
+
Object.defineProperty(exports, "cip68ReferenceUnit", { enumerable: true, get: function () { return cip68_1.cip68ReferenceUnit; } });
|
|
12
|
+
Object.defineProperty(exports, "cip68UserUnits", { enumerable: true, get: function () { return cip68_1.cip68UserUnits; } });
|
|
13
|
+
Object.defineProperty(exports, "cip68DecimalsFromDatum", { enumerable: true, get: function () { return cip68_1.cip68DecimalsFromDatum; } });
|
|
6
14
|
//# sourceMappingURL=index.js.map
|
package/srv/cbor/parse.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export interface ParsedInput {
|
|
|
5
5
|
export interface ParsedAsset {
|
|
6
6
|
/** `"policyIdHex" + "assetNameHex"` (concatenated, no separator). */
|
|
7
7
|
unit: string;
|
|
8
|
-
/** Signed decimal string
|
|
8
|
+
/** Signed decimal string; negative for burns in `mint`, never negative in outputs. */
|
|
9
9
|
quantity: string;
|
|
10
10
|
}
|
|
11
11
|
export interface ParsedOutput {
|
|
@@ -15,6 +15,19 @@ export interface ParsedOutput {
|
|
|
15
15
|
datumHash: string | null;
|
|
16
16
|
inlineDatumHex: string | null;
|
|
17
17
|
referenceScriptHex: string | null;
|
|
18
|
+
/** Byte length of the output as it stands in the transaction. */
|
|
19
|
+
cborSize: number;
|
|
20
|
+
}
|
|
21
|
+
export interface ParsedWithdrawal {
|
|
22
|
+
/** Bech32 reward address. */
|
|
23
|
+
rewardAddress: string;
|
|
24
|
+
lovelace: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ParsedCertificate {
|
|
27
|
+
/** Position in the body's certificate list. */
|
|
28
|
+
index: number;
|
|
29
|
+
/** Ledger certificate name, e.g. `StakeDelegation` or `RegistrationDrep`. */
|
|
30
|
+
type: string;
|
|
18
31
|
}
|
|
19
32
|
export interface ParsedWitnesses {
|
|
20
33
|
vkeyCount: number;
|
|
@@ -24,17 +37,11 @@ export interface ParsedWitnesses {
|
|
|
24
37
|
redeemers: number;
|
|
25
38
|
}
|
|
26
39
|
export interface ParsedTransaction {
|
|
27
|
-
/**
|
|
28
|
-
* Blake2b-256 hash of the transaction body. Stable across signed/unsigned
|
|
29
|
-
* CBOR — signing adds witnesses without changing the body hash.
|
|
30
|
-
*/
|
|
40
|
+
/** Blake2b-256 of the body. Signing adds witnesses, so the hash stays the same. */
|
|
31
41
|
txHash: string;
|
|
32
|
-
/**
|
|
33
|
-
* `"mainnet"` or `"testnet"` when the body carries a network ID byte, else
|
|
34
|
-
* `null`. Preview vs preprod cannot be distinguished from CBOR alone; a
|
|
35
|
-
* consumer needing that split must compare against the service network.
|
|
36
|
-
*/
|
|
37
42
|
network: 'mainnet' | 'testnet' | null;
|
|
43
|
+
/** Body field 15: 1 = mainnet, 0 = testnet, null if absent. */
|
|
44
|
+
networkId: number | null;
|
|
38
45
|
inputs: ParsedInput[];
|
|
39
46
|
outputs: ParsedOutput[];
|
|
40
47
|
/** Validity-interval start slot (decimal string) or `null` if absent. */
|
|
@@ -43,22 +50,27 @@ export interface ParsedTransaction {
|
|
|
43
50
|
validityEnd: string | null;
|
|
44
51
|
/** Fee in lovelace (decimal string). */
|
|
45
52
|
fee: string;
|
|
46
|
-
/** Native-asset mint
|
|
53
|
+
/** Native-asset mint and burn entries; quantities are signed. */
|
|
47
54
|
mint: ParsedAsset[];
|
|
48
55
|
/** Metadata labels present (uint64 → decimal string); full payload via GetMetadataByTxHash for submitted txs. */
|
|
49
56
|
metadataLabels: string[];
|
|
50
57
|
collateral: ParsedInput[];
|
|
58
|
+
referenceInputs: ParsedInput[];
|
|
59
|
+
withdrawals: ParsedWithdrawal[];
|
|
60
|
+
certificates: ParsedCertificate[];
|
|
61
|
+
/** Number of votes over all voters; 0 if the body has no voting procedures. */
|
|
62
|
+
votingProcedures: number;
|
|
63
|
+
proposalProcedures: number;
|
|
64
|
+
/** Lovelace (decimal string) or `null` if absent. */
|
|
65
|
+
treasuryDonation: string | null;
|
|
66
|
+
/** Lovelace (decimal string) or `null` if absent. */
|
|
67
|
+
currentTreasuryValue: string | null;
|
|
51
68
|
/** 28-byte Ed25519 key hashes listed in the tx body's required_signers field. */
|
|
52
69
|
requiredSigners: string[];
|
|
53
70
|
scriptDataHash: string | null;
|
|
71
|
+
/** `false` when the transaction is flagged as failing its scripts. On chain it then spends only the collateral and creates no outputs. */
|
|
72
|
+
isValid: boolean;
|
|
54
73
|
witnesses: ParsedWitnesses;
|
|
55
74
|
}
|
|
56
|
-
/**
|
|
57
|
-
* Parse hex-encoded Cardano transaction CBOR (signed or unsigned) into structured
|
|
58
|
-
* fields. Pure function — no network call, no DB write. Callers are responsible
|
|
59
|
-
* for upstream size/format validation via `isValidTxCborHex`.
|
|
60
|
-
*
|
|
61
|
-
* @throws TransactionValidationError with code `TX_PARSE_FAILED` on malformed CBOR.
|
|
62
|
-
*/
|
|
63
75
|
export declare function parseTransaction(cborHex: string): ParsedTransaction;
|
|
64
76
|
//# sourceMappingURL=parse.d.ts.map
|
package/srv/cbor/parse.js
CHANGED
|
@@ -2,19 +2,20 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.parseTransaction = parseTransaction;
|
|
4
4
|
const buildooor_1 = require("@harmoniclabs/buildooor");
|
|
5
|
+
const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
|
|
6
|
+
const cbor_1 = require("@harmoniclabs/cbor");
|
|
5
7
|
const errors_1 = require("../utils/errors");
|
|
6
8
|
const error_codes_1 = require("../utils/error-codes");
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
* fields. Pure function — no network call, no DB write. Callers are responsible
|
|
10
|
-
* for upstream size/format validation via `isValidTxCborHex`.
|
|
11
|
-
*
|
|
12
|
-
* @throws TransactionValidationError with code `TX_PARSE_FAILED` on malformed CBOR.
|
|
13
|
-
*/
|
|
9
|
+
// Pure, no network call. Callers validate size and format with `isValidTxCborHex` first.
|
|
10
|
+
// Throws TX_PARSE_FAILED on malformed CBOR.
|
|
14
11
|
function parseTransaction(cborHex) {
|
|
15
12
|
let tx;
|
|
13
|
+
let networkId;
|
|
16
14
|
try {
|
|
17
|
-
|
|
15
|
+
// one decode for both readers; keepRef keeps the original bytes for the body hash and datums
|
|
16
|
+
const parsed = cbor_1.Cbor.parse(Buffer.from(cborHex, 'hex'), { keepRef: true });
|
|
17
|
+
tx = buildooor_1.Tx.fromCborObj(parsed);
|
|
18
|
+
networkId = readNetworkId(parsed);
|
|
18
19
|
}
|
|
19
20
|
catch (e) {
|
|
20
21
|
const msg = e instanceof Error ? e.message : String(e);
|
|
@@ -24,6 +25,7 @@ function parseTransaction(cborHex) {
|
|
|
24
25
|
return {
|
|
25
26
|
txHash: body.hash.toString(),
|
|
26
27
|
network: normalizeNetwork(body.network),
|
|
28
|
+
networkId,
|
|
27
29
|
inputs: body.inputs.map(mapInput),
|
|
28
30
|
outputs: body.outputs.map(mapOutput),
|
|
29
31
|
validityStart: body.validityIntervalStart != null ? body.validityIntervalStart.toString() : null,
|
|
@@ -32,8 +34,19 @@ function parseTransaction(cborHex) {
|
|
|
32
34
|
mint: mapMint(body.mint),
|
|
33
35
|
metadataLabels: extractMetadataLabels(tx.auxiliaryData),
|
|
34
36
|
collateral: (body.collateralInputs ?? []).map(mapInput),
|
|
37
|
+
referenceInputs: (body.refInputs ?? []).map(mapInput),
|
|
38
|
+
withdrawals: (body.withdrawals?.map ?? []).map((w) => ({
|
|
39
|
+
rewardAddress: w.rewardAccount.toString(),
|
|
40
|
+
lovelace: w.amount.toString(),
|
|
41
|
+
})),
|
|
42
|
+
certificates: (body.certs ?? []).map(mapCertificate),
|
|
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,
|
|
35
47
|
requiredSigners: (body.requiredSigners ?? []).map((s) => s.toString()),
|
|
36
48
|
scriptDataHash: body.scriptDataHash ? body.scriptDataHash.toString() : null,
|
|
49
|
+
isValid: tx.isScriptValid,
|
|
37
50
|
witnesses: countWitnesses(tx.witnesses),
|
|
38
51
|
};
|
|
39
52
|
}
|
|
@@ -66,7 +79,7 @@ function mapOutput(out) {
|
|
|
66
79
|
}
|
|
67
80
|
else {
|
|
68
81
|
// anything not a Hash32 is an inline `Data` (PlutusData) payload
|
|
69
|
-
inlineDatumHex = Buffer.from((0, buildooor_1.dataToCbor)(out.datum)).toString('hex');
|
|
82
|
+
inlineDatumHex = Buffer.from(inlineDatumBytes(out) ?? (0, buildooor_1.dataToCbor)(out.datum)).toString('hex');
|
|
70
83
|
}
|
|
71
84
|
}
|
|
72
85
|
const referenceScriptHex = out.refScript
|
|
@@ -79,8 +92,30 @@ function mapOutput(out) {
|
|
|
79
92
|
datumHash,
|
|
80
93
|
inlineDatumHex,
|
|
81
94
|
referenceScriptHex,
|
|
95
|
+
// the bytes as received; a re-encoding can be shorter
|
|
96
|
+
cborSize: out.cborRef ? out.cborRef.toBuffer().length : out.toCborBytes().length,
|
|
82
97
|
};
|
|
83
98
|
}
|
|
99
|
+
function mapCertificate(cert, index) {
|
|
100
|
+
return { index, type: (0, cardano_ledger_ts_1.certTypeToString)(cert.certType) };
|
|
101
|
+
}
|
|
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) {
|
|
104
|
+
const body = parsed instanceof cbor_1.CborArray ? parsed.array[0] : undefined;
|
|
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;
|
|
107
|
+
}
|
|
108
|
+
/** Inline datum bytes as they stand in the transaction; decoding and re-encoding may change them. */
|
|
109
|
+
function inlineDatumBytes(out) {
|
|
110
|
+
if (!out.cborRef)
|
|
111
|
+
return undefined;
|
|
112
|
+
const parsed = cbor_1.Cbor.parse(out.toCborBytes());
|
|
113
|
+
if (!(parsed instanceof cbor_1.CborMap))
|
|
114
|
+
return undefined;
|
|
115
|
+
const option = parsed.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === 2n)?.v;
|
|
116
|
+
const tagged = option instanceof cbor_1.CborArray ? option.array[1] : undefined;
|
|
117
|
+
return tagged instanceof cbor_1.CborTag && tagged.data instanceof cbor_1.CborBytes ? tagged.data.bytes : undefined;
|
|
118
|
+
}
|
|
84
119
|
function mapMint(mint) {
|
|
85
120
|
if (!mint)
|
|
86
121
|
return [];
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Data } from '@harmoniclabs/plutus-data';
|
|
2
|
+
export type PlutusDataJson = {
|
|
3
|
+
constructor: number;
|
|
4
|
+
fields: PlutusDataJson[];
|
|
5
|
+
} | {
|
|
6
|
+
int: number | string;
|
|
7
|
+
} | {
|
|
8
|
+
bytes: string;
|
|
9
|
+
} | {
|
|
10
|
+
list: PlutusDataJson[];
|
|
11
|
+
} | {
|
|
12
|
+
map: {
|
|
13
|
+
k: PlutusDataJson;
|
|
14
|
+
v: PlutusDataJson;
|
|
15
|
+
}[];
|
|
16
|
+
};
|
|
17
|
+
export declare function plutusDataToJson(data: Data): PlutusDataJson;
|
|
18
|
+
/** @throws TransactionValidationError (`TX_PARSE_FAILED`) when the hex is not PlutusData CBOR. */
|
|
19
|
+
export declare function decodePlutusData(cborHex: string): PlutusDataJson;
|
|
20
|
+
//# sourceMappingURL=plutus-data-json.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.plutusDataToJson = plutusDataToJson;
|
|
4
|
+
exports.decodePlutusData = decodePlutusData;
|
|
5
|
+
const plutus_data_1 = require("@harmoniclabs/plutus-data");
|
|
6
|
+
const errors_1 = require("../utils/errors");
|
|
7
|
+
const error_codes_1 = require("../utils/error-codes");
|
|
8
|
+
function plutusDataToJson(data) {
|
|
9
|
+
if (data instanceof plutus_data_1.DataConstr)
|
|
10
|
+
return { constructor: Number(data.constr), fields: data.fields.map(plutusDataToJson) };
|
|
11
|
+
if (data instanceof plutus_data_1.DataI) {
|
|
12
|
+
const i = data.int;
|
|
13
|
+
return { int: i >= BigInt(Number.MIN_SAFE_INTEGER) && i <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(i) : i.toString() };
|
|
14
|
+
}
|
|
15
|
+
if (data instanceof plutus_data_1.DataB)
|
|
16
|
+
return { bytes: Buffer.from(data.bytes).toString('hex') };
|
|
17
|
+
if (data instanceof plutus_data_1.DataList)
|
|
18
|
+
return { list: data.list.map(plutusDataToJson) };
|
|
19
|
+
if (data instanceof plutus_data_1.DataMap)
|
|
20
|
+
return { map: data.map.map((kv) => ({ k: plutusDataToJson(kv.fst), v: plutusDataToJson(kv.snd) })) };
|
|
21
|
+
throw new TypeError('unknown PlutusData node');
|
|
22
|
+
}
|
|
23
|
+
/** @throws TransactionValidationError (`TX_PARSE_FAILED`) when the hex is not PlutusData CBOR. */
|
|
24
|
+
function decodePlutusData(cborHex) {
|
|
25
|
+
try {
|
|
26
|
+
return plutusDataToJson((0, plutus_data_1.dataFromCbor)(cborHex.trim().toLowerCase()));
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
throw new errors_1.TransactionValidationError(`Not PlutusData CBOR: ${err instanceof Error ? err.message : String(err)}`, err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=plutus-data-json.js.map
|