@odatano/core 2.0.0-rc.4 → 2.0.0-rc.41

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 (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -3,17 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.setActiveNetwork = setActiveNetwork;
4
4
  exports.getActiveNetwork = getActiveNetwork;
5
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`).
6
+ * Dependency-free holder for the active network, so leaf utilities (validators) can read it
7
+ * without importing `server.ts`. Set by `initializeAppContext`, `null` before bootstrap.
17
8
  */
18
9
  let active = null;
19
10
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
@@ -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,62 @@
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
+ /**
9
+ * Bulk INSERT/UPSERT on PostgreSQL: send the rows as one text parameter.
10
+ * @cap-js/postgres turns every `.entries()` row list into a stream and ships it through a
11
+ * per-transaction temp table (`CREATE TEMP TABLE` + `COPY`), three round trips per write plus a
12
+ * table created and dropped per transaction. Row lists built from in-memory arrays are drained
13
+ * into a string instead; streams a caller passes in (media) keep the driver's path.
14
+ */
15
+ const cds_1 = __importDefault(require("@sap/cds"));
16
+ const stream_1 = require("stream");
17
+ const logger = cds_1.default.log('PgInlineJson');
18
+ const INSTALLED = Symbol.for('odatano.pgInlineJson');
19
+ /** A JSON row stream the CAP renderer built from an array (it keeps the array as `_raw`). */
20
+ function isInlineRowStream(v) {
21
+ return v instanceof stream_1.Readable && Array.isArray(v._raw);
22
+ }
23
+ const dbKind = () => String((cds_1.default.env?.requires?.db)?.kind ?? '');
24
+ async function drain(stream) {
25
+ const parts = [];
26
+ for await (const part of stream)
27
+ parts.push(Buffer.isBuffer(part) ? part : Buffer.from(String(part)));
28
+ return Buffer.concat(parts).toString('utf8');
29
+ }
30
+ /** Wraps the driver's `_prepareStreams` once; returns false when the driver or the hook is missing. */
31
+ function installPostgresInlineJson() {
32
+ let PostgresService;
33
+ try {
34
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
35
+ }
36
+ catch (err) {
37
+ if (dbKind() === 'postgres')
38
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, bulk writes keep the COPY buffer: ${String(err?.message ?? err)}`);
39
+ return false;
40
+ }
41
+ const proto = PostgresService?.prototype;
42
+ const orig = proto?._prepareStreams;
43
+ if (!proto || typeof orig !== 'function') {
44
+ logger.warn('@cap-js/postgres has no _prepareStreams hook; bulk writes keep the COPY buffer');
45
+ return false;
46
+ }
47
+ if (proto[INSTALLED])
48
+ return true;
49
+ proto._prepareStreams = function (query, values) {
50
+ if (!Array.isArray(values) || !values.some(isInlineRowStream))
51
+ return orig.call(this, query, values);
52
+ return (async () => {
53
+ const inlined = await Promise.all(values.map(v => (isInlineRowStream(v) ? drain(v) : v)));
54
+ return orig.call(this, query, inlined);
55
+ })();
56
+ };
57
+ proto[INSTALLED] = true;
58
+ if (dbKind() === 'postgres')
59
+ logger.info('Bulk writes on Postgres: row lists sent inline, no COPY buffer');
60
+ return true;
61
+ }
62
+ //# 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,56 @@
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
+ /**
9
+ * ORDER BY on PostgreSQL: drop the NULLS clause for columns that cannot be NULL.
10
+ * @cap-js/postgres renders `ASC NULLS FIRST` / `DESC NULLS LAST`, the opposite of a btree index's
11
+ * placement, so `$top` reads sorted the whole table; key, `not null` and `@cds.valid.from` columns are exempt.
12
+ */
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const logger = cds_1.default.log('PgOrderNulls');
15
+ const INSTALLED = Symbol.for('odatano.pgOrderNulls');
16
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
17
+ function stripNullsForNotNull(orderBy, rendered) {
18
+ return rendered.map((sql, i) => {
19
+ const c = orderBy[i];
20
+ if (!c || c.nulls)
21
+ return sql;
22
+ const el = c.element;
23
+ if (el && (el.key === true || el.notNull === true || el['@cds.valid.from'] === true))
24
+ return sql.replace(/ NULLS (FIRST|LAST)$/, '');
25
+ return sql;
26
+ });
27
+ }
28
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
29
+ function installPostgresOrderNulls() {
30
+ let PostgresService;
31
+ try {
32
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
33
+ }
34
+ catch (err) {
35
+ // No loadable Postgres driver: silent unless the database is Postgres.
36
+ const dbKind = String((cds_1.default.env?.requires?.db)?.kind ?? '');
37
+ if (dbKind === 'postgres')
38
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
39
+ return false;
40
+ }
41
+ const proto = PostgresService.CQN2SQL?.prototype;
42
+ const orig = proto?._orderBy;
43
+ if (!proto || typeof orig !== 'function') {
44
+ logger.warn('@cap-js/postgres has no _orderBy hook; ORDER BY keeps the NULLS clause (indexes will not serve ordered reads)');
45
+ return false;
46
+ }
47
+ if (proto[INSTALLED])
48
+ return true;
49
+ proto._orderBy = function (orderBy, ...rest) {
50
+ return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
51
+ };
52
+ proto[INSTALLED] = true;
53
+ logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
54
+ return true;
55
+ }
56
+ //# sourceMappingURL=pg-order-nulls.js.map
@@ -1,35 +1,42 @@
1
1
  import type { JSONValue } from './types';
