@odatano/core 2.0.0-rc.1 → 2.0.0-rc.11

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 (66) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -2
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  7. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  8. package/@cds-models/odatano/cardano/index.js +6 -0
  9. package/README.md +62 -4
  10. package/db/schema.cds +105 -0
  11. package/package.json +9 -3
  12. package/src/index.d.ts +6 -0
  13. package/src/index.js +21 -1
  14. package/src/plugin.js +33 -30
  15. package/srv/blockchain/backends/blockfrost-backend.js +1 -10
  16. package/srv/blockchain/backends/koios-backend.js +1 -10
  17. package/srv/blockchain/backends/ogmios-backend.d.ts +29 -4
  18. package/srv/blockchain/backends/ogmios-backend.js +96 -7
  19. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  20. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  21. package/srv/blockchain/cardano-indexer.d.ts +18 -0
  22. package/srv/blockchain/cardano-indexer.js +58 -3
  23. package/srv/blockchain/crawler/crawler.d.ts +55 -0
  24. package/srv/blockchain/crawler/crawler.js +153 -3
  25. package/srv/blockchain/crawler/index.d.ts +9 -0
  26. package/srv/blockchain/crawler/index.js +37 -4
  27. package/srv/blockchain/crawler/sync-state.d.ts +13 -1
  28. package/srv/blockchain/crawler/sync-state.js +24 -2
  29. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  30. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  31. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  32. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  33. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  34. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  35. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  36. package/srv/cardano-agent-service.cds +150 -0
  37. package/srv/cardano-agent-service.d.ts +2 -0
  38. package/srv/cardano-agent-service.js +16 -0
  39. package/srv/cardano-indexer-service.cds +36 -3
  40. package/srv/cardano-indexer-service.js +3 -0
  41. package/srv/cardano-service.js +57 -3
  42. package/srv/cardano-sign-service.cds +200 -180
  43. package/srv/cardano-tx-service.cds +32 -26
  44. package/srv/cardano-tx-service.js +96 -38
  45. package/srv/cardano-worker-service.cds +125 -125
  46. package/srv/server.d.ts +2 -1
  47. package/srv/server.js +18 -34
  48. package/srv/utils/agent-grants-config.d.ts +65 -0
  49. package/srv/utils/agent-grants-config.js +148 -0
  50. package/srv/utils/agent-grants.d.ts +314 -0
  51. package/srv/utils/agent-grants.js +821 -0
  52. package/srv/utils/agent-token-auth.d.ts +19 -0
  53. package/srv/utils/agent-token-auth.js +81 -0
  54. package/srv/utils/db-sanitize.d.ts +40 -0
  55. package/srv/utils/db-sanitize.js +98 -0
  56. package/srv/utils/errors.d.ts +18 -0
  57. package/srv/utils/errors.js +24 -1
  58. package/srv/utils/liveness.d.ts +23 -0
  59. package/srv/utils/liveness.js +49 -0
  60. package/srv/utils/mappers.d.ts +27 -0
  61. package/srv/utils/mappers.js +67 -7
  62. package/srv/utils/rate-limiter.d.ts +57 -0
  63. package/srv/utils/rate-limiter.js +126 -0
  64. package/srv/utils/tx-request-parsers.d.ts +13 -0
  65. package/srv/utils/tx-request-parsers.js +32 -0
  66. package/srv/utils/types.d.ts +34 -0
package/db/schema.cds CHANGED
@@ -1631,3 +1631,108 @@ entity CardanoWalletJobs {
1631
1631
  @description: 'Timestamp the job reached a terminal state (confirmed | failed | cancelled)'
1632
1632
  finishedAt : Timestamp;
1633
1633
  }
