@odatano/core 1.11.0 → 2.0.0-rc.10

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 (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -17,6 +17,7 @@ exports.mapNetworkInfo = mapNetworkInfo;
17
17
  exports.mapBlock = mapBlock;
18
18
  exports.mapEpoch = mapEpoch;
19
19
  exports.mapTransactionMetadata = mapTransactionMetadata;
20
+ exports.metadataIdFor = metadataIdFor;
20
21
  exports.mapPool = mapPool;
21
22
  exports.mapAsset = mapAsset;
22
23
  exports.mapAssetHistory = mapAssetHistory;
@@ -31,11 +32,14 @@ exports.mapTransactionSubmission = mapTransactionSubmission;
31
32
  exports.mapAddressSigningRequest = mapAddressSigningRequest;
32
33
  exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
33
34
  exports.normalizeCostModels = normalizeCostModels;
35
+ exports.decodeAssetName = decodeAssetName;
34
36
  exports.computeCip14Fingerprint = computeCip14Fingerprint;
35
37
  exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
36
38
  const cds_1 = __importDefault(require("@sap/cds"));
39
+ const node_util_1 = require("node:util");
37
40
  const blake2b_1 = __importDefault(require("blake2b"));
38
41
  const bech32_1 = require("bech32");
42
+ const client_1 = require("@cardano-ogmios/client");
39
43
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
40
44
  const logger = cds_1.default.log('mappers');
41
45
  const errors_1 = require("./errors");
@@ -50,7 +54,9 @@ const errors_1 = require("./errors");
50
54
  */
51
55
  function mapTransaction(providerTx) {
52
56
  // determine presence of optional data
53
- const hasMetadata = providerTx.metadata != null && (Array.isArray(providerTx.metadata));
57
+ // length check matters: the Ogmios chain-sync mapper produced `[]` for metadata-less
58
+ // txs, which the old `Array.isArray` test counted as "has metadata"
59
+ const hasMetadata = Array.isArray(providerTx.metadata) && providerTx.metadata.length > 0;
54
60
  const hasInputs = Array.isArray(providerTx.inputs) && providerTx.inputs.length > 0;
55
61
  const hasOutputs = Array.isArray(providerTx.outputs) && providerTx.outputs.length > 0;
56
62
  return {
@@ -86,7 +92,9 @@ function mapTransactionInputs(txHash, txInputs) {
86
92
  return {
87
93
  tx_hash: txHash,
88
94
  inputIndex: inputIndex,
89
- address_address: input.address,
95
+ // `|| null`: unresolved chain-sync inputs carry '' — persist a null FK, not a
96
+ // dangling empty-string Addresses association (lazy-path inputs are never empty)
97
+ address_address: input.address || null,
90
98
  utxoData_dataHash: input.dataHash || null,
91
99
  utxoData_inlineDatum: input.inlineDatum || null,
92
100
  utxoData_referenceScriptHash: input.referenceScriptHash || null,
@@ -420,6 +428,8 @@ function mapBlock(providerBlockData, epochData) {
420
428
  slotLeader: providerBlockData.slotLeader ?? null,
421
429
  epochNumber: epochData?.epoch ?? providerBlockData.epoch,
422
430
  epoch: epochData,
431
+ // absolute slot — the crawler's reorg cut axis (same axis as Transactions.slot)
432
+ slot: providerBlockData.slot ?? null,
423
433
  epochSlot: providerBlockData.epochSlot,
424
434
  size: providerBlockData.size,
425
435
  txCount: providerBlockData.txCount,
@@ -455,21 +465,55 @@ function mapEpoch(providerEpochData) {
455
465
  function mapTransactionMetadata(providerLabels) {
456
466
  const rows = [];
457
467
  for (const lbl of providerLabels) {
458
- const numericId = Number(lbl.label);
459
- // Metadata labels are uint64; the exact value is kept in the `label` string.
460
- // The numeric `id` key (now Integer64) is exact up to 2^53 — warn beyond that.
461
- if (!Number.isSafeInteger(numericId)) {
462
- logger.warn(`Metadata label ${lbl.label} exceeds safe-integer range — numeric id key may lose precision (string label is exact)`);
468
+ const id = metadataIdFor(lbl.label);
469
+ if (id === null) {
470
+ // A NaN key would fail the whole bulk write (PostgreSQL: "invalid input syntax
471
+ // for type bigint") and, in the crawler, count towards the poison-block latch.
472
+ logger.warn(`Metadata label ${JSON.stringify(lbl.label)} of tx ${lbl.txHash} is not a uint64 — row skipped`);
473
+ continue;
463
474
  }
464
475
  rows.push({
465
- id: numericId,
476
+ // uint64 label → int64 key, exact (see metadataIdFor); `label` keeps the original string
477
+ id: id,
466
478
  tx_hash: lbl.txHash,
467
479
  label: lbl.label.toString(),
468
- payload: lbl.json !== undefined ? JSON.stringify(lbl.json) : null,
480
+ // Ogmios' parser deliberately exposes numeric metadata as native bigint.
481
+ // Its matching serializer writes those values as exact JSON number tokens;
482
+ // native JSON.stringify would throw, while Number coercion would truncate.
483
+ payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
469
484
  });
470
485
  }
471
486
  return rows;
472
487
  }
488
+ /**
489
+ * Metadata labels are uint64, the `TransactionMetadata.id` key is Integer64 (int64).
490
+ * Labels >= 2^63 are mapped through two's complement (BigInt.asIntN) so they stay
491
+ * unique and in range – preprod tx ee4f7c88… carries label 17802948329108123211,
492
+ * which PostgreSQL rejected as "out of range for type bigint" and halted the
493
+ * crawler. Beyond 2^53 the value is passed as a decimal string so that no
494
+ * precision is lost on the way to the database (CAP accepts strings for
495
+ * Integer64); `label` always keeps the original text.
496
+ *
497
+ * @returns the int64 key, or null when the label is not a non-negative integer
498
+ * (the caller skips the row — a NaN key would fail the whole bulk write)
499
+ */
500
+ function metadataIdFor(label) {
501
+ let big;
502
+ if (typeof label === 'number') {
503
+ if (!Number.isFinite(label))
504
+ return null;
505
+ big = BigInt(Math.trunc(label));
506
+ }
507
+ else {
508
+ const text = String(label).trim();
509
+ if (!/^\d+$/.test(text))
510
+ return null;
511
+ big = BigInt(text);
512
+ }
513
+ const wrapped = BigInt.asIntN(64, big);
514
+ const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
515
+ return safe ? Number(wrapped) : wrapped.toString();
516
+ }
473
517
  /**
474
518
  * Map Pool Data
475
519
  * Converts provider pool data into PoolRow format
@@ -839,9 +883,35 @@ function normalizeCostModels(raw) {
839
883
  * @returns {string} UTF-8 string or original hex if conversion fails
840
884
  */
841
885
  function hexToUtf8(hex) {
886
+ return decodeAssetName(hex);
887
+ }
888
+ // ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the
889
+ // round trip (Buffer.toString('utf8') kept it; TextDecoder's default drops it).
890
+ const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
891
+ /**
892
+ * Decode an asset name (hex bytes) into its display string.
893
+ *
894
+ * Asset names are arbitrary bytes. When they are not valid UTF-8, or when they
895
+ * contain U+0000, the hex form is returned unchanged: PostgreSQL rejects NUL in
896
+ * `text` and in the JSON documents @cap-js/postgres uses for bulk INSERT/UPSERT
897
+ * ("unsupported Unicode escape sequence"), which halted the crawler on preprod
898
+ * block 4281919 (asset name ending in 0x00). SQLite accepted the same bytes
899
+ * silently. `assetNameHex` always keeps the exact bytes, so nothing is lost.
900
+ *
901
+ * @param hex - asset name as hex string
902
+ * @returns UTF-8 text, or the hex string when the bytes are not clean text
903
+ */
904
+ function decodeAssetName(hex) {
842
905
  if (!hex)
843
906
  return hex;
844
- return Buffer.from(hex, 'hex').toString('utf8');
907
+ let text;
908
+ try {
909
+ text = strictUtf8.decode(Buffer.from(hex, 'hex'));
910
+ }
911
+ catch {
912
+ return hex;
913
+ }
914
+ return text.includes('\u0000') ? hex : text;
845
915
  }
846
916
  /**
847
917
  * Parse asset unit (policyId + assetNameHex) into components.
@@ -0,0 +1,57 @@
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
+ */
6
+ export interface RateLimiterOptions {
7
+ windowMs: number;
8
+ maxRequests: number;
9
+ /** Max tracked keys (default 10 000). */
10
+ maxKeys?: number;
11
+ /** Stale-key sweep interval (default 60 000 ms). */
12
+ 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
+ maxKeysPerGroup?: number;
20
+ }
21
+ export interface RateCheckResult {
22
+ allowed: boolean;
23
+ retryAfterMs: number;
24
+ }
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
+ export declare function principalRateKey(req: unknown, scope: string): string;
32
+ export declare class RateLimiter {
33
+ private readonly windowMs;
34
+ private readonly maxRequests;
35
+ private readonly maxKeys;
36
+ private readonly maxKeysPerGroup;
37
+ private readonly groupCounts;
38
+ private readonly hits;
39
+ private readonly sweepTimer;
40
+ constructor(opts: RateLimiterOptions);
41
+ check(key: string): RateCheckResult;
42
+ /** Would ONE more hit fit? Records nothing. */
43
+ peek(key: string): RateCheckResult;
44
+ /** Forget every key (tests). */
45
+ 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
+ */
50
+ checkMany(key: string, count: number): RateCheckResult;
51
+ private dropKey;
52
+ /** Remove keys with no hits within the current window. */
53
+ private sweep;
54
+ /** Stop the background sweep timer. */
55
+ destroy(): void;
56
+ }
57
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1,126 @@
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
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.RateLimiter = void 0;
9
+ exports.principalRateKey = principalRateKey;
10
+ /** The group a key belongs to: everything before the first ':' (the principal). */
11
+ function groupOf(key) {
12
+ const i = key.indexOf(':');
13
+ return i < 0 ? key : key.slice(0, i);
14
+ }
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
+ */
21
+ function principalRateKey(req, scope) {
22
+ const r = req;
23
+ const user = r?.user?.id;
24
+ const ip = r?._?.req?.ip ?? r?.http?.req?.ip ?? r?.ip;
25
+ const principal = user ? `user=${String(user)}`
26
+ : ip ? `ip=${String(ip).replace(/:/g, '.')}`
27
+ : 'anonymous';
28
+ return `${principal}:${scope}`;
29
+ }
30
+ class RateLimiter {
31
+ windowMs;
32
+ maxRequests;
33
+ maxKeys;
34
+ maxKeysPerGroup;
35
+ groupCounts = new Map();
36
+ hits = new Map();
37
+ sweepTimer;
38
+ constructor(opts) {
39
+ this.windowMs = opts.windowMs;
40
+ this.maxRequests = opts.maxRequests;
41
+ this.maxKeys = opts.maxKeys || 10_000;
42
+ this.maxKeysPerGroup = opts.maxKeysPerGroup || 64;
43
+ this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs || 60_000);
44
+ if (typeof this.sweepTimer.unref === 'function')
45
+ this.sweepTimer.unref();
46
+ }
47
+ check(key) {
48
+ return this.checkMany(key, 1);
49
+ }
50
+ /** Would ONE more hit fit? Records nothing. */
51
+ peek(key) {
52
+ const now = Date.now();
53
+ const inWindow = (this.hits.get(key) ?? []).filter((t) => t > now - this.windowMs);
54
+ if (inWindow.length < this.maxRequests)
55
+ return { allowed: true, retryAfterMs: 0 };
56
+ const oldest = Math.min(...inWindow);
57
+ return { allowed: false, retryAfterMs: Math.max(oldest + this.windowMs - now, 0) };
58
+ }
59
+ /** Forget every key (tests). */
60
+ reset() {
61
+ this.hits.clear();
62
+ this.groupCounts.clear();
63
+ }
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
+ */
68
+ checkMany(key, count) {
69
+ if (count <= 0)
70
+ return { allowed: true, retryAfterMs: 0 };
71
+ const now = Date.now();
72
+ const windowStart = now - this.windowMs;
73
+ if (!this.hits.has(key)) {
74
+ const group = groupOf(key);
75
+ if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
76
+ return { allowed: false, retryAfterMs: this.windowMs };
77
+ }
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).
80
+ if (this.hits.size >= this.maxKeys) {
81
+ const oldest = this.hits.keys().next().value;
82
+ if (oldest !== undefined)
83
+ this.dropKey(oldest);
84
+ }
85
+ this.groupCounts.set(group, (this.groupCounts.get(group) ?? 0) + 1);
86
+ }
87
+ let timestamps = this.hits.get(key) || [];
88
+ timestamps = timestamps.filter((t) => t > windowStart);
89
+ this.hits.delete(key); // re-insert below = most recently used
90
+ if (timestamps.length + count > this.maxRequests) {
91
+ timestamps.sort((a, b) => a - b);
92
+ const oldestInWindow = timestamps[0];
93
+ const retryAfterMs = oldestInWindow === undefined ? this.windowMs : oldestInWindow + this.windowMs - now;
94
+ this.hits.set(key, timestamps);
95
+ return { allowed: false, retryAfterMs: Math.max(retryAfterMs, 0) };
96
+ }
97
+ for (let i = 0; i < count; i++)
98
+ timestamps.push(now);
99
+ this.hits.set(key, timestamps);
100
+ return { allowed: true, retryAfterMs: 0 };
101
+ }
102
+ dropKey(key) {
103
+ if (!this.hits.delete(key))
104
+ return;
105
+ const group = groupOf(key);
106
+ const n = (this.groupCounts.get(group) ?? 1) - 1;
107
+ if (n <= 0)
108
+ this.groupCounts.delete(group);
109
+ else
110
+ this.groupCounts.set(group, n);
111
+ }
112
+ /** Remove keys with no hits within the current window. */
113
+ sweep() {
114
+ const windowStart = Date.now() - this.windowMs;
115
+ for (const [key, timestamps] of this.hits) {
116
+ if (!timestamps.some((t) => t > windowStart))
117
+ this.dropKey(key);
118
+ }
119
+ }
120
+ /** Stop the background sweep timer. */
121
+ destroy() {
122
+ clearInterval(this.sweepTimer);
123
+ }
124
+ }
125
+ exports.RateLimiter = RateLimiter;
126
+ //# sourceMappingURL=rate-limiter.js.map
@@ -0,0 +1,26 @@
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.
24
+ */
25
+ export declare function emitServiceEvent(serviceName: string, event: string, data: Record<string, unknown>): void;
26
+ //# sourceMappingURL=service-events.d.ts.map
@@ -0,0 +1,46 @@
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.emitServiceEvent = emitServiceEvent;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const logger = cds_1.default.log('ServiceEvents');
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.
32
+ */
33
+ function emitServiceEvent(serviceName, event, data) {
34
+ const srv = cds_1.default.services?.[serviceName];
35
+ if (!srv?.emit)
36
+ return; // not served (unit tests, standalone boot) — nothing to notify
37
+ try {
38
+ void Promise.resolve(srv.emit(event, data)).catch((err) => {
39
+ logger.warn(`${serviceName}.${event} subscriber failed (ignored):`, err);
40
+ });
41
+ }
42
+ catch (err) {
43
+ logger.warn(`${serviceName}.${event} could not be emitted (ignored):`, err);
44
+ }
45
+ }
46
+ //# sourceMappingURL=service-events.js.map
@@ -0,0 +1,71 @@
1
+ import type { JSONValue } from './types';
2
+ /**
3
+ * Shared parsers for the Build*-action JSON payload fields. Used by the
4
+ * synchronous CardanoTransactionService handlers AND the wallet-worker's
5
+ * request transformation (srv/blockchain/wallet-worker/build-request.ts) so
6
+ * both paths accept exactly the same payload shape.
7
+ *
8
+ * Result contract: { parsed } on success (undefined for absent/empty input →
9
+ * no-op) or { error } with a caller-presentable message.
10
+ */
11
+ export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson'): {
12
+ parsed?: Array<{
13
+ txHash: string;
14
+ outputIndex: number;
15
+ }>;
16
+ error?: string;
17
+ };
18
+ /**
19
+ * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
20
+ * Same result contract as the other parse* helpers.
21
+ */
22
+ export declare function parseRequiredSigners(requiredSignersJson: string | undefined): {
23
+ parsed?: string[];
24
+ error?: string;
25
+ };
26
+ /**
27
+ * Parse and validate an assetsJson array ({unit, quantity} entries) with the same
28
+ * per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
29
+ * into the builder and surfaced as 500s.
30
+ */
31
+ export declare function parseAssetsArray(assetsJson: string | undefined, fieldName: string): {
32
+ parsed?: Array<{
33
+ unit: string;
34
+ quantity: string;
35
+ }>;
36
+ error?: string;
37
+ };
38
+ /** Upper bound on extra outputs per transaction (defence against tx-size blow-up). */
39
+ export declare const MAX_EXTRA_OUTPUTS = 32;
40
+ export interface ParsedExtraOutput {
41
+ address: string;
42
+ lovelaceAmount: string;
43
+ assets?: Array<{
44
+ unit: string;
45
+ quantity: string;
46
+ }>;
47
+ inlineDatum?: JSONValue;
48
+ referenceScript?: string;
49
+ }
50
+ /**
51
+ * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
52
+ * for empty array → no-op) or { error } on validation failure.
53
+ */
54
+ export declare function parseExtraOutputs(extraOutputsJson: string | undefined): {
55
+ parsed?: ParsedExtraOutput[];
56
+ error?: string;
57
+ };
58
+ /**
59
+ * Parse the optional PER-ACTION policy fields of a mintActionsJson entry
60
+ * (multi-policy mint FR): `mintingPolicyScript` (CBOR hex, applied as-is; a
61
+ * parameterized per-action script must be pre-applied by the caller) and
62
+ * `redeemerJson` (a JSON-encoded string, same convention as extraOutputs'
63
+ * inlineDatumJson). Absent fields fall back to the action's top-level
64
+ * script/redeemer at build time.
65
+ */
66
+ export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number): {
67
+ script?: string;
68
+ redeemer?: JSONValue;
69
+ error?: string;
70
+ };
71
+ //# sourceMappingURL=tx-request-parsers.d.ts.map