2
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.
3
+ * PlutusData-JSON input-index placeholder `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`; must be the
4
+ * entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
6
5
  */
7
6
  export declare const INPUT_IDX_REGEX: RegExp;
7
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
8
+ export declare const REF_IDX_REGEX: RegExp;
9
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
10
+ export declare const WDRL_IDX_REGEX: RegExp;
8
11
  /** Minimal UTxO reference shape used by the placeholder resolver. */
9
12
  export interface InputRef {
10
13
  txHash: string;
11
14
  outputIndex: number;
12
15
  }
16
+ /** Credential of a reward account, as the ledger orders withdrawals. */
17
+ export interface WithdrawalCredential {
18
+ credentialHash: string;
19
+ isScript: boolean;
20
+ }
13
21
  export interface ResolveContext {
14
- /** Inputs in their final, post-sort order — index of `ref` in this array == resolved placeholder value. */
22
+ /** Inputs in their final, post-sort order; the array index is the resolved placeholder value. */
15
23
  sortedInputs: InputRef[];
24
+ /** All reference inputs in ledger order; absent where the build does not support `__REF_IDX__`. */
25
+ sortedReferenceInputs?: InputRef[];
26
+ /** Withdrawal credential hashes in ledger order; absent where the build does not support `__WDRL_IDX__`. */
27
+ sortedWithdrawals?: string[];
16
28
  }
17
29
  /**
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.
30
+ * Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc.
31
+ * The ledger orders reference inputs the same way.
21
32
  */
22
33
  export declare function sortInputsLikeBuildooor<T extends InputRef>(refs: T[]): T[];
34
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
35
+ export declare function sortWithdrawalsLikeLedger<T extends WithdrawalCredential>(entries: T[]): T[];
23
36
  /**
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.
37
+ * Replaces `{int: "__INPUT_IDX:…__"}`, `{int: "__REF_IDX:…__"}` and `{int: "__WDRL_IDX:…__"}` leaves with
38
+ * the position in the matching list. Only `int` fields are inspected (`bytes` may legitimately contain
39
+ * `__`); an unknown ref throws TransactionValidationError.
33
40
  */
34
41
  export declare function resolveIndexPlaceholders(node: JSONValue, ctx: ResolveContext): JSONValue;
35
42
  //# sourceMappingURL=plutus-placeholders.d.ts.map