1634
+
1635
+ /**
1636
+ * Agent grants (v2.0): scoped bearer capabilities an Admin hands to an agent
1637
+ * instead of a full user. The token is a capability, not an identity — it is
1638
+ * stored as SHA-256 only, and a request carrying it runs as the principal
1639
+ * `agent:<ID>` with the role `agent-grant`, never as the operator. Enforcement
1640
+ * (allow list, wallet pinning, daily budget) lives in srv/utils/agent-grants.ts;
1641
+ * the transport lane that admits `x-agent-token` in srv/utils/agent-token-auth.ts.
1642
+ * Admin-only table: creation and revocation happen through CardanoAgentService
1643
+ * actions, a token request may read its own row only.
1644
+ */
1645
+ @title : 'Agent Grants'
1646
+ @description: 'Scoped, budgeted bearer capabilities for agents (token stored as SHA-256 only)'
1647
+ entity CardanoAgentGrants {
1648
+
1649
+ @title : 'Grant Id (Key)'
1650
+ key ID : UUID;
1651
+
1652
+ @title : 'Operator'
1653
+ @description: 'User id of the Admin that issued the grant (audit; the token never runs as this user)'
1654
+ userId : String(200) not null;
1655
+
1656
+ @title : 'Agent Label'
1657
+ @description: 'Human-readable agent name, informational'
1658
+ agentLabel : String(100);
1659
+
1660
+ @title : 'Token Hash'
1661
+ @description: 'SHA-256 of the bearer token; the token itself is shown once and never stored'
1662
+ tokenHash : String(64) not null;
1663
+
1664
+ @title : 'Allowed Actions'
1665
+ @description: 'JSON array of allow-listed action names (builds, signing-request lifecycle, submits, wallet jobs)'
1666
+ allowedActions : LargeString not null;
1667
+
1668
+ @title : 'Wallet Id'
1669
+ @description: 'Worker wallet this grant is pinned to; required for SubmitWalletJob / CancelJob, injected into those requests'
1670
+ walletId : String(50);
1671
+
1672
+ @title : 'Allowed Job Kinds'
1673
+ @description: 'JSON array of WalletJobKind values the grant may queue; null = every kind'
1674
+ allowedJobKinds : LargeString;
1675
+
1676
+ @title : 'Max Jobs Per Day'
1677
+ @description: 'Daily budget of allow-listed action calls (UTC day); null = unlimited'
1678
+ maxJobsPerDay : Integer;
1679
+
1680
+ @title : 'Jobs Used Today'
1681
+ @description: 'Budget consumed inside budgetWindow'
1682
+ jobsUsedToday : Integer default 0;
1683
+
1684
+ @title : 'Budget Window'
1685
+ @description: 'UTC day YYYY-MM-DD the counter belongs to'
1686
+ budgetWindow : String(10);
1687
+
1688
+ @title : 'Valid Until'
1689
+ @description: 'Expiry; null = no expiry'
1690
+ validUntil : Timestamp;
1691
+
1692
+ @title : 'Is Active'
1693
+ @description: 'False once revoked; a revoked token is an unknown token'
1694
+ isActive : Boolean default true;
1695
+
1696
+ @title : 'Revoked At'
1697
+ revokedAt : Timestamp;
1698
+
1699
+ @title : 'Created At'
1700
+ createdAt : Timestamp;
1701
+
1702
+ @title : 'Last Used At'
1703
+ @description: 'Last request admitted under this token (updated at most once a minute)'
1704
+ lastUsedAt : Timestamp;
1705
+ }
1706
+
1707
+ /**
1708
+ * Daily per-action counters of admitted calls under a grant (feeds
1709
+ * CardanoAgentService.GetGrantUsage). Written by the enforcement hook next to
1710
+ * the daily budget: `calls + 1` when a call is admitted, `refunded + 1` when the
1711
+ * handler then refuses its input. Not exposed as an entity — the function is
1712
+ * the contract. A few dozen rows per grant and day at most; no retention job yet.
1713
+ */
1714
+ entity CardanoAgentGrantUsage {
1715
+
1716
+ @title : 'Grant'
1717
+ key grant : Association to CardanoAgentGrants;
1718
+
1719
+ @title : 'Day'
1720
+ @description: 'UTC day YYYY-MM-DD the call was admitted on'
1721
+ key day : String(10);
1722
+
1723
+ @title : 'Service'
1724
+ @description: 'CAP service name (CardanoTransactionService, CardanoSignService, ...)'
1725
+ key service : String(60);
1726
+
1727
+ @title : 'Action'
1728
+ @description: 'Action name (BuildSimpleAdaTransaction, SubmitTransaction, ...)'
1729
+ key action : String(100);
1730
+
1731
+ @title : 'Calls'
1732
+ @description: 'Admitted calls (budget charged where the grant has one)'
1733
+ calls : Integer default 0;
1734
+
1735
+ @title : 'Refunded'
1736
+ @description: 'Admitted calls whose handler refused the input (400..428); their unit was given back'
1737
+ refunded : Integer default 0;
1738
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.1",
3
+ "version": "2.0.0-rc.11",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -33,6 +33,7 @@
33
33
  "@harmoniclabs/cbor": "^2.0.1",
34
34
  "@harmoniclabs/crypto": "^0.3.0",
35
35
  "@harmoniclabs/uint8array-utils": "^1.0.4",
36
+ "@odatano/cap-auth": "^0.1.0",
36
37
  "@sap/xssec": "^4",
37
38
  "axios": "^1.18.0",
38
39
  "bech32": "^2.0.0",
@@ -45,7 +46,7 @@
45
46
  "axios": "^1.18.0",
46
47
  "esbuild": "0.28.1",
47
48
  "form-data": "^4.0.6",
48
- "fast-uri": "^3.1.5",
49
+ "fast-uri": "^3.1.7",
49
50
  "ws": "7.5.11",
50
51
  "@sap/approuter": {
51
52
  "body-parser": "^2.2.3"
@@ -55,6 +56,7 @@
55
56
  "@cap-js/cds-test": "^0.4.1",
56
57
  "@cap-js/cds-typer": "^0.40.0",
57
58
  "@cap-js/cds-types": "^0.18.0",
59
+ "@cap-js/postgres": "^3.1.1",
58
60
  "@cap-js/sqlite": "^3",
59
61
  "@sap/cds": "^10",
60
62
  "@sap/cds-dk": "^10",
@@ -95,6 +97,9 @@
95
97
  "kind": "sqlite",
96
98
  "credentials": {
97
99
  "url": "db.sqlite"
100
+ },
101
+ "client": {
102
+ "timeout": 5000
98
103
  }
99
104
  },
100
105
  "[production]": {
@@ -141,7 +146,8 @@
141
146
  "pretest:unit": "npm run cds:types",
142
147
  "test:unit": "vitest run --project unit",
143
148
  "watch-odatano": "cds watch --open odatano/index.html?sap-ui-xx-viewCache=false --livereload false",
144
- "watch-wallet": "cds watch --open wallet/webapp/index.html"
149
+ "watch-wallet": "cds watch --open wallet/webapp/index.html",
150
+ "release:check": "node scripts/release-check.mjs"
145
151
  },
146
152
  "sapux": [
147
153
  "app/odatano"
package/src/index.d.ts CHANGED
@@ -4,6 +4,12 @@ export { CardanoIndexer } from '../srv/blockchain/cardano-indexer';
4
4
  export { CardanoTransactionBuilder } from '../srv/blockchain/cardano-tx-builder';
5
5
  export { getAppContext, getCardanoIndexer, getCardanoClient, getCardanoTxBuilder, loadConfigFromEnv, loadHsmConfigFromEnv, loadCrawlerConfigFromEnv, startCrawlerIfConfigured, loadWalletWorkerConfigFromEnv, startWalletWorkerIfConfigured, shutdownAppContext, } from '../srv/server';
6
6
  export { getHsmSigner } from '../srv/blockchain/signing/hsm-signer';
7
+ export { issueAgentGrant, updateAgentGrant, rotateAgentGrantToken, revokeAgentGrantById, getGrantUsage, resolveUsageWindow, hashAgentToken, AGENT_TOKEN_HEADER, AGENT_TOKEN_PREFIX, AGENT_ROLE, AGENT_ALLOWLISTABLE_ACTIONS, AGENT_ALWAYS_ALLOWED_EVENTS, } from '../srv/utils/agent-grants';
8
+ export type { IssueAgentGrantInput, IssuedAgentGrant, AgentGrantStatus, UpdateAgentGrantInput, UpdateAgentGrantResult, RotatedAgentGrant, AgentGrantUsage, GrantUsageCall, UsageWindow, } from '../srv/utils/agent-grants';
9
+ export { registerTransportLane } from '@odatano/cap-auth';
10
+ export type { TransportLane, LaneOutcome } from '@odatano/cap-auth';
11
+ export { loadAgentGrantsConfig } from '../srv/utils/agent-grants-config';
12
+ export type { AgentGrantsConfig } from '../srv/utils/agent-grants-config';
7
13
  export type { HsmConfig, HsmSignResult } from '../srv/utils/types';
8
14
  export { parseTransaction } from '../srv/cbor';
9
15
  export type { ParsedTransaction, ParsedInput, ParsedOutput, ParsedAsset, ParsedWitnesses, } from '../srv/cbor';
package/src/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.parseTransaction = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
39
+ exports.parseTransaction = exports.loadAgentGrantsConfig = exports.registerTransportLane = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
40
40
  exports.initialize = initialize;
41
41
  exports.shutdown = shutdown;
42
42
  exports.getStatus = getStatus;
@@ -65,6 +65,26 @@ Object.defineProperty(exports, "shutdownAppContext", { enumerable: true, get: fu
65
65
  // Re-export HSM signer for programmatic access
66
66
  var hsm_signer_1 = require("../srv/blockchain/signing/hsm-signer");
67
67
  Object.defineProperty(exports, "getHsmSigner", { enumerable: true, get: function () { return hsm_signer_1.getHsmSigner; } });
68
+ // Agent grants (v2.0, AGENT_GRANTS_DESIGN.md): the programmatic seams other
69
+ // packages build on — @odatano/x402 sells grants through issueAgentGrant and
70
+ // adds its payment lane through registerTransportLane.
71
+ var agent_grants_1 = require("../srv/utils/agent-grants");
72
+ Object.defineProperty(exports, "issueAgentGrant", { enumerable: true, get: function () { return agent_grants_1.issueAgentGrant; } });
73
+ Object.defineProperty(exports, "updateAgentGrant", { enumerable: true, get: function () { return agent_grants_1.updateAgentGrant; } });
74
+ Object.defineProperty(exports, "rotateAgentGrantToken", { enumerable: true, get: function () { return agent_grants_1.rotateAgentGrantToken; } });
75
+ Object.defineProperty(exports, "revokeAgentGrantById", { enumerable: true, get: function () { return agent_grants_1.revokeAgentGrantById; } });
76
+ Object.defineProperty(exports, "getGrantUsage", { enumerable: true, get: function () { return agent_grants_1.getGrantUsage; } });
77
+ Object.defineProperty(exports, "resolveUsageWindow", { enumerable: true, get: function () { return agent_grants_1.resolveUsageWindow; } });
78
+ Object.defineProperty(exports, "hashAgentToken", { enumerable: true, get: function () { return agent_grants_1.hashAgentToken; } });
79
+ Object.defineProperty(exports, "AGENT_TOKEN_HEADER", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_HEADER; } });
80
+ Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_PREFIX; } });
81
+ Object.defineProperty(exports, "AGENT_ROLE", { enumerable: true, get: function () { return agent_grants_1.AGENT_ROLE; } });
82
+ Object.defineProperty(exports, "AGENT_ALLOWLISTABLE_ACTIONS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALLOWLISTABLE_ACTIONS; } });
83
+ Object.defineProperty(exports, "AGENT_ALWAYS_ALLOWED_EVENTS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALWAYS_ALLOWED_EVENTS; } });
84
+ var cap_auth_1 = require("@odatano/cap-auth");
85
+ Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return cap_auth_1.registerTransportLane; } });
86
+ var agent_grants_config_1 = require("../srv/utils/agent-grants-config");
87
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_1.loadAgentGrantsConfig; } });
68
88
  // Re-export pure CBOR utilities (no CAP round-trip needed)
