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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -2,19 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.setActiveNetwork = setActiveNetwork;
4
4
  exports.getActiveNetwork = getActiveNetwork;
5
- /**
6
- * Module-scoped holder for the active Cardano network.
7
- *
8
- * This is a deliberately tiny *leaf* module: it has no runtime dependencies (the
9
- * `Network` import is type-only and erased at compile), so leaf utilities such as
10
- * `validators.ts` can read the configured network WITHOUT importing `server.ts`
11
- * — which would otherwise drag the whole server → indexer graph (and its
12
- * module-load `cds.ql` access) into every consumer.
13
- *
14
- * Set during bootstrap by `initializeAppContext` and cleared on shutdown. Reads
15
- * before bootstrap return `null`; callers treat that as "not ready" rather than
16
- * throwing (e.g. network-aware validators return `false`).
17
- */
5
+ // Holds the active network so validators can read it without importing server.ts.
6
+ // Null before bootstrap.
18
7
  let active = null;
19
8
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
20
9
  function setActiveNetwork(n) {
@@ -0,0 +1,31 @@
1
+ import type { Request } from '@sap/cds';
2
+ /** A page of a list operation. The CDS model range-checks `limit` and `skip` before the handler runs. */
3
+ export interface Page {
4
+ limit: number;
5
+ skip: number;
6
+ }
7
+ /** The page a request asks for, with the operation's default limit when none is given. */
8
+ export declare function pageOf(data: {
9
+ limit?: number | null;
10
+ skip?: number | null;
11
+ }, defaultLimit: number): Page;
12
+ /** The rows of one page out of a list that is already in its final order. */
13
+ export declare function pageRows<T>(rows: T[], page: Page): T[];
14
+ /** Rows sorted by a string key; a fixed order keeps pages stable across calls. */
15
+ export declare function byKey<T>(rows: T[], keyOf: (row: T) => string): T[];
16
+ /** UTxOs in output-reference order: tx hash, then output index. */
17
+ export declare function byOutRef<T extends {
18
+ hash?: string | null;
19
+ index?: number | null;
20
+ }>(rows: T[]): T[];
21
+ /** Newest first. Koios rows carry only a time, Blockfrost rows only a height; the tx hash breaks ties. */
22
+ export declare function sortAssetHistory<T extends {
23
+ blockHeight?: number | null;
24
+ blockTime?: number | null;
25
+ txHash?: string | null;
26
+ }>(rows: T[]): T[];
27
+ /** Operations over a provider's newest rows reach at most this far. */
28
+ export declare const LATEST_WINDOW = 100;
29
+ /** Page over the newest LATEST_WINDOW rows; a page reaching past them is a 400. */
30
+ export declare function latestWindowPage(req: Request, ctx: string, defaultLimit: number): Page;
31
+ //# sourceMappingURL=paging.d.ts.map
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LATEST_WINDOW = void 0;
4
+ exports.pageOf = pageOf;
5
+ exports.pageRows = pageRows;
6
+ exports.byKey = byKey;
7
+ exports.byOutRef = byOutRef;
8
+ exports.sortAssetHistory = sortAssetHistory;
9
+ exports.latestWindowPage = latestWindowPage;
10
+ const errors_1 = require("./errors");
11
+ /** The page a request asks for, with the operation's default limit when none is given. */
12
+ function pageOf(data, defaultLimit) {
13
+ return { limit: data.limit ?? defaultLimit, skip: data.skip ?? 0 };
14
+ }
15
+ /** The rows of one page out of a list that is already in its final order. */
16
+ function pageRows(rows, page) {
17
+ return rows.slice(page.skip, page.skip + page.limit);
18
+ }
19
+ /** Rows sorted by a string key; a fixed order keeps pages stable across calls. */
20
+ function byKey(rows, keyOf) {
21
+ return [...rows].sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
22
+ }
23
+ /** UTxOs in output-reference order: tx hash, then output index. */
24
+ function byOutRef(rows) {
25
+ return [...rows].sort((a, b) => String(a.hash ?? '').localeCompare(String(b.hash ?? '')) || Number(a.index ?? 0) - Number(b.index ?? 0));
26
+ }
27
+ /** Newest first. Koios rows carry only a time, Blockfrost rows only a height; the tx hash breaks ties. */
28
+ function sortAssetHistory(rows) {
29
+ return [...rows].sort((a, b) => Number(b.blockHeight ?? -1) - Number(a.blockHeight ?? -1)
30
+ || Number(b.blockTime ?? -1) - Number(a.blockTime ?? -1)
31
+ || String(b.txHash ?? '').localeCompare(String(a.txHash ?? '')));
32
+ }
33
+ /** Operations over a provider's newest rows reach at most this far. */
34
+ exports.LATEST_WINDOW = 100;
35
+ /** Page over the newest LATEST_WINDOW rows; a page reaching past them is a 400. */
36
+ function latestWindowPage(req, ctx, defaultLimit) {
37
+ const page = pageOf(req.data, defaultLimit);
38
+ if (page.skip + page.limit > exports.LATEST_WINDOW) {
39
+ (0, errors_1.rejectInvalid)(req, ctx, `skip + limit must not exceed ${exports.LATEST_WINDOW}`, 'skip');
40
+ }
41
+ return page;
42
+ }
43
+ //# sourceMappingURL=paging.js.map
@@ -0,0 +1,8 @@
1
+ import { Readable } from 'stream';
2
+ /** A JSON row stream the CAP renderer built from an array (it keeps the array as `_raw`). */
3
+ export declare function isInlineRowStream(v: unknown): v is Readable & {
4
+ _raw: unknown[];
5
+ };
6
+ /** Wraps the driver's `_prepareStreams` once; returns false when the driver or the hook is missing. */
7
+ export declare function installPostgresInlineJson(): boolean;
8
+ //# sourceMappingURL=pg-inline-json.d.ts.map
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isInlineRowStream = isInlineRowStream;
7
+ exports.installPostgresInlineJson = installPostgresInlineJson;
8
+ // Sends bulk INSERT and UPSERT rows on PostgreSQL as one text parameter. The driver default
9
+ // streams them through a temp table, which costs three round trips per write.
10
+ // Streams a caller passes in keep the driver's path.
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const stream_1 = require("stream");
13
+ const logger = cds_1.default.log('PgInlineJson');
14
+ const INSTALLED = Symbol.for('odatano.pgInlineJson');
15
+ /** A JSON row stream the CAP renderer built from an array (it keeps the array as `_raw`). */
16
+ function isInlineRowStream(v) {
17
+ return v instanceof stream_1.Readable && Array.isArray(v._raw);
18
+ }
19
+ const dbKind = () => String((cds_1.default.env?.requires?.db)?.kind ?? '');
20
+ async function drain(stream) {
21
+ const parts = [];
22
+ for await (const part of stream)
23
+ parts.push(Buffer.isBuffer(part) ? part : Buffer.from(String(part)));
24
+ return Buffer.concat(parts).toString('utf8');
25
+ }
26
+ /** Wraps the driver's `_prepareStreams` once; returns false when the driver or the hook is missing. */
27
+ function installPostgresInlineJson() {
28
+ let PostgresService;
29
+ try {
30
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
31
+ }
32
+ catch (err) {
33
+ if (dbKind() === 'postgres')
34
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, bulk writes keep the COPY buffer: ${String(err?.message ?? err)}`);
35
+ return false;
36
+ }
37
+ const proto = PostgresService?.prototype;
38
+ const orig = proto?._prepareStreams;
39
+ if (!proto || typeof orig !== 'function') {
40
+ logger.warn('@cap-js/postgres has no _prepareStreams hook; bulk writes keep the COPY buffer');
41
+ return false;
42
+ }
43
+ if (proto[INSTALLED])
44
+ return true;
45
+ proto._prepareStreams = function (query, values) {
46
+ if (!Array.isArray(values) || !values.some(isInlineRowStream))
47
+ return orig.call(this, query, values);
48
+ return (async () => {
49
+ const inlined = await Promise.all(values.map(v => (isInlineRowStream(v) ? drain(v) : v)));
50
+ return orig.call(this, query, inlined);
51
+ })();
52
+ };
53
+ proto[INSTALLED] = true;
54
+ if (dbKind() === 'postgres')
55
+ logger.info('Bulk writes on Postgres: row lists sent inline, no COPY buffer');
56
+ return true;
57
+ }
58
+ //# sourceMappingURL=pg-inline-json.js.map
@@ -0,0 +1,14 @@
1
+ interface OrderTerm {
2
+ nulls?: string;
3
+ element?: {
4
+ key?: boolean;
5
+ notNull?: boolean;
6
+ '@cds.valid.from'?: boolean;
7
+ };
8
+ }
9
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
10
+ export declare function stripNullsForNotNull(orderBy: OrderTerm[], rendered: string[]): string[];
11
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
12
+ export declare function installPostgresOrderNulls(): boolean;
13
+ export {};
14
+ //# sourceMappingURL=pg-order-nulls.d.ts.map
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.stripNullsForNotNull = stripNullsForNotNull;
7
+ exports.installPostgresOrderNulls = installPostgresOrderNulls;
8
+ // Drops the NULLS clause from ORDER BY on PostgreSQL for columns that cannot be NULL.
9
+ // The driver's NULLS placement is the opposite of the btree index, so `$top` would sort the whole table.
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ const logger = cds_1.default.log('PgOrderNulls');
12
+ const INSTALLED = Symbol.for('odatano.pgOrderNulls');
13
+ const dbKind = () => String((cds_1.default.env?.requires?.db)?.kind ?? '');
14
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
15
+ function stripNullsForNotNull(orderBy, rendered) {
16
+ return rendered.map((sql, i) => {
17
+ const c = orderBy[i];
18
+ if (!c || c.nulls)
19
+ return sql;
20
+ const el = c.element;
21
+ if (el && (el.key === true || el.notNull === true || el['@cds.valid.from'] === true))
22
+ return sql.replace(/ NULLS (FIRST|LAST)$/, '');
23
+ return sql;
24
+ });
25
+ }
26
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
27
+ function installPostgresOrderNulls() {
28
+ let PostgresService;
29
+ try {
30
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
31
+ }
32
+ catch (err) {
33
+ // No loadable Postgres driver: silent unless the database is Postgres.
34
+ if (dbKind() === 'postgres')
35
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
36
+ return false;
37
+ }
38
+ const proto = PostgresService.CQN2SQL?.prototype;
39
+ const orig = proto?._orderBy;
40
+ if (!proto || typeof orig !== 'function') {
41
+ logger.warn('@cap-js/postgres has no _orderBy hook; ORDER BY keeps the NULLS clause (indexes will not serve ordered reads)');
42
+ return false;
43
+ }
44
+ if (proto[INSTALLED])
45
+ return true;
46
+ proto._orderBy = function (orderBy, ...rest) {
47
+ return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
48
+ };
49
+ proto[INSTALLED] = true;
50
+ if (dbKind() === 'postgres')
51
+ logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
52
+ return true;
53
+ }
54
+ //# sourceMappingURL=pg-order-nulls.js.map
@@ -1,35 +1,29 @@
1
1
  import type { JSONValue } from './types';
2
- /**
3
- * PlutusData-JSON input-index placeholder.
4
- * Matches the full string form `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`.
5
- * The placeholder must be the entire `int` field value — partial matches are ignored.
6
- */
7
2
  export declare const INPUT_IDX_REGEX: RegExp;
3
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
4
+ export declare const REF_IDX_REGEX: RegExp;
5
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
6
+ export declare const WDRL_IDX_REGEX: RegExp;
8
7
  /** Minimal UTxO reference shape used by the placeholder resolver. */
9
8
  export interface InputRef {
10
9
  txHash: string;
11
10
  outputIndex: number;
12
11
  }
12
+ /** Credential of a reward account, as the ledger orders withdrawals. */
13
+ export interface WithdrawalCredential {
14
+ credentialHash: string;
15
+ isScript: boolean;
16
+ }
13
17
  export interface ResolveContext {
14
- /** Inputs in their final, post-sort order — index of `ref` in this array == resolved placeholder value. */
18
+ /** Inputs in their final, post-sort order; the array index is the resolved placeholder value. */
15
19
  sortedInputs: InputRef[];
20
+ /** All reference inputs in ledger order; absent where the build does not support `__REF_IDX__`. */
21
+ sortedReferenceInputs?: InputRef[];
22
+ /** Withdrawal credential hashes in ledger order; absent where the build does not support `__WDRL_IDX__`. */
23
+ sortedWithdrawals?: string[];
16
24
  }
17
- /**
18
- * Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
19
- * This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
20
- * Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
21
- */
22
25
  export declare function sortInputsLikeBuildooor<T extends InputRef>(refs: T[]): T[];
23
- /**
24
- * Walk a PlutusData JSON tree and replace any `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves
25
- * with `{int: <resolvedIndex>}` according to the sorted input order in `ctx`.
26
- *
27
- * Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
28
- * are left untouched — hex payloads may legitimately contain `__` sequences.
29
- *
30
- * Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
31
- * in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
32
- * can diagnose missing forceInputs / script UTxOs.
33
- */
26
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
27
+ export declare function sortWithdrawalsLikeLedger<T extends WithdrawalCredential>(entries: T[]): T[];
34
28
  export declare function resolveIndexPlaceholders(node: JSONValue, ctx: ResolveContext): JSONValue;
35
29
  //# sourceMappingURL=plutus-placeholders.d.ts.map
@@ -1,23 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.INPUT_IDX_REGEX = void 0;
3
+ exports.WDRL_IDX_REGEX = exports.REF_IDX_REGEX = exports.INPUT_IDX_REGEX = void 0;
4
4
  exports.sortInputsLikeBuildooor = sortInputsLikeBuildooor;
5
+ exports.sortWithdrawalsLikeLedger = sortWithdrawalsLikeLedger;
5
6
  exports.resolveIndexPlaceholders = resolveIndexPlaceholders;
6
7
  const errors_1 = require("./errors");
7
- /**
8
- * PlutusData-JSON input-index placeholder.
9
- * Matches the full string form `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`.
10
- * The placeholder must be the entire `int` field value — partial matches are ignored.
11
- */
12
- // case-insensitive: tx hashes are conventionally lowercase, but accept either
13
- // case and normalize the captured hash to lowercase at the use site
8
+ // Input-index placeholder; must be the entire `int` field value.
9
+ // The hash is case-insensitive and lowercased at the use site.
14
10
  exports.INPUT_IDX_REGEX = /^__INPUT_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
11
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
12
+ exports.REF_IDX_REGEX = /^__REF_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
13
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
14
+ exports.WDRL_IDX_REGEX = /^__WDRL_IDX:([0-9a-fA-F]{56})__$/;
15
15
  const MAX_WALK_DEPTH = 64;
16
- /**
17
- * Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
18
- * This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
19
- * Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
20
- */
16
+ // Ledger set order as Buildooor sorts it: txHash bytes, then outputIndex.
17
+ // The ledger orders reference inputs the same way.
21
18
  function sortInputsLikeBuildooor(refs) {
22
19
  const copy = refs.slice();
23
20
  copy.sort((a, b) => {
@@ -30,20 +27,59 @@ function sortInputsLikeBuildooor(refs) {
30
27
  });
31
28
  return copy;
32
29
  }
33
- /**
34
- * Walk a PlutusData JSON tree and replace any `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves
35
- * with `{int: <resolvedIndex>}` according to the sorted input order in `ctx`.
36
- *
37
- * Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
38
- * are left untouched — hex payloads may legitimately contain `__` sequences.
39
- *
40
- * Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
41
- * in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
42
- * can diagnose missing forceInputs / script UTxOs.
43
- */
30
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
31
+ function sortWithdrawalsLikeLedger(entries) {
32
+ const copy = entries.slice();
33
+ copy.sort((a, b) => {
34
+ if (a.isScript !== b.isScript)
35
+ return a.isScript ? -1 : 1;
36
+ return Buffer.compare(Buffer.from(a.credentialHash, 'hex'), Buffer.from(b.credentialHash, 'hex'));
37
+ });
38
+ return copy;
39
+ }
40
+ // Replaces INPUT_IDX, REF_IDX and WDRL_IDX placeholders with the position in the matching list.
41
+ // Only `int` fields are inspected, since `bytes` may contain `__`. An unknown ref throws.
44
42
  function resolveIndexPlaceholders(node, ctx) {
45
43
  return walk(node, ctx, 0);
46
44
  }
45
+ function positionOf(value, ctx) {
46
+ const input = exports.INPUT_IDX_REGEX.exec(value);
47
+ if (input) {
48
+ const txHash = input[1].toLowerCase(); // input refs are validated lowercase
49
+ const outputIndex = Number(input[2]);
50
+ const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
51
+ if (pos === -1) {
52
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
53
+ }
54
+ return pos;
55
+ }
56
+ const ref = exports.REF_IDX_REGEX.exec(value);
57
+ if (ref) {
58
+ if (!ctx.sortedReferenceInputs) {
59
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
60
+ }
61
+ const txHash = ref[1].toLowerCase();
62
+ const outputIndex = Number(ref[2]);
63
+ const pos = ctx.sortedReferenceInputs.findIndex(r => r.txHash === txHash && r.outputIndex === outputIndex);
64
+ if (pos === -1) {
65
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references ${txHash}#${outputIndex}, which is not a reference input of the transaction`);
66
+ }
67
+ return pos;
68
+ }
69
+ const wdrl = exports.WDRL_IDX_REGEX.exec(value);
70
+ if (wdrl) {
71
+ if (!ctx.sortedWithdrawals) {
72
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
73
+ }
74
+ const credentialHash = wdrl[1].toLowerCase();
75
+ const pos = ctx.sortedWithdrawals.indexOf(credentialHash);
76
+ if (pos === -1) {
77
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references credential ${credentialHash}, which has no withdrawal in the transaction`);
78
+ }
79
+ return pos;
80
+ }
81
+ return undefined;
82
+ }
47
83
  function walk(node, ctx, depth) {
48
84
  if (depth > MAX_WALK_DEPTH) {
49
85
  throw new errors_1.TransactionValidationError(`PlutusData placeholder walker exceeded max depth ${MAX_WALK_DEPTH}`);
@@ -56,15 +92,8 @@ function walk(node, ctx, depth) {
56
92
  const out = {};
57
93
  for (const [key, value] of Object.entries(node)) {
58
94
  if (key === 'int' && typeof value === 'string') {
59
- const match = exports.INPUT_IDX_REGEX.exec(value);
60
- if (match) {
61
- const [, rawTxHash, idxStr] = match;
62
- const txHash = rawTxHash.toLowerCase(); // normalize to match validated lowercase input refs
63
- const outputIndex = Number(idxStr);
64
- const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
65
- if (pos === -1) {
66
- throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
67
- }
95
+ const pos = positionOf(value, ctx);
96
+ if (pos !== undefined) {
68
97
  out[key] = pos;
69
98
  continue;
70
99
  }
@@ -1,8 +1,4 @@
1
- /**
2
- * In-memory sliding-window rate limiter, ported from NIGHTGATE
3
- * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
4
- * agent-token attempts; nothing here touches the database.
5
- */
1
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
6
2
  export interface RateLimiterOptions {
7
3
  windowMs: number;
8
4
  maxRequests: number;
@@ -10,24 +6,12 @@ export interface RateLimiterOptions {
10
6
  maxKeys?: number;
11
7
  /** Stale-key sweep interval (default 60 000 ms). */
12
8
  sweepIntervalMs?: number;
13
- /**
14
- * Max distinct keys ONE group may hold (default 64). The group is the key up
15
- * to its first ':' (the principal in `principal:scope` keys). Bounds what a
16
- * single caller can do to the shared table: without it, made-up scopes under
17
- * one principal evicted every other caller's window.
18
- */
19
9
  maxKeysPerGroup?: number;
20
10
  }
21
11
  export interface RateCheckResult {
22
12
  allowed: boolean;
23
13
  retryAfterMs: number;
24
14
  }
25
- /**
26
- * Rate-limit key for a CAP request: the principal (user, else client address)
27
- * plus the scope. Batch parts carry no address and a proxy hides the real one,
28
- * so the address is the last resort only. The principal is the limiter's GROUP
29
- * (see maxKeysPerGroup), hence no ':' in it.
30
- */
31
15
  export declare function principalRateKey(req: unknown, scope: string): string;
32
16
  export declare class RateLimiter {
33
17
  private readonly windowMs;
@@ -43,10 +27,7 @@ export declare class RateLimiter {
43
27
  peek(key: string): RateCheckResult;
44
28
  /** Forget every key (tests). */
45
29
  reset(): void;
46
- /**
47
- * Consume `count` slots atomically: either ALL fit into the window and are
48
- * recorded, or NONE are (a rejected caller has consumed nothing).
49
- */
30
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
50
31
  checkMany(key: string, count: number): RateCheckResult;
51
32
  private dropKey;
52
33
  /** Remove keys with no hits within the current window. */
@@ -1,9 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * In-memory sliding-window rate limiter, ported from NIGHTGATE
4
- * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
5
- * agent-token attempts; nothing here touches the database.
6
- */
2
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
7
3
  Object.defineProperty(exports, "__esModule", { value: true });
8
4
  exports.RateLimiter = void 0;
9
5
  exports.principalRateKey = principalRateKey;
@@ -12,12 +8,8 @@ function groupOf(key) {
12
8
  const i = key.indexOf(':');
13
9
  return i < 0 ? key : key.slice(0, i);
14
10
  }
15
- /**
16
- * Rate-limit key for a CAP request: the principal (user, else client address)
17
- * plus the scope. Batch parts carry no address and a proxy hides the real one,
18
- * so the address is the last resort only. The principal is the limiter's GROUP
19
- * (see maxKeysPerGroup), hence no ':' in it.
20
- */
11
+ // Key `principal:scope` for a CAP request. The principal is the user, else the client address.
12
+ // Colons in an IPv6 address are replaced, because the text before the first ':' is the group.
21
13
  function principalRateKey(req, scope) {
22
14
  const r = req;
23
15
  const user = r?.user?.id;
@@ -61,10 +53,7 @@ class RateLimiter {
61
53
  this.hits.clear();
62
54
  this.groupCounts.clear();
63
55
  }
64
- /**
65
- * Consume `count` slots atomically: either ALL fit into the window and are
66
- * recorded, or NONE are (a rejected caller has consumed nothing).
67
- */
56
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
68
57
  checkMany(key, count) {
69
58
  if (count <= 0)
70
59
  return { allowed: true, retryAfterMs: 0 };
@@ -75,8 +64,7 @@ class RateLimiter {
75
64
  if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
76
65
  return { allowed: false, retryAfterMs: this.windowMs };
77
66
  }
78
- // At capacity a NEW key evicts the least recently used one (the map is
79
- // insertion ordered and `set` below re-inserts on every hit).
67
+ // At capacity a new key evicts the least recently used one (insertion-ordered map, re-inserted per hit).
80
68
  if (this.hits.size >= this.maxKeys) {
81
69
  const oldest = this.hits.keys().next().value;
82
70
  if (oldest !== undefined)
@@ -0,0 +1,12 @@
1
+ export interface Readiness {
2
+ status: 'ready' | 'not_ready';
3
+ timestamp: string;
4
+ /** The client, the indexer and the transaction builder exist. */
5
+ context: boolean;
6
+ /** The database answers and holds the schema. */
7
+ database: boolean;
8
+ /** The HSM session is connected; null when no HSM is configured. */
9
+ hsm: boolean | null;
10
+ }
11
+ export declare function buildReadiness(parts: Pick<Readiness, 'context' | 'hsm'>, now?: Date): Promise<Readiness>;
12
+ //# sourceMappingURL=readiness.d.ts.map
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ // Readiness body for getReadiness(): whether this instance can serve requests. It names the
3
+ // missing part and nothing else, so an anonymous probe learns no configuration detail.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.buildReadiness = buildReadiness;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const tx_utils_1 = require("./tx-utils");
11
+ const { SELECT } = cds_1.default.ql;
12
+ const PROBE_TIMEOUT_MS = 3000;
13
+ async function databaseAnswers() {
14
+ if (!cds_1.default.db)
15
+ return false;
16
+ try {
17
+ await (0, tx_utils_1.detachedTx)('readiness probe', (db) => db.run(SELECT.one.from('odatano.cardano.CardanoSyncState').columns('ID')), PROBE_TIMEOUT_MS);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ async function buildReadiness(parts, now = new Date()) {
25
+ const database = await databaseAnswers();
26
+ const ready = parts.context && database && parts.hsm !== false;
27
+ return { status: ready ? 'ready' : 'not_ready', timestamp: now.toISOString(), context: parts.context, database, hsm: parts.hsm };
28
+ }
29
+ //# sourceMappingURL=readiness.js.map
@@ -0,0 +1,19 @@
1
+ import { Script } from '@harmoniclabs/cardano-ledger-ts';
2
+ /** Script language of a reference script as the entities expose it. */
3
+ export type ReferenceScriptType = 'native' | 'plutusV1' | 'plutusV2' | 'plutusV3';
4
+ /** Hash, ledger byte size and type of a reference script; `cbor` holds the Plutus script bytes when known. */
5
+ export interface ReferenceScriptInfo {
6
+ hash: string;
7
+ size: number;
8
+ type: ReferenceScriptType;
9
+ cbor: string | null;
10
+ }
11
+ export declare function normalizeScriptType(raw: unknown): ReferenceScriptType | null;
12
+ /** Ledger script hash: blake2b-224 over the language tag byte followed by the script bytes. */
13
+ export declare function referenceScriptHash(type: ReferenceScriptType, bytes: Uint8Array): string;
14
+ export declare function referenceScriptSize(script: Script): number;
15
+ export declare function sizePlaceholderScript(size: number): Script;
16
+ /** Hash, size and type of an Ogmios `script` object (`{ language, cbor }`); null without one. */
17
+ export declare function ogmiosReferenceScript(script: unknown): ReferenceScriptInfo | null;
18
+ export declare function cliReferenceScript(ref: unknown): ReferenceScriptInfo | null;
19
+ //# sourceMappingURL=reference-script.d.ts.map
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeScriptType = normalizeScriptType;
4
+ exports.referenceScriptHash = referenceScriptHash;
5
+ exports.referenceScriptSize = referenceScriptSize;
6
+ exports.sizePlaceholderScript = sizePlaceholderScript;
7
+ exports.ogmiosReferenceScript = ogmiosReferenceScript;
8
+ exports.cliReferenceScript = cliReferenceScript;
9
+ const crypto_1 = require("@harmoniclabs/crypto");
10
+ const cbor_1 = require("@harmoniclabs/cbor");
11
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
12
+ const LANGUAGE_TAG = { native: 0, plutusV1: 1, plutusV2: 2, plutusV3: 3 };
13
+ // Maps provider spellings such as `plutus:v3`, `PlutusScriptV3`, `timelock` or `SimpleScript`.
14
+ // Null when unknown.
15
+ function normalizeScriptType(raw) {
16
+ if (typeof raw !== 'string')
17
+ return null;
18
+ const m = /^(?:plutus:?(?:script)?v?)([1-3])$/i.exec(raw.replace(/\s+/g, ''));
19
+ if (m)
20
+ return `plutusV${m[1]}`;
21
+ return /^(native|timelock|multisig|simplescript)/i.test(raw) ? 'native' : null;
22
+ }
23
+ /** Ledger script hash: blake2b-224 over the language tag byte followed by the script bytes. */
24
+ function referenceScriptHash(type, bytes) {
25
+ const tagged = Uint8Array.from(Buffer.concat([Buffer.from([LANGUAGE_TAG[type]]), Buffer.from(bytes)]));
26
+ return Buffer.from((0, crypto_1.blake2b_224)(tagged)).toString('hex');
27
+ }
28
+ // Ledger-charged size: the compiler's script bytestring for Plutus, the CBOR for native scripts.
29
+ function referenceScriptSize(script) {
30
+ if (script.type === 'NativeScript')
31
+ return script.bytes.length;
32
+ const n = script.bytes.length;
33
+ // definite-length CBOR bytestring header
34
+ const header = n < 24 ? 1 : n < 0x100 ? 2 : n < 0x10000 ? 3 : 5;
35
+ return n + header;
36
+ }
37
+ // Empty script of the given ledger size, so the fee counts a reference script known by size only.
38
+ // Never a witness, never serialized. Its hash matches no real script.
39
+ function sizePlaceholderScript(size) {
40
+ for (let n = Math.max(0, size - 5); n <= size; n++) {
41
+ const header = n < 24 ? 1 : n < 0x100 ? 2 : n < 0x10000 ? 3 : 5;
42
+ if (n + header === size)
43
+ return cardano_ledger_ts_1.Script.plutusV3(new Uint8Array(n));
44
+ }
45
+ return cardano_ledger_ts_1.Script.plutusV3(new Uint8Array(Math.max(0, size - 1)));
46
+ }
47
+ /** Hash, size and type of an Ogmios `script` object (`{ language, cbor }`); null without one. */
48
+ function ogmiosReferenceScript(script) {
49
+ const s = script;
50
+ const type = normalizeScriptType(s?.language);
51
+ if (!type || typeof s?.cbor !== 'string' || s.cbor.length === 0)
52
+ return null;
53
+ const bytes = Buffer.from(s.cbor, 'hex');
54
+ return { hash: referenceScriptHash(type, bytes), size: bytes.length, type, cbor: type === 'native' ? null : s.cbor };
55
+ }
56
+ // cardano-cli's Plutus `cborHex` wraps the script once more than the ledger does.
57
+ // The ledger hashes and charges the inner bytes. A native script is given as JSON.
58
+ function cliReferenceScript(ref) {
59
+ const r = ref;
60
+ const script = r?.script;
61
+ if (!script || typeof script !== 'object')
62
+ return null;
63
+ const envelope = script;
64
+ const type = normalizeScriptType(envelope.type) ?? normalizeScriptType(r?.scriptLanguage);
65
+ try {
66
+ if (type && type !== 'native' && typeof envelope.cborHex === 'string') {
67
+ const outer = cbor_1.Cbor.parse(Buffer.from(envelope.cborHex, 'hex'));
68
+ if (!(outer instanceof cbor_1.CborBytes))
69
+ return null;
70
+ const inner = Buffer.from(outer.bytes);
71
+ return { hash: referenceScriptHash(type, inner), size: inner.length, type, cbor: inner.toString('hex') };
72
+ }
73
+ if (type === 'native' || r?.scriptLanguage?.startsWith('SimpleScript')) {
74
+ // cardano-cli prints a native script as JSON.
75
+ const native = cardano_ledger_ts_1.Script.native(script);
76
+ return { hash: native.hash.toString(), size: native.bytes.length, type: 'native', cbor: null };
77
+ }
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ return null;
83
+ }
84
+ //# sourceMappingURL=reference-script.js.map