@odatano/core 2.0.0-rc.5 → 2.0.0-rc.7

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/README.md CHANGED
@@ -1,167 +1,185 @@
1
- ![alt text](docs/assets/odatano_logo/logo_odatano_white.png)
2
-
3
- # Enterprise OData Services for the Cardano Blockchain
4
-
5
- Funded by [Cardano Catalyst Fund 14](https://projectcatalyst.io/funds/14/sponsored-by-leftovers/sap-cardano-odata-v4-api-with-cap-and-sap-cardano-sdk) all four milestones completed and approved (April 2026).
6
-
7
- **ODATANO** is an SAP CAP–based service that exposes the Cardano blockchain via a standardized **OData V4** interface, enabling enterprise-grade read and write access with native transaction building.
8
-
9
- [![Tests](https://github.com/ODATANO/ODATANO/actions/workflows/test.yaml/badge.svg)](https://github.com/ODATANO/ODATANO/actions/workflows/test.yaml)
10
- [![Coverage](https://codecov.io/gh/ODATANO/ODATANO/branch/main/graph/badge.svg)](https://codecov.io/gh/ODATANO/ODATANO)
11
- [![npm version](https://img.shields.io/npm/v/@odatano/core?logo=npm)](https://www.npmjs.com/package/@odatano/core)
12
- [![npm downloads](https://img.shields.io/npm/dt/@odatano/core?logo=npm&label=downloads&color=blue)](https://www.npmjs.com/package/@odatano/core)
13
- [![License](https://img.shields.io/badge/license-Apache%202.0-yellow)](LICENSE)
14
-
15
-
16
- ## Quick Start
17
-
18
- ### As CAP Plugin (recommended)
19
-
20
- Add ODATANO to any existing SAP CAP project:
21
-
22
- ```bash
23
- npm install @odatano/core @cap-js/sqlite
24
- ```
25
-
26
- ```json
27
- {
28
- "cds": {
29
- "requires": {
30
- "db": { "kind": "sqlite" },
31
- "odatano-core": {
32
- "network": "preview",
33
- "backends": ["blockfrost"]
34
- }
35
- }
36
- }
37
- }
38
- ```
39
-
40
- Put your API key in a `.env` file in the project root (loaded automatically by `cds serve` / `cds watch`) — don't commit it to `package.json`:
41
-
42
- ```bash
43
- # .env
44
- BLOCKFROST_API_KEY=preview_your_api_key_here
45
- ```
46
-
47
- ```bash
48
- cds deploy --to sqlite
49
- cds serve
50
- ```
51
-
52
- > Config in `cds.requires.odatano-core` takes precedence over environment
53
- > variables; a `blockfrostApiKey` set there would override the `.env` value.
54
-
55
- > **Self-hosted Blockfrost-compatible node?** (Dolos MiniBF, Demeter Self-Hosted)
56
- > Set `blockfrostCustomBackend` to the node's base URL (e.g. `http://localhost:3010/api/v0`).
57
- > When set, `blockfrostApiKey` becomes optional. See the [Backend Configuration Guide](docs/guides/BACKEND_CONFIGURATION.md#self-hosted-blockfrost-compatible-backends).
58
-
59
- ### Standalone
60
-
61
- Run ODATANO as a self-contained service (no host CAP project needed):
62
-
63
- ```bash
64
- git clone https://github.com/ODATANO/ODATANO && cd ODATANO
65
- npm ci
66
- cp .env.example .env # set BLOCKFROST_API_KEY, NETWORK, BACKENDS
67
- cds deploy --to sqlite
68
- cds serve
69
- ```
70
-
71
- Or with Docker — this brings up a local **cardano-node + Ogmios + ODATANO** stack
72
- (Preview), with the service pre-wired to the local Ogmios backend:
73
-
74
- ```bash
75
- docker compose up -d # full stack
76
- docker compose up -d cardano-node ogmios # just the chain backend (pre-sync)
77
- docker compose logs -f ogmios # watch sync (/health: 202 syncing, 200 near tip)
78
- ```
79
-
80
- > First sync from genesis takes hours; the node DB persists in a Docker volume so
81
- > restarts resume. Until Ogmios catches up, historical queries fall back to
82
- > Blockfrost (set `BLOCKFROST_API_KEY`).
83
-
84
- Service available at `http://localhost:4004`. See the [Quick Start Guide](docs/QUICK_START.md#local-ogmios--cardano-node-docker) for the local Ogmios stack and full details.
85
-
86
- ## Dev Mode: Mocked Authentication
87
-
88
- > **Heads-up.** `cds serve` uses CAP's mocked auth: `@requires: 'authenticated-user'` accepts any Basic-Auth header against a mock user (`alice`, `bob`, …) — passwords are not checked. Anonymous requests get 401, but anyone reaching the port can authenticate.
89
- >
90
- > Production needs the `[production]` profile (`NODE_ENV=production`), which switches to `auth: xsuaa`. Don't expose a dev-mode instance. See the [Security Guide](docs/guides/SECURITY_GUIDE.md#authentication-xsuaa).
91
-
92
- ## Services
93
-
94
- | Service | Path | Purpose |
95
- |---|---|---|
96
- | CardanoODataService | `/odata/v4/cardano-odata/` | Read blockchain data (20 entities, 19 actions) |
97
- | CardanoTransactionService | `/odata/v4/cardano-transaction/` | Build & submit transactions (13 actions) |
98
- | CardanoSignService | `/odata/v4/cardano-sign/` | External signing + HSM (9 actions) |
99
- | CardanoIndexerService | `/odata/v4/cardano-indexer/` | Chain crawler / pre-sync control (v2.0, off by default) |
100
- | CardanoWorkerService | `/odata/v4/cardano-worker/` | Asynchronous wallet jobs (v2.0, off by default) |
101
- | CardanoAgentService | `/odata/v4/cardano-agent/` | Agent grants: scoped bearer tokens for agents (v2.0, off by default) |
102
-
103
- Both v2.0 services also publish **CAP events**, so a consumer can subscribe instead of polling —
104
- in-process, no broker required:
105
-
106
- ```js
107
- (await cds.connect.to('CardanoWorkerService')).on('jobConfirmed', ({ data }) => …)
108
- (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
109
- ```
110
-
111
- ## Agent grants (v2.0, off by default)
112
-
113
- Hand an agent a **scoped, budgeted token** instead of a user. Design and rationale:
114
- [AGENT_GRANTS_DESIGN.md](AGENT_GRANTS_DESIGN.md).
115
-
116
- ```bash
117
- AGENT_GRANTS_ENABLED=true # or cds.requires.odatano-core.agentGrants.enabled
118
- AGENT_GRANTS_DELEGATE=mocked # CAP auth kind that keeps authenticating non-token requests (default: configured kind)
119
- ```
120
-
121
- 1. An **Admin** issues a grant (`POST /odata/v4/cardano-agent/CreateAgentGrant`): an allow list of
122
- actions, optionally a worker `walletId` (required for `SubmitWalletJob`/`CancelJob`), allowed job
123
- kinds, a daily budget and an expiry. The response carries the token `odat_…` **once**; the
124
- server stores only its SHA-256.
125
- 2. The agent sends `x-agent-token: odat_…` on any of the six service paths. It runs as the principal
126
- `agent:<grantId>` with the single role `agent-grant`, never as the operator: every
127
- `@requires: 'Admin'` surface (pause/resume, HSM signing, grant administration) refuses it by
128
- construction. Reads and compute-only actions are always allowed; allow-listed actions each cost
129
- one budget unit per UTC day (a build is the service an agent buys); everything else is 403.
130
- Wallet jobs are pinned to the grant's wallet and visible only to the grant that queued them.
131
- 3. `GET /odata/v4/cardano-agent/GetGrantStatus()` tells the agent what it may do and how much budget
132
- is left; `RevokeAgentGrant` turns the token into an unknown token immediately.
133
-
134
- Grantable: `Build*`, `SetCollateral`, `CreateSigningRequest`, `VerifySignature`, `Submit*`,
135
- `CheckSubmissionStatus`, `SubmitWalletJob`, `CancelJob`. Never: `SignWithHsm*`, `Pause*`/`Resume*`,
136
- `pauseCrawler`/`resumeCrawler`, grant administration.
137
-
138
- Programmatic seams for other packages (`@odatano/x402` sells grants against a 402 payment):
139
- `issueAgentGrant()`, `revokeAgentGrantById()`, `registerTransportLane()` from `@odatano/core`.
140
-
141
- ## Requirements
142
-
143
- - **Node.js >= 22.5** and **@sap/cds >= 10** (peer dependency). CAP 9 hosts cannot load `@odatano/core@2`.
144
- - Upgrading a consumer from 1.x: run **`cds deploy`**. 2.0 adds four tables (`CardanoSyncState`,
145
- `CardanoReorgLog`, `CardanoWorkerWallets`, `CardanoWalletJobs`) plus a `dedupKey` column; without
146
- the redeploy the new services answer `no such table` while the old ones keep working.
147
-
148
- ## Documentation
149
-
150
- | Guide | Description |
151
- |-------|-------------|
152
- | [Quick Start](docs/QUICK_START.md) | Get running in 5 minutes |
153
- | [User Guide](docs/guides/USER_GUIDE.md) | API usage, entities, and examples |
154
- | [Developer Guide](docs/guides/DEVELOPER_GUIDE.md) | Architecture and development |
155
- | [Transaction Workflow](docs/guides/TRANSACTION_WORKFLOW.md) | Build → Sign → Submit flow |
156
- | [Security Guide](docs/guides/SECURITY_GUIDE.md) | Authentication, signing security, HSM |
157
- | [Docker Deployment](docs/guides/DOCKER_DEPLOYMENT.md) | Container deployment |
158
-
159
- ## License
160
-
161
- Apache License 2.0 - see [LICENSE](LICENSE)
162
-
163
- ## Support
164
-
165
- - **Issues**: [GitHub Issues](https://github.com/ODATANO/ODATANO/issues)
166
- - **Project Lead**: Max Weber
167
- - **Contact**: info@odatano.dev
1
+ ![alt text](docs/assets/odatano_logo/logo_odatano_white.png)
2
+
3
+ # Enterprise OData Services for the Cardano Blockchain
4
+
5
+ Funded by [Cardano Catalyst Fund 14](https://projectcatalyst.io/funds/14/sponsored-by-leftovers/sap-cardano-odata-v4-api-with-cap-and-sap-cardano-sdk) all four milestones completed and approved (April 2026).
6
+
7
+ **ODATANO** is an SAP CAP–based service that exposes the Cardano blockchain via a standardized **OData V4** interface, enabling enterprise-grade read and write access with native transaction building.
8
+
9
+ [![Tests](https://github.com/ODATANO/ODATANO/actions/workflows/test.yaml/badge.svg)](https://github.com/ODATANO/ODATANO/actions/workflows/test.yaml)
10
+ [![Coverage](https://codecov.io/gh/ODATANO/ODATANO/branch/main/graph/badge.svg)](https://codecov.io/gh/ODATANO/ODATANO)
11
+ [![npm version](https://img.shields.io/npm/v/@odatano/core?logo=npm)](https://www.npmjs.com/package/@odatano/core)
12
+ [![npm downloads](https://img.shields.io/npm/dt/@odatano/core?logo=npm&label=downloads&color=blue)](https://www.npmjs.com/package/@odatano/core)
13
+ [![License](https://img.shields.io/badge/license-Apache%202.0-yellow)](LICENSE)
14
+
15
+
16
+ ## Quick Start
17
+
18
+ ### As CAP Plugin (recommended)
19
+
20
+ Add ODATANO to any existing SAP CAP project:
21
+
22
+ ```bash
23
+ npm install @odatano/core @cap-js/sqlite
24
+ ```
25
+
26
+ ```json
27
+ {
28
+ "cds": {
29
+ "requires": {
30
+ "db": { "kind": "sqlite" },
31
+ "odatano-core": {
32
+ "network": "preview",
33
+ "backends": ["blockfrost"]
34
+ }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ Put your API key in a `.env` file in the project root (loaded automatically by `cds serve` / `cds watch`) — don't commit it to `package.json`:
41
+
42
+ ```bash
43
+ # .env
44
+ BLOCKFROST_API_KEY=preview_your_api_key_here
45
+ ```
46
+
47
+ ```bash
48
+ cds deploy --to sqlite
49
+ cds serve
50
+ ```
51
+
52
+ > Config in `cds.requires.odatano-core` takes precedence over environment
53
+ > variables; a `blockfrostApiKey` set there would override the `.env` value.
54
+
55
+ > **Self-hosted Blockfrost-compatible node?** (Dolos MiniBF, Demeter Self-Hosted)
56
+ > Set `blockfrostCustomBackend` to the node's base URL (e.g. `http://localhost:3010/api/v0`).
57
+ > When set, `blockfrostApiKey` becomes optional. See the [Backend Configuration Guide](docs/guides/BACKEND_CONFIGURATION.md#self-hosted-blockfrost-compatible-backends).
58
+
59
+ ### Standalone
60
+
61
+ Run ODATANO as a self-contained service (no host CAP project needed):
62
+
63
+ ```bash
64
+ git clone https://github.com/ODATANO/ODATANO && cd ODATANO
65
+ npm ci
66
+ cp .env.example .env # set BLOCKFROST_API_KEY, NETWORK, BACKENDS
67
+ cds deploy --to sqlite
68
+ cds serve
69
+ ```
70
+
71
+ Or with Docker — this brings up a local **cardano-node + Ogmios + ODATANO** stack
72
+ (Preview), with the service pre-wired to the local Ogmios backend:
73
+
74
+ ```bash
75
+ docker compose up -d # full stack
76
+ docker compose up -d cardano-node ogmios # just the chain backend (pre-sync)
77
+ docker compose logs -f ogmios # watch sync (/health: 202 syncing, 200 near tip)
78
+ ```
79
+
80
+ > First sync from genesis takes hours; the node DB persists in a Docker volume so
81
+ > restarts resume. Until Ogmios catches up, historical queries fall back to
82
+ > Blockfrost (set `BLOCKFROST_API_KEY`).
83
+
84
+ Service available at `http://localhost:4004`. See the [Quick Start Guide](docs/QUICK_START.md#local-ogmios--cardano-node-docker) for the local Ogmios stack and full details.
85
+
86
+ ## Dev Mode: Mocked Authentication
87
+
88
+ > **Heads-up.** `cds serve` uses CAP's mocked auth: `@requires: 'authenticated-user'` accepts any Basic-Auth header against a mock user (`alice`, `bob`, …) — passwords are not checked. Anonymous requests get 401, but anyone reaching the port can authenticate.
89
+ >
90
+ > Production needs the `[production]` profile (`NODE_ENV=production`), which switches to `auth: xsuaa`. Don't expose a dev-mode instance. See the [Security Guide](docs/guides/SECURITY_GUIDE.md#authentication-xsuaa).
91
+
92
+ ## Services
93
+
94
+ | Service | Path | Purpose |
95
+ |---|---|---|
96
+ | CardanoODataService | `/odata/v4/cardano-odata/` | Read blockchain data (20 entities, 19 actions) |
97
+ | CardanoTransactionService | `/odata/v4/cardano-transaction/` | Build & submit transactions (13 actions) |
98
+ | CardanoSignService | `/odata/v4/cardano-sign/` | External signing + HSM (9 actions) |
99
+ | CardanoIndexerService | `/odata/v4/cardano-indexer/` | Chain crawler / pre-sync control (v2.0, off by default) |
100
+ | CardanoWorkerService | `/odata/v4/cardano-worker/` | Asynchronous wallet jobs (v2.0, off by default) |
101
+ | CardanoAgentService | `/odata/v4/cardano-agent/` | Agent grants: scoped bearer tokens for agents (v2.0, off by default) |
102
+
103
+ Both v2.0 services also publish **CAP events**, so a consumer can subscribe instead of polling —
104
+ in-process, no broker required:
105
+
106
+ ```js
107
+ (await cds.connect.to('CardanoWorkerService')).on('jobConfirmed', ({ data }) => …)
108
+ (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
109
+ ```
110
+
111
+ ## Agent grants (v2.0, off by default)
112
+
113
+ Hand an agent a **scoped, budgeted token** instead of a user.
114
+
115
+ ```bash
116
+ AGENT_GRANTS_ENABLED=true # or cds.requires.odatano-core.agentGrants.enabled
117
+ AGENT_GRANTS_DELEGATE=mocked # CAP auth kind that keeps authenticating non-token requests (default: configured kind)
118
+ AGENT_GRANT_ADMIN_RATE_LIMIT=10 # grant administration calls per principal per hour (or agentGrants.adminRateLimit)
119
+ ```
120
+
121
+ 1. An **Admin** issues a grant (`POST /odata/v4/cardano-agent/CreateAgentGrant`): an allow list of
122
+ actions, optionally a worker `walletId` (required for `SubmitWalletJob`/`CancelJob`), allowed job
123
+ kinds, a daily budget and an expiry. The response carries the token `odat_…` **once**; the
124
+ server stores only its SHA-256.
125
+ 2. The agent sends `x-agent-token: odat_…` on any of the six service paths. It runs as the principal
126
+ `agent:<grantId>` with the single role `agent-grant`, never as the operator: every
127
+ `@requires: 'Admin'` surface (pause/resume, HSM signing, grant administration) refuses it by
128
+ construction. Reads and compute-only actions are always allowed; allow-listed actions each cost
129
+ one budget unit per UTC day (a build is the service an agent buys); everything else is 403.
130
+ Wallet jobs are pinned to the grant's wallet and visible only to the grant that queued them.
131
+ 3. `GET /odata/v4/cardano-agent/GetGrantStatus()` tells the agent what it may do and how much budget
132
+ is left; `RevokeAgentGrant` turns the token into an unknown token immediately.
133
+ 4. Lifecycle (Admin, same semantics as NIGHTGATE's agent grants so a gateway drives both with one
134
+ code path): `UpdateAgentGrant` changes label, allow list, job kinds, daily budget or expiry
135
+ (absent = untouched, explicit `null` = cleared; the wallet binding is immutable, 409
136
+ `GRANT_REVOKED` on a revoked grant); `RotateAgentGrantToken` returns a fresh token once, the old
137
+ one is unknown from the next request; `GetGrantUsage(grantId, since, until)` lists admitted calls
138
+ per service and action over up to 366 days (an Admin for any grant, a token for its own). All
139
+ administration calls share the per-principal hourly rate limit above.
140
+
141
+ Grantable: `Build*`, `SetCollateral`, `CreateSigningRequest`, `VerifySignature`, `Submit*`,
142
+ `CheckSubmissionStatus`, `SubmitWalletJob`, `CancelJob`. Never: `SignWithHsm*`, `Pause*`/`Resume*`,
143
+ `pauseCrawler`/`resumeCrawler`, grant administration.
144
+
145
+ Programmatic seams for other packages (`@odatano/x402` sells grants against a 402 payment):
146
+ `issueAgentGrant()`, `updateAgentGrant()`, `rotateAgentGrantToken()`, `revokeAgentGrantById()`,
147
+ `getGrantUsage()`, `registerTransportLane()` from `@odatano/core`.
148
+
149
+ ## Liveness probe
150
+
151
+ `GET /odata/v4/cardano-indexer/getLiveness()` answers `200 { status: "alive", timestamp, uptime,
152
+ version, network }` **without credentials** (`@requires: 'any'`) as long as the process runs — no
153
+ backend or DB probe, no secrets. The Docker `HEALTHCHECK`, compose and upstream probes use it
154
+ instead of the service document, so a wrong operator password no longer reads as "ODATANO down".
155
+ Readiness (crawler, worker, backends) stays authenticated: `getStatus()`, `GetWorkerStatus()`,
156
+ `GetNetworkInformation`.
157
+
158
+ ## Requirements
159
+
160
+ - **Node.js >= 22.5** and **@sap/cds >= 10** (peer dependency). CAP 9 hosts cannot load `@odatano/core@2`.
161
+ - Upgrading a consumer from 1.x: run **`cds deploy`**. 2.0 adds six tables (`CardanoSyncState`,
162
+ `CardanoReorgLog`, `CardanoWorkerWallets`, `CardanoWalletJobs`, `CardanoAgentGrants`,
163
+ `CardanoAgentGrantUsage`) plus a `dedupKey` column; without the redeploy the new services answer
164
+ `no such table` while the old ones keep working.
165
+
166
+ ## Documentation
167
+
168
+ | Guide | Description |
169
+ |-------|-------------|
170
+ | [Quick Start](docs/QUICK_START.md) | Get running in 5 minutes |
171
+ | [User Guide](docs/guides/USER_GUIDE.md) | API usage, entities, and examples |
172
+ | [Developer Guide](docs/guides/DEVELOPER_GUIDE.md) | Architecture and development |
173
+ | [Transaction Workflow](docs/guides/TRANSACTION_WORKFLOW.md) | Build → Sign → Submit flow |
174
+ | [Security Guide](docs/guides/SECURITY_GUIDE.md) | Authentication, signing security, HSM |
175
+ | [Docker Deployment](docs/guides/DOCKER_DEPLOYMENT.md) | Container deployment |
176
+
177
+ ## License
178
+
179
+ Apache License 2.0 - see [LICENSE](LICENSE)
180
+
181
+ ## Support
182
+
183
+ - **Issues**: [GitHub Issues](https://github.com/ODATANO/ODATANO/issues)
184
+ - **Project Lead**: Max Weber
185
+ - **Contact**: info@odatano.dev
package/db/schema.cds CHANGED
@@ -1703,3 +1703,36 @@ entity CardanoAgentGrants {
1703
1703
  @description: 'Last request admitted under this token (updated at most once a minute)'
1704
1704
  lastUsedAt : Timestamp;
1705
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.5",
3
+ "version": "2.0.0-rc.7",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -95,6 +95,9 @@
95
95
  "kind": "sqlite",
96
96
  "credentials": {
97
97
  "url": "db.sqlite"
98
+ },
99
+ "client": {
100
+ "timeout": 5000
98
101
  }
99
102
  },
100
103
  "[production]": {
@@ -141,7 +144,8 @@
141
144
  "pretest:unit": "npm run cds:types",
142
145
  "test:unit": "vitest run --project unit",
143
146
  "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"
147
+ "watch-wallet": "cds watch --open wallet/webapp/index.html",
148
+ "release:check": "node scripts/release-check.mjs"
145
149
  },
146
150
  "sapux": [
147
151
  "app/odatano"
package/src/index.d.ts CHANGED
@@ -4,8 +4,8 @@ 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, revokeAgentGrantById, 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 } from '../srv/utils/agent-grants';
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
9
  export { registerTransportLane } from '../srv/utils/agent-token-auth';
10
10
  export type { TransportLane, LaneOutcome } from '../srv/utils/agent-token-auth';
11
11
  export { loadAgentGrantsConfig } from '../srv/utils/agent-grants-config';
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.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.revokeAgentGrantById = 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;
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;
@@ -70,7 +70,11 @@ Object.defineProperty(exports, "getHsmSigner", { enumerable: true, get: function
70
70
  // adds its payment lane through registerTransportLane.
71
71
  var agent_grants_1 = require("../srv/utils/agent-grants");
72
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; } });
73
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; } });
74
78
  Object.defineProperty(exports, "hashAgentToken", { enumerable: true, get: function () { return agent_grants_1.hashAgentToken; } });
75
79
  Object.defineProperty(exports, "AGENT_TOKEN_HEADER", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_HEADER; } });
76
80
  Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_PREFIX; } });
@@ -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)
@@ -4,11 +4,13 @@ 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");
14
16
  const mappers_1 = require("../../utils/mappers");
@@ -63,6 +65,23 @@ function ogmiosValueToLovelaceString(value) {
63
65
  const lovelace = value.ada?.lovelace;
64
66
  return lovelace === undefined ? '0' : String(lovelace);
65
67
  }
68
+ /**
69
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
70
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
71
+ * 0x3 = script hash. The validators already enforce HRP + length before the
72
+ * request reaches a backend, so this only has to split the payload.
73
+ */
74
+ function decodeDrepId(drepId) {
75
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
76
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
77
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
78
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
79
+ }
80
+ return {
81
+ hashHex: bytes.subarray(1).toString('hex'),
82
+ isScript: (bytes[0] & 0x0f) === 0x03,
83
+ };
84
+ }
66
85
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
86
  function resolveOgmiosTip(tip) {
68
87
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -88,7 +107,8 @@ class OgmiosBackend {
88
107
  'getTransaction',
89
108
  'getTransactionMetadata',
90
109
  'getAddressTransactions',
91
- 'getDrep',
110
+ // getDrep is NOT listed: served from the live ledger state via
111
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
112
  'getAssetInfo',
93
113
  'getAddress',
94
114
  'getNetworkInformation',
@@ -305,13 +325,60 @@ class OgmiosBackend {
305
325
  }, this.name);
306
326
  }
307
327
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
328
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
329
+ *
330
+ * The client package (6.14) ships the schema types but no wrapper for this query,
331
+ * so it goes through the exported `Method()` primitive on our interaction context —
332
+ * the same building block the client uses for `stakePools` & co.
333
+ *
334
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
335
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
336
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
337
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
338
+ *
339
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
310
340
  * @returns {Promise<DrepData>} drep data
311
341
  */
312
- async getDrep(_drepId) {
342
+ async getDrep(drepId) {
313
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
344
+ await this.ensureConnected();
345
+ if (!this.context) {
346
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
347
+ }
348
+ const { hashHex, isScript } = decodeDrepId(drepId);
349
+ const [summaries, currentEpoch] = await Promise.all([
350
+ (0, client_1.Method)({
351
+ method: 'queryLedgerState/delegateRepresentatives',
352
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
353
+ }, {
354
+ handler: (response, resolve, reject) => {
355
+ if (response.error) {
356
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
357
+ }
358
+ else {
359
+ resolve(Array.isArray(response.result) ? response.result : []);
360
+ }
361
+ },
362
+ }, this.context),
363
+ this.stateQueryClient.epoch(),
364
+ ]);
365
+ // Filter by id: the query is already credential-scoped, but never trust a
366
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
367
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
368
+ if (!drep)
369
+ throw new errors_1.NotFoundError('Drep', this.name);
370
+ const mandateEpoch = drep.mandate?.epoch;
371
+ return {
372
+ drepId,
373
+ hex: hashHex,
374
+ amount: ogmiosValueToLovelaceString(drep.stake),
375
+ hasScript: isScript || drep.from === 'script',
376
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0,
377
+ // matching what the Koios mapper does since its schema change.
378
+ lastActiveEpoch: 0,
379
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
380
+ retired: false,
381
+ };
315
382
  }, this.name);
316
383
  }
317
384
  /**