69
89
  var cbor_1 = require("../srv/cbor");
70
90
  Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return cbor_1.parseTransaction; } });
package/src/plugin.js CHANGED
@@ -52,32 +52,46 @@ if (!cds_1.default.env.requires) {
52
52
  if (!cds_1.default.env.requires.kinds) {
53
53
  cds_1.default.env.requires.kinds = {};
54
54
  }
55
+ /** The schema and the six CDS services this package ships, package-qualified. */
56
+ const PLUGIN_MODEL = [
57
+ '@odatano/core/db/schema',
58
+ '@odatano/core/srv/cardano-service',
59
+ '@odatano/core/srv/cardano-tx-service',
60
+ '@odatano/core/srv/cardano-sign-service',
61
+ '@odatano/core/srv/cardano-indexer-service',
62
+ '@odatano/core/srv/cardano-worker-service',
63
+ '@odatano/core/srv/cardano-agent-service'
64
+ ];
65
+ /** Relative `@impl` values used in the CDS files (rewritten in plugin mode, see below). */
66
+ const IMPL_PATHS = [
67
+ 'srv/cardano-service',
68
+ 'srv/cardano-tx-service',
69
+ 'srv/cardano-sign-service',
70
+ 'srv/cardano-indexer-service',
71
+ 'srv/cardano-worker-service',
72
+ 'srv/cardano-agent-service'
73
+ ];
55
74
  cds_1.default.env.requires.kinds['odatano-core'] = {
56
75
  impl: '@odatano/core',
57
- model: [
58
- '@odatano/core/db/schema',
59
- '@odatano/core/srv/cardano-service',
60
- '@odatano/core/srv/cardano-tx-service',
61
- '@odatano/core/srv/cardano-sign-service',
62
- '@odatano/core/srv/cardano-indexer-service',
63
- '@odatano/core/srv/cardano-worker-service'
64
- ]
76
+ model: [...PLUGIN_MODEL]
65
77
  };
66
78
  // CRITICAL: Also set model directly on the requires entry.
67
79
  // CAP's _link_required_services() merges kind→requires BEFORE cds-plugin.js runs,
68
80
  // so the model array on the kind is never merged. Set it directly.
69
81
  const req = cds_1.default.env.requires['odatano-core'];
70
82
  if (req) {
71
- req.model = [
72
- '@odatano/core/db/schema',
73
- '@odatano/core/srv/cardano-service',
74
- '@odatano/core/srv/cardano-tx-service',
75
- '@odatano/core/srv/cardano-sign-service',
76
- '@odatano/core/srv/cardano-indexer-service',
77
- '@odatano/core/srv/cardano-worker-service'
78
- ];
83
+ req.model = [...PLUGIN_MODEL];
79
84
  }
80
85
  logger.debug('Plugin registered');
86
+ /**
87
+ * Agent grants (AGENT_GRANTS_DESIGN.md). Off by default; switched on by
88
+ * cds.requires.odatano-core.agentGrants.enabled / AGENT_GRANTS_ENABLED=true.
89
+ * Has to run at plugin load, before CAP builds its middlewares (the auth impl
90
+ * is swapped here). srv/server.ts makes the same call for standalone mode, where
91
+ * this file is never loaded; the call is idempotent and never throws.
92
+ */
93
+ require('../srv/utils/agent-grants-config')
94
+ .activateAgentGrants();
81
95
  /**
82
96
  * Rewrite @impl paths for plugin mode.
83
97
  * CDS files use relative @impl (e.g. 'srv/cardano-service') which resolves from cds.root.
@@ -90,20 +104,9 @@ cds_1.default.on('loaded', (model) => {
90
104
  return;
91
105
  const defs = model.definitions ?? {};
92
106
  for (const def of Object.values(defs)) {
93
- if (def['@impl'] === 'srv/cardano-service') {
94
- def['@impl'] = '@odatano/core/srv/cardano-service';
95
- }
96
- else if (def['@impl'] === 'srv/cardano-tx-service') {
97
- def['@impl'] = '@odatano/core/srv/cardano-tx-service';
98
- }
99
- else if (def['@impl'] === 'srv/cardano-sign-service') {
100
- def['@impl'] = '@odatano/core/srv/cardano-sign-service';
101
- }
102
- else if (def['@impl'] === 'srv/cardano-indexer-service') {
103
- def['@impl'] = '@odatano/core/srv/cardano-indexer-service';
104
- }
105
- else if (def['@impl'] === 'srv/cardano-worker-service') {
106
- def['@impl'] = '@odatano/core/srv/cardano-worker-service';
107
+ const impl = def['@impl'];
108
+ if (impl && IMPL_PATHS.includes(impl)) {
109
+ def['@impl'] = `@odatano/core/${impl}`;
107
110
  }
108
111
  }
109
112
  });
@@ -274,16 +274,7 @@ class BlockfrostBackend {
274
274
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
275
275
  const a = await this.api.assetsById(unit);
276
276
  const reg = a.metadata ?? null;
277
- const decodeUtf8 = (hex) => {
278
- if (!hex)
279
- return null;
280
- try {
281
- return Buffer.from(hex, 'hex').toString('utf8');
282
- }
283
- catch {
284
- return null;
285
- }
286
- };
277
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
287
278
  return {
288
279
  unit: a.asset,
289
280
  policyId: a.policy_id,
@@ -519,16 +519,7 @@ class KoiosBackend {
519
519
  const onchainMetadata = mintMeta && typeof mintMeta === 'object'
520
520
  ? (mintMeta['721'] ?? mintMeta)
521
521
  : null;
522
- const decodeUtf8 = (hex) => {
523
- if (!hex)
524
- return null;
525
- try {
526
- return Buffer.from(hex, 'hex').toString('utf8');
527
- }
528
- catch {
529
- return null;
530
- }
531
- };
522
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
532
523
  const mintCnt = typeof a.mint_cnt === 'number' ? a.mint_cnt : 0;
533
524
  const burnCnt = typeof a.burn_cnt === 'number' ? a.burn_cnt : 0;
534
525
  return {
@@ -1,6 +1,16 @@
1
1
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
2
2
  import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint } from './cardano-backend';
3
3
  import { Network } from '../cardano-client';
4
+ /**
5
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
6
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
7
+ * 0x3 = script hash. The validators already enforce HRP + length before the
8
+ * request reaches a backend, so this only has to split the payload.
9
+ */
10
+ export declare function decodeDrepId(drepId: string): {
11
+ hashHex: string;
12
+ isScript: boolean;
13
+ };
4
14
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
5
15
  export declare function resolveOgmiosTip(tip: 'origin' | {
6
16
  slot: number;
@@ -107,11 +117,21 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
107
117
  */
108
118
  getTransactionMetadata(_tx_hash: string): Promise<MetadataLabelTx[]>;
109
119
  /**
110
- * Get specific Drep Data (not supported for Ogmios)
111
- * @param _drepId drep id
120
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
121
+ *
122
+ * The client package (6.14) ships the schema types but no wrapper for this query,
123
+ * so it goes through the exported `Method()` primitive on our interaction context —
124
+ * the same building block the client uses for `stakePools` & co.
125
+ *
126
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
127
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
128
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
129
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
130
+ *
131
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
112
132
  * @returns {Promise<DrepData>} drep data
113
133
  */
114
- getDrep(_drepId: string): Promise<DrepData>;
134
+ getDrep(drepId: string): Promise<DrepData>;
115
135
  /**
116
136
  * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
117
137
  * @param _unit asset unit (policyId + assetNameHex)
@@ -233,6 +253,10 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
233
253
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
234
254
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
235
255
  * the network's Shelley anchor (same config the tx-builder uses).
256
+ *
257
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
258
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
259
+ * corrects both the transaction and this sum in applyCollateralFees().
236
260
  */
237
261
  private mapOgmiosBlock;
238
262
  /**
@@ -240,7 +264,8 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
240
264
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
241
265
  * resolved downstream by the indexer). `spends` selects the ledger-applied
242
266
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
243
- * its collateral-return output, never its declared regular inputs/outputs.
267
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
268
+ * follows that partition too — see the `spendsCollaterals` branch below.
244
269
  */
245
270
  private mapOgmiosTx;
246
271
  }
@@ -4,13 +4,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OgmiosBackend = void 0;
7
+ exports.decodeDrepId = decodeDrepId;
7
8
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
9
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
10
11
  const node_http_1 = __importDefault(require("node:http"));
11
12
  const client_1 = require("@cardano-ogmios/client");
13
+ const bech32_1 = require("bech32");
12
14
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
15
  const errors_1 = require("../../utils/errors");
16
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
14
17
  const mappers_1 = require("../../utils/mappers");
15
18
  const const_1 = require("../../utils/const");
16
19
  const logger = cds_1.default.log('OgmiosBackend');
@@ -63,6 +66,23 @@ function ogmiosValueToLovelaceString(value) {
63
66
  const lovelace = value.ada?.lovelace;
64
67
  return lovelace === undefined ? '0' : String(lovelace);
65
68
  }
69
+ /**
70
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
71
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
72
+ * 0x3 = script hash. The validators already enforce HRP + length before the
73
+ * request reaches a backend, so this only has to split the payload.
74
+ */
75
+ function decodeDrepId(drepId) {
76
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
77
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
78
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
79
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
80
+ }
81
+ return {
82
+ hashHex: bytes.subarray(1).toString('hex'),
83
+ isScript: (bytes[0] & 0x0f) === 0x03,
84
+ };
85
+ }
66
86
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
87
  function resolveOgmiosTip(tip) {
68
88
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -88,7 +108,8 @@ class OgmiosBackend {
88
108
  'getTransaction',
89
109
  'getTransactionMetadata',
90
110
  'getAddressTransactions',
91
- 'getDrep',
111
+ // getDrep is NOT listed: served from the live ledger state via
112
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
113
  'getAssetInfo',
93
114
  'getAddress',
94
115
  'getNetworkInformation',
@@ -305,13 +326,60 @@ class OgmiosBackend {
305
326
  }, this.name);
306
327
  }
307
328
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
329
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
330
+ *
331
+ * The client package (6.14) ships the schema types but no wrapper for this query,
332
+ * so it goes through the exported `Method()` primitive on our interaction context —
333
+ * the same building block the client uses for `stakePools` & co.
334
+ *
335
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
336
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
337
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
338
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
339
+ *
340
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
310
341
  * @returns {Promise<DrepData>} drep data
311
342
  */
312
- async getDrep(_drepId) {
343
+ async getDrep(drepId) {
313
344
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
345
+ await this.ensureConnected();
346
+ if (!this.context) {
347
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
348
+ }
349
+ const { hashHex, isScript } = decodeDrepId(drepId);
350
+ const [summaries, currentEpoch] = await Promise.all([
351
+ (0, client_1.Method)({
352
+ method: 'queryLedgerState/delegateRepresentatives',
353
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
354
+ }, {
355
+ handler: (response, resolve, reject) => {
356
+ if (response.error) {
357
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
358
+ }
359
+ else {
360
+ resolve(Array.isArray(response.result) ? response.result : []);
361
+ }
362
+ },
363
+ }, this.context),
364
+ this.stateQueryClient.epoch(),
365
+ ]);
366
+ // Filter by id: the query is already credential-scoped, but never trust a
367
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
368
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
369
+ if (!drep)
370
+ throw new errors_1.NotFoundError('Drep', this.name);
371
+ const mandateEpoch = drep.mandate?.epoch;
372
+ return {
373
+ drepId,
374
+ hex: hashHex,
375
+ amount: ogmiosValueToLovelaceString(drep.stake),
376
+ hasScript: isScript || drep.from === 'script',
377
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0,
378
+ // matching what the Koios mapper does since its schema change.
379
+ lastActiveEpoch: 0,
380
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
381
+ retired: false,
382
+ };
315
383
  }, this.name);
316
384
  }
317
385
  /**
@@ -731,6 +799,14 @@ class OgmiosBackend {
731
799
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
800
  }
733
801
  };
802
+ // A frame the client's own parser cannot handle never reaches this class: it throws
803
+ // inside the library's socket handler, where nothing awaits it, and ends the process.
804
+ // The guard intercepts that and routes the unusable frame here instead, as an ordinary
805
+ // stream error naming the block. Installed per open (one stream at a time) and
806
+ // idempotent, so reopening only swaps the callback.
807
+ (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
808
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
809
+ });
734
810
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
811
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
812
  void reportStreamError(err);
@@ -837,6 +913,10 @@ class OgmiosBackend {
837
913
  * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
838
914
  * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
839
915
  * the network's Shelley anchor (same config the tx-builder uses).
916
+ *
917
+ * A phase-2 failure whose body declares no `total_collateral` still carries its
918
+ * declared fee here, because the collateral inputs are not resolved yet. The indexer
919
+ * corrects both the transaction and this sum in applyCollateralFees().
840
920
  */
841
921
  mapOgmiosBlock(block) {
842
922
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
@@ -865,7 +945,8 @@ class OgmiosBackend {
865
945
  * and metadata are mapped fully; inputs are kept as bare references (address/amount
866
946
  * resolved downstream by the indexer). `spends` selects the ledger-applied
867
947
  * partition: a phase-2-invalid transaction consumes collaterals and creates only
868
- * its collateral-return output, never its declared regular inputs/outputs.
948
+ * its collateral-return output, never its declared regular inputs/outputs. The fee
949
+ * follows that partition too — see the `spendsCollaterals` branch below.
869
950
  */
870
951
  mapOgmiosTx(tx, block, index) {
871
952
  const mapInput = (input, flags = {}) => ({
@@ -905,13 +986,21 @@ class OgmiosBackend {
905
986
  json: v.json,
906
987
  }))
907
988
  : [];
989
+ // A phase-2 failure does not pay the fee declared in the body — the ledger consumes
990
+ // the collateral instead. `total_collateral` is that amount and the ledger enforces
991
+ // the equality, so prefer it; the body omits it often enough that the indexer derives
992
+ // the rest from the resolved collateral inputs once it has them.
993
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
994
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
908
995
  return {
909
996
  hash: tx.id,
910
997
  blockHash: block.id,
911
998
  blockHeight: block.height,
912
999
  slot: block.slot,
913
1000
  index,
914
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
1001
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1002
+ spendsCollaterals,
1003
+ totalCollateral,
915
1004
  deposit: '0',
916
1005
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
1006
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
3
+ *
4
+ * `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
5
+ * `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
6
+ * `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
7
+ * walks the parsed tree recursively. A native script nests one JSON object per clause, and
8
+ * nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
9
+ * expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
10
+ *
11
+ * That is not a theoretical shape. Preprod block 5183974 carries a native script nested
12
+ * 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
13
+ * The block is 43 kB on chain and 205 kB as a chain-sync frame.
14
+ *
15
+ * The crash is fatal rather than merely annoying, because of where the parse happens
16
+ * (`ChainSynchronization/Client.js`):
17
+ *
18
+ * socket.on('message', async (message) => {
19
+ * await responseHandler(util_1.safeJSON.parse(message));
20
+ * });
21
+ *
22
+ * `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
23
+ * the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
24
+ * crawler's poison-block latch cannot help: it guards the persist path, and the server is
25
+ * gone long before a block reaches it. Docker restarts, the crawler resumes at the same
26
+ * block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
27
+ *
28
+ * This guard wraps `safeJSON.parse` (a public export of the client package) so that the
29
+ * fast path is untouched and only an overflowing frame takes the recovery route:
30
+ *
31
+ * 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
32
+ * 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
33
+ * hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
34
+ * is no longer a limit. `sanitize` is skipped, because it would overflow on the very
35
+ * same structure;
36
+ * 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
37
+ * The guard never throws, because throwing here is what kills the process.
38
+ *
39
+ * Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
40
+ * `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
41
+ * `JSON.parse` completes in 17 ms.
42
+ *
43
+ * Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
44
+ * consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
45
+ */
46
+ import { safeJSON } from '@cardano-ogmios/client';
47
+ /** A frame the guard could not turn into an object at all. */
48
+ export interface UnparseableFrame {
49
+ /** Block height, when it could be read off the raw text; null when even that failed. */
50
+ height: number | null;
51
+ /** Block id (hash), when readable. */
52
+ id: string | null;
53
+ reason: string;
54
+ bytes: number;
55
+ }
56
+ /**
57
+ * Integers outside the safe double range, written into JSON strings so that plain
58
+ * `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
59
+ * never recursing, so it is immune to the nesting that sent us here in the first place.
60
+ *
61
+ * Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
62
+ * names) are skipped, and so are floats and exponents, which are doubles by nature and have
63
+ * no exact integer to preserve.
64
+ */
65
+ export declare function widenBigIntegers(text: string): string;
66
+ /**
67
+ * Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
68
+ * report callback, so reopening the chain-sync stream never stacks wrappers.
69
+ *
70
+ * @param onUnparseableFrame called when a frame survives neither parser. The guard returns
71
+ * a sentinel instead of throwing, so the caller owns what happens next — the stream
72
+ * itself stalls, because the client drops anything that is not a nextBlock response.
73
+ */
74
+ export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): void;
75
+ /** Tests only — drop the wrapper so each case starts from the untouched client. */
76
+ export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
77
+ //# sourceMappingURL=ogmios-frame-guard.d.ts.map