@@ -1,22 +1,23 @@
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
  /**
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.
9
+ * PlutusData-JSON input-index placeholder `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`; must be the
10
+ * entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
11
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
14
12
  exports.INPUT_IDX_REGEX = /^__INPUT_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
13
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
14
+ exports.REF_IDX_REGEX = /^__REF_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
15
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
16
+ exports.WDRL_IDX_REGEX = /^__WDRL_IDX:([0-9a-fA-F]{56})__$/;
15
17
  const MAX_WALK_DEPTH = 64;
16
18
  /**
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.
19
+ * Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc.
20
+ * The ledger orders reference inputs the same way.
20
21
  */
21
22
  function sortInputsLikeBuildooor(refs) {
22
23
  const copy = refs.slice();
@@ -30,20 +31,62 @@ function sortInputsLikeBuildooor(refs) {
30
31
  });
31
32
  return copy;
32
33
  }
34
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
35
+ function sortWithdrawalsLikeLedger(entries) {
36
+ const copy = entries.slice();
37
+ copy.sort((a, b) => {
38
+ if (a.isScript !== b.isScript)
39
+ return a.isScript ? -1 : 1;
40
+ return Buffer.compare(Buffer.from(a.credentialHash, 'hex'), Buffer.from(b.credentialHash, 'hex'));
41
+ });
42
+ return copy;
43
+ }
33
44
  /**
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.
45
+ * Replaces `{int: "__INPUT_IDX:…__"}`, `{int: "__REF_IDX:…__"}` and `{int: "__WDRL_IDX:…__"}` leaves with
46
+ * the position in the matching list. Only `int` fields are inspected (`bytes` may legitimately contain
47
+ * `__`); an unknown ref throws TransactionValidationError.
43
48
  */
44
49
  function resolveIndexPlaceholders(node, ctx) {
45
50
  return walk(node, ctx, 0);
46
51
  }
52
+ function positionOf(value, ctx) {
53
+ const input = exports.INPUT_IDX_REGEX.exec(value);
54
+ if (input) {
55
+ const txHash = input[1].toLowerCase(); // input refs are validated lowercase
56
+ const outputIndex = Number(input[2]);
57
+ const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
58
+ if (pos === -1) {
59
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
60
+ }
61
+ return pos;
62
+ }
63
+ const ref = exports.REF_IDX_REGEX.exec(value);
64
+ if (ref) {
65
+ if (!ctx.sortedReferenceInputs) {
66
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
67
+ }
68
+ const txHash = ref[1].toLowerCase();
69
+ const outputIndex = Number(ref[2]);
70
+ const pos = ctx.sortedReferenceInputs.findIndex(r => r.txHash === txHash && r.outputIndex === outputIndex);
71
+ if (pos === -1) {
72
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references ${txHash}#${outputIndex}, which is not a reference input of the transaction`);
73
+ }
74
+ return pos;
75
+ }
76
+ const wdrl = exports.WDRL_IDX_REGEX.exec(value);
77
+ if (wdrl) {
78
+ if (!ctx.sortedWithdrawals) {
79
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
80
+ }
81
+ const credentialHash = wdrl[1].toLowerCase();
82
+ const pos = ctx.sortedWithdrawals.indexOf(credentialHash);
83
+ if (pos === -1) {
84
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references credential ${credentialHash}, which has no withdrawal in the transaction`);
85
+ }
86
+ return pos;
87
+ }
88
+ return undefined;
89
+ }
47
90
  function walk(node, ctx, depth) {
48
91
  if (depth > MAX_WALK_DEPTH) {
49
92
  throw new errors_1.TransactionValidationError(`PlutusData placeholder walker exceeded max depth ${MAX_WALK_DEPTH}`);
@@ -56,15 +99,8 @@ function walk(node, ctx, depth) {
56
99
  const out = {};
57
100
  for (const [key, value] of Object.entries(node)) {
58
101
  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
- }
102
+ const pos = positionOf(value, ctx);
103
+ if (pos !== undefined) {
68
104
  out[key] = pos;
69
105
  continue;
70
106
  }
@@ -0,0 +1,46 @@
1
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
2
+ export interface RateLimiterOptions {
3
+ windowMs: number;
4
+ maxRequests: number;
5
+ /** Max tracked keys (default 10 000). */
6
+ maxKeys?: number;
7
+ /** Stale-key sweep interval (default 60 000 ms). */
8
+ sweepIntervalMs?: number;
9
+ /**
10
+ * Max distinct keys one group (key up to its first ':', the principal) may hold (default 64),
11
+ * so one caller's made-up scopes cannot evict other callers' windows.
12
+ */
13
+ maxKeysPerGroup?: number;
14
+ }
15
+ export interface RateCheckResult {
16
+ allowed: boolean;
17
+ retryAfterMs: number;
18
+ }
19
+ /**
20
+ * Rate-limit key `principal:scope` for a CAP request; the principal is the user, else the client
21
+ * address (last resort: batch parts and proxies hide it). No ':' in the principal, it is the group.
22
+ */
23
+ export declare function principalRateKey(req: unknown, scope: string): string;
24
+ export declare class RateLimiter {
25
+ private readonly windowMs;
26
+ private readonly maxRequests;
27
+ private readonly maxKeys;
28
+ private readonly maxKeysPerGroup;
29
+ private readonly groupCounts;
30
+ private readonly hits;
31
+ private readonly sweepTimer;
32
+ constructor(opts: RateLimiterOptions);
33
+ check(key: string): RateCheckResult;
34
+ /** Would ONE more hit fit? Records nothing. */
35
+ peek(key: string): RateCheckResult;
36
+ /** Forget every key (tests). */
37
+ reset(): void;
38
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
39
+ checkMany(key: string, count: number): RateCheckResult;
40
+ private dropKey;
41
+ /** Remove keys with no hits within the current window. */
42
+ private sweep;
43
+ /** Stop the background sweep timer. */
44
+ destroy(): void;
45
+ }
46
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.RateLimiter = void 0;
5
+ exports.principalRateKey = principalRateKey;
6
+ /** The group a key belongs to: everything before the first ':' (the principal). */
7
+ function groupOf(key) {
8
+ const i = key.indexOf(':');
9
+ return i < 0 ? key : key.slice(0, i);
10
+ }
11
+ /**
12
+ * Rate-limit key `principal:scope` for a CAP request; the principal is the user, else the client
13
+ * address (last resort: batch parts and proxies hide it). No ':' in the principal, it is the group.
14
+ */
15
+ function principalRateKey(req, scope) {
16
+ const r = req;
17
+ const user = r?.user?.id;
18
+ const ip = r?._?.req?.ip ?? r?.http?.req?.ip ?? r?.ip;
19
+ const principal = user ? `user=${String(user)}`
20
+ : ip ? `ip=${String(ip).replace(/:/g, '.')}`
21
+ : 'anonymous';
22
+ return `${principal}:${scope}`;
23
+ }
24
+ class RateLimiter {
25
+ windowMs;
26
+ maxRequests;
27
+ maxKeys;
28
+ maxKeysPerGroup;
29
+ groupCounts = new Map();
30
+ hits = new Map();
31
+ sweepTimer;
32
+ constructor(opts) {
33
+ this.windowMs = opts.windowMs;
34
+ this.maxRequests = opts.maxRequests;
35
+ this.maxKeys = opts.maxKeys || 10_000;
36
+ this.maxKeysPerGroup = opts.maxKeysPerGroup || 64;
37
+ this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs || 60_000);
38
+ if (typeof this.sweepTimer.unref === 'function')
39
+ this.sweepTimer.unref();
40
+ }
41
+ check(key) {
42
+ return this.checkMany(key, 1);
43
+ }
44
+ /** Would ONE more hit fit? Records nothing. */
45
+ peek(key) {
46
+ const now = Date.now();
47
+ const inWindow = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
48
+ if (inWindow.length < this.maxRequests)
49
+ return { allowed: true, retryAfterMs: 0 };
50
+ const oldest = Math.min(...inWindow);
51
+ return { allowed: false, retryAfterMs: Math.max(oldest + this.windowMs - now, 0) };
52
+ }
53
+ /** Forget every key (tests). */
54
+ reset() {
55
+ this.hits.clear();
56
+ this.groupCounts.clear();
57
+ }
58
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
59
+ checkMany(key, count) {
60
+ if (count <= 0)
61
+ return { allowed: true, retryAfterMs: 0 };
62
+ const now = Date.now();
63
+ const windowStart = now - this.windowMs;
64
+ if (!this.hits.has(key)) {
65
+ const group = groupOf(key);
66
+ if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
67
+ return { allowed: false, retryAfterMs: this.windowMs };
68
+ }
69
+ // At capacity a new key evicts the least recently used one (insertion-ordered map, re-inserted per hit).
70
+ if (this.hits.size >= this.maxKeys) {
71
+ const oldest = this.hits.keys().next().value;
72
+ if (oldest !== undefined)
73
+ this.dropKey(oldest);
74
+ }
75
+ this.groupCounts.set(group, (this.groupCounts.get(group) ?? 0) + 1);
76
+ }
77
+ let timestamps = this.hits.get(key) || [];
78
+ timestamps = timestamps.filter((t) => t > windowStart);
79
+ this.hits.delete(key); // re-insert below = most recently used
80
+ if (timestamps.length + count > this.maxRequests) {
81
+ timestamps.sort((a, b) => a - b);
82
+ const oldestInWindow = timestamps[0];
83
+ const retryAfterMs = oldestInWindow === undefined ? this.windowMs : oldestInWindow + this.windowMs - now;
84
+ this.hits.set(key, timestamps);
85
+ return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 0) };
86
+ }
87
+ for (let i = 0; i < count; i++)
88
+ timestamps.push(now);
89
+ this.hits.set(key, timestamps);
90
+ return { allowed: true, retryAfterMs: 0 };
91
+ }
92
+ dropKey(key) {
93
+ if (!this.hits.delete(key))
94
+ return;
95
+ const group = groupOf(key);
96
+ const n = (this.groupCounts.get(group) ?? 1) - 1;
97
+ if (n <= 0)
98
+ this.groupCounts.delete(group);
99
+ else
100
+ this.groupCounts.set(group, n);
101
+ }
102
+ /** Remove keys with no hits within the current window. */
103
+ sweep() {
104
+ const windowStart = Date.now() - this.windowMs;
105
+ for (const [key, timestamps] of this.hits) {
106
+ if (!timestamps.some((t) => t > windowStart))
107
+ this.dropKey(key);
108
+ }
109
+ }
110
+ /** Stop the background sweep timer. */
111
+ destroy() {
112
+ clearInterval(this.sweepTimer);
113
+ }
114
+ }
115
+ exports.RateLimiter = RateLimiter;
116
+ //# sourceMappingURL=rate-limiter.js.map
@@ -1,26 +1,6 @@
1
1
  /**
2
- * Mirror an internal notification onto a CAP service as a declared event, so
3
- * consumers can subscribe instead of polling:
4
- *
5
- * const worker = await cds.connect.to('CardanoWorkerService');
6
- * worker.on('jobConfirmed', ({ data }) => …);
7
- *
8
- * ODATANO ships as a CAP plugin, so a consumer runs in the SAME process — these
9
- * events therefore need no broker and no `cds.requires.messaging`. Configuring a
10
- * messaging service later routes the very same emits through it (with the CAP
11
- * outbox) without a change here.
12
- *
13
- * Three properties this helper guarantees, because every caller is a background
14
- * loop that must not be disturbed by an observer:
15
- * - **Never throws.** A missing service, a rejected emit or a broken subscriber
16
- * is logged and swallowed; the crawler/worker carries on.
17
- * - **Never blocks.** Emission is fire-and-forget; a slow subscriber cannot stall
18
- * block ingestion.
19
- * - **Silent when unserved.** In unit tests and before CAP's `served` phase the
20
- * service simply does not exist yet — that is normal, not an error.
21
- *
22
- * Call sites must emit AFTER their transaction commits: an event that names data
23
- * a subscriber cannot read yet is worse than no event.
2
+ * Emits a declared CAP service event in-process (no broker needed). Never throws, never blocks,
3
+ * silent when the service is not served yet. Callers must emit AFTER their transaction commits.
24
4
  */
25
5
  export declare function emitServiceEvent(serviceName: string, event: string, data: Record<string, unknown>): void;
26
6
  //# sourceMappingURL=service-events.d.ts.map
@@ -7,33 +7,13 @@ exports.emitServiceEvent = emitServiceEvent;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const logger = cds_1.default.log('ServiceEvents');
9
9
  /**
10
- * Mirror an internal notification onto a CAP service as a declared event, so
11
- * consumers can subscribe instead of polling:
12
- *
13
- * const worker = await cds.connect.to('CardanoWorkerService');
14
- * worker.on('jobConfirmed', ({ data }) => …);
15
- *
16
- * ODATANO ships as a CAP plugin, so a consumer runs in the SAME process — these
17
- * events therefore need no broker and no `cds.requires.messaging`. Configuring a
18
- * messaging service later routes the very same emits through it (with the CAP
19
- * outbox) without a change here.
20
- *
21
- * Three properties this helper guarantees, because every caller is a background
22
- * loop that must not be disturbed by an observer:
23
- * - **Never throws.** A missing service, a rejected emit or a broken subscriber
24
- * is logged and swallowed; the crawler/worker carries on.
25
- * - **Never blocks.** Emission is fire-and-forget; a slow subscriber cannot stall
26
- * block ingestion.
27
- * - **Silent when unserved.** In unit tests and before CAP's `served` phase the
28
- * service simply does not exist yet — that is normal, not an error.
29
- *
30
- * Call sites must emit AFTER their transaction commits: an event that names data
31
- * a subscriber cannot read yet is worse than no event.
10
+ * Emits a declared CAP service event in-process (no broker needed). Never throws, never blocks,
11
+ * silent when the service is not served yet. Callers must emit AFTER their transaction commits.
32
12
  */
33
13
  function emitServiceEvent(serviceName, event, data) {
34
14
  const srv = cds_1.default.services?.[serviceName];
35
15
  if (!srv?.emit)
36
- return; // not served (unit tests, standalone boot) — nothing to notify
16
+ return; // not served yet
37
17
  try {
38
18
  void Promise.resolve(srv.emit(event, data)).catch((err) => {
39
19
  logger.warn(`${serviceName}.${event} subscriber failed (ignored):`, err);
@@ -1,23 +1,13 @@
1
1
  /**
2
- * Combine an unsigned transaction with a witness set from CIP-30 wallet signing
3
- *
4
- * CIP-30 signTx() returns only the witness set, not a complete signed transaction.
5
- * This function combines the original unsigned transaction with the witness set
6
- * to create a complete signed transaction that can be submitted to the network.
7
- *
8
- * @param unsignedTxCbor - The unsigned transaction CBOR (hex)
9
- * @param witnessSetCbor - The witness set CBOR from CIP-30 signTx() (hex)
10
- * @returns Complete signed transaction CBOR (hex)
2
+ * Combine an unsigned tx with the witness set a CIP-30 `signTx()` returns into a submittable signed tx.
3
+ * @returns complete signed transaction CBOR (hex)
11
4
  */
12
5
  export declare function combineTransactionWithWitnesses(unsignedTxCbor: string, witnessSetCbor: string): string;
13
6
  /**
14
- * Check if a CBOR string is a witness set (vs a full transaction)
15
- *
16
- * CIP-30 returns witness sets, not full transactions.
17
- * This helps detect when we need to call combineTransactionWithWitnesses.
18
- *
19
- * @param cborHex - CBOR hex string
20
- * @returns true if it's a witness set, false if it's a full transaction
7
+ * True when the CBOR is a CIP-30 witness set (map) rather than a full transaction (array).
8
+ * Reads the major type of the first byte only; a malformed map fails later in the combine step.
21
9
  */
22
10
  export declare function isWitnessSetCbor(cborHex: string): boolean;
11
+ /** The signed transaction: as given, or the unsigned one plus a CIP-30 witness set. */
12
+ export declare function toSignedTransaction(unsignedTxCbor: string | null | undefined, signedTxOrWitnessSet: string): string;
23
13
  //# sourceMappingURL=signing-helper.d.ts.map