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

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 (239) 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 +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -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
@@ -0,0 +1,13 @@
1
+ import { BackendError } from './errors';
2
+ import type { CardanoClient } from '../blockchain/cardano-client';
3
+ import type { Request } from '@sap/cds';
4
+ /** What an operator read on the chain for an unresolved outcome. */
5
+ export type ResolvedOutcome = 'confirmed' | 'failed';
6
+ /** The note a resolution leaves on the record: the outcome, who, when and why. */
7
+ export declare function resolutionNote(outcome: ResolvedOutcome, user: string | undefined, note: string | null | undefined, now?: Date): string;
8
+ /** Refuses a resolution whose txHash names another transaction than the record's. */
9
+ export declare function checkResolvedTxHash(req: Request, action: string, given: string | null | undefined, recorded: string | null | undefined): void;
10
+ export declare function refuseFailedWhileItCanLand(action: string, outcome: ResolvedOutcome, signedTxCbor: string | null | undefined, client: Pick<CardanoClient, 'readLedger' | 'network'>): Promise<void>;
11
+ /** The 409 for a record another call resolved first. */
12
+ export declare function resolvedConcurrently(action: string): BackendError;
13
+ //# sourceMappingURL=resolution.d.ts.map
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolutionNote = resolutionNote;
4
+ exports.checkResolvedTxHash = checkResolvedTxHash;
5
+ exports.refuseFailedWhileItCanLand = refuseFailedWhileItCanLand;
6
+ exports.resolvedConcurrently = resolvedConcurrently;
7
+ const errors_1 = require("./errors");
8
+ const error_codes_1 = require("./error-codes");
9
+ const landing_proof_1 = require("../blockchain/signing/landing-proof");
10
+ /** The note a resolution leaves on the record: the outcome, who, when and why. */
11
+ function resolutionNote(outcome, user, note, now = new Date()) {
12
+ const why = note?.trim() ? `: ${note.trim()}` : '';
13
+ return `${outcome} by ${user ?? 'unknown'} at ${now.toISOString()}${why}`.slice(0, 500);
14
+ }
15
+ /** Refuses a resolution whose txHash names another transaction than the record's. */
16
+ function checkResolvedTxHash(req, action, given, recorded) {
17
+ if (given && given.toLowerCase() !== (recorded ?? '').toLowerCase()) {
18
+ (0, errors_1.rejectInvalid)(req, action, `txHash ${given} is not the transaction of this record (${recorded ?? 'none'})`, 'txHash');
19
+ }
20
+ }
21
+ // A failed outcome needs bytes that can no longer land. A landing spends every input, so one spent
22
+ // input already rules it out; while every input is unspent and the bytes are not expired, they can
23
+ // still land, and failed is refused. Read before the request takes its connection.
24
+ async function refuseFailedWhileItCanLand(action, outcome, signedTxCbor, client) {
25
+ if (outcome !== 'failed' || !signedTxCbor || (0, landing_proof_1.isExpired)(signedTxCbor, client.network))
26
+ return;
27
+ let inputs;
28
+ try {
29
+ inputs = (0, landing_proof_1.landingFacts)(signedTxCbor).inputs;
30
+ }
31
+ catch {
32
+ return; // unreadable bytes cannot be sent either
33
+ }
34
+ if (!inputs.length)
35
+ return;
36
+ // an outpoint the backend does not know reads as spent
37
+ const { unspent } = await client.readLedger(inputs);
38
+ if (inputs.every((_, i) => unspent[i] === true)) {
39
+ throw new errors_1.BackendError(`${action}: the transaction can still land, every input it spends is unspent. ` +
40
+ 'Resolve it as failed once one of them is spent by another transaction', 409, error_codes_1.ERROR_CODES.OUTCOME_STILL_OPEN);
41
+ }
42
+ }
43
+ /** The 409 for a record another call resolved first. */
44
+ function resolvedConcurrently(action) {
45
+ return new errors_1.BackendError(`${action}: the record was resolved concurrently`, 409, error_codes_1.ERROR_CODES.RESOLVED_CONCURRENTLY);
46
+ }
47
+ //# sourceMappingURL=resolution.js.map
@@ -0,0 +1,15 @@
1
+ import cds from '@sap/cds';
2
+ /** The parts of a linked model definition this module reads. */
3
+ interface Typed {
4
+ items?: Typed;
5
+ elements?: Record<string, Typed | undefined>;
6
+ _target?: Typed;
7
+ scale?: number;
8
+ returns?: Typed;
9
+ actions?: Record<string, Typed | undefined>;
10
+ }
11
+ /** `value` with every Int64 and Decimal number as text; `value` itself when it holds none. */
12
+ export declare function numbersAsText(def: Typed | undefined, value: unknown): unknown;
13
+ export declare function answerNumbersAsText(srv: cds.Service): void;
14
+ export {};
15
+ //# sourceMappingURL=result-numbers.d.ts.map
@@ -0,0 +1,61 @@
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.numbersAsText = numbersAsText;
7
+ exports.answerNumbersAsText = answerNumbersAsText;
8
+ const cds_1 = __importDefault(require("@sap/cds"));
9
+ /** Text of an Int64 or Decimal value, in the form the database returns it. */
10
+ function numberText(def, value) {
11
+ const scale = def instanceof cds_1.default.builtin.classes.Decimal ? def.scale : undefined;
12
+ if (scale === undefined)
13
+ return String(value);
14
+ return typeof value === 'bigint' ? (scale ? `${value}.${'0'.repeat(scale)}` : String(value)) : value.toFixed(scale);
15
+ }
16
+ /** `value` with every Int64 and Decimal number as text; `value` itself when it holds none. */
17
+ function numbersAsText(def, value) {
18
+ if (!def || value === null || value === undefined)
19
+ return value;
20
+ if (Array.isArray(value)) {
21
+ // a to-many association has no `items`: its rows are rows of the target
22
+ const of = def.items ?? def;
23
+ let copy;
24
+ value.forEach((item, i) => {
25
+ const text = numbersAsText(of, item);
26
+ // Object.assign keeps what CAP adds to a result array, such as $count
27
+ if (text !== item)
28
+ (copy ??= Object.assign([], value))[i] = text;
29
+ });
30
+ return copy ?? value;
31
+ }
32
+ if (typeof value === 'number' || typeof value === 'bigint') {
33
+ const { Int64, Decimal } = cds_1.default.builtin.classes;
34
+ return def instanceof Int64 || def instanceof Decimal ? numberText(def, value) : value;
35
+ }
36
+ if (typeof value !== 'object')
37
+ return value;
38
+ const elements = (def._target ?? def).elements;
39
+ if (!elements)
40
+ return value;
41
+ let copy;
42
+ for (const [name, item] of Object.entries(value)) {
43
+ const text = numbersAsText(elements[name], item);
44
+ if (text !== item)
45
+ (copy ??= { ...value })[name] = text;
46
+ }
47
+ return copy ?? value;
48
+ }
49
+ // Answers reads and operations of `srv` with Int64 and Decimal as text. The result is replaced,
50
+ // never changed in place: a handler may answer with an object that other code keeps counting in.
51
+ function answerNumbersAsText(srv) {
52
+ srv.after('*', (_results, req) => {
53
+ const target = req.target;
54
+ const operations = (target?.actions ?? srv.actions);
55
+ const def = req.event === 'READ' ? target : operations?.[req.event]?.returns;
56
+ const text = numbersAsText(def, req.results);
57
+ if (text !== req.results)
58
+ req.reply(text);
59
+ });
60
+ }
61
+ //# sourceMappingURL=result-numbers.js.map
@@ -0,0 +1,7 @@
1
+ /** The number in `v`, or null when the column is empty or not a number. */
2
+ export declare function optionalNum(v: unknown): number | null;
3
+ /** The number in `v`, or `fallback` when the column is empty or not a number. */
4
+ export declare function requiredNum(v: unknown, fallback?: number): number;
5
+ /** A timestamp column as ISO text, or null when empty. */
6
+ export declare function timestamp(v: unknown): string | null;
7
+ //# sourceMappingURL=row-values.d.ts.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ // Database reads return Int64 and Decimal as text and timestamps in the adapter's own form.
3
+ // These turn a column value into the type the code works with.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.optionalNum = optionalNum;
6
+ exports.requiredNum = requiredNum;
7
+ exports.timestamp = timestamp;
8
+ /** The number in `v`, or null when the column is empty or not a number. */
9
+ function optionalNum(v) {
10
+ if (v === null || v === undefined || v === '')
11
+ return null;
12
+ const n = Number(v);
13
+ return Number.isNaN(n) ? null : n;
14
+ }
15
+ /** The number in `v`, or `fallback` when the column is empty or not a number. */
16
+ function requiredNum(v, fallback = 0) {
17
+ return optionalNum(v) ?? fallback;
18
+ }
19
+ /** A timestamp column as ISO text, or null when empty. */
20
+ function timestamp(v) {
21
+ if (v === null || v === undefined || v === '')
22
+ return null;
23
+ if (v instanceof Date)
24
+ return v.toISOString();
25
+ return String(v);
26
+ }
27
+ //# sourceMappingURL=row-values.js.map
@@ -1,26 +1,2 @@
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
1
  export declare function emitServiceEvent(serviceName: string, event: string, data: Record<string, unknown>): void;
26
2
  //# sourceMappingURL=service-events.d.ts.map
@@ -6,34 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.emitServiceEvent = emitServiceEvent;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
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
- */
9
+ // Emits a CAP service event in-process. Never throws and is silent before the service is served.
10
+ // Callers must emit after their transaction commits.
33
11
  function emitServiceEvent(serviceName, event, data) {
34
12
  const srv = cds_1.default.services?.[serviceName];
35
13
  if (!srv?.emit)
36
- return; // not served (unit tests, standalone boot) — nothing to notify
14
+ return; // not served yet
37
15
  try {
38
16
  void Promise.resolve(srv.emit(event, data)).catch((err) => {
39
17
  logger.warn(`${serviceName}.${event} subscriber failed (ignored):`, err);
@@ -1,23 +1,6 @@
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)
11
- */
1
+ /** Merges the witness set from CIP-30 `signTx()` into the unsigned tx. Returns signed CBOR hex. */
12
2
  export declare function combineTransactionWithWitnesses(unsignedTxCbor: string, witnessSetCbor: string): string;
13
- /**
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
21
- */
22
3
  export declare function isWitnessSetCbor(cborHex: string): boolean;
4
+ /** The signed transaction: as given, or the unsigned one plus a CIP-30 witness set. */
5
+ export declare function toSignedTransaction(unsignedTxCbor: string | null | undefined, signedTxOrWitnessSet: string): string;
23
6
  //# sourceMappingURL=signing-helper.d.ts.map
@@ -5,25 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.combineTransactionWithWitnesses = combineTransactionWithWitnesses;
7
7
  exports.isWitnessSetCbor = isWitnessSetCbor;
8
+ exports.toSignedTransaction = toSignedTransaction;
8
9
  const cds_1 = __importDefault(require("@sap/cds"));
9
10
  const cbor_1 = require("@harmoniclabs/cbor");
10
11
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
11
12
  const errors_1 = require("./errors");
12
13
  const logger = cds_1.default.log('SigningHelper');
13
- /**
14
- * Combine an unsigned transaction with a witness set from CIP-30 wallet signing
15
- *
16
- * CIP-30 signTx() returns only the witness set, not a complete signed transaction.
17
- * This function combines the original unsigned transaction with the witness set
18
- * to create a complete signed transaction that can be submitted to the network.
19
- *
20
- * @param unsignedTxCbor - The unsigned transaction CBOR (hex)
21
- * @param witnessSetCbor - The witness set CBOR from CIP-30 signTx() (hex)
22
- * @returns Complete signed transaction CBOR (hex)
23
- */
14
+ /** Merges the witness set from CIP-30 `signTx()` into the unsigned tx. Returns signed CBOR hex. */
24
15
  function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
25
16
  try {
26
- // Parse at raw CBOR level — no Cardano type validation, preserves all encoding metadata
17
+ // Raw CBOR level: no Cardano type validation, preserves all encoding metadata
27
18
  const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
28
19
  if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
29
20
  throw new errors_1.TransactionValidationError('Invalid transaction CBOR structure');
@@ -31,41 +22,29 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
31
22
  const walletWsObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(witnessSetCbor));
32
23
  // txObj.array[0] = body, [1] = witness_set, [2] = is_valid, [3] = auxiliary_data
33
24
  const origWs = txObj.array[1];
25
+ if (!(origWs instanceof cbor_1.CborMap) || !(walletWsObj instanceof cbor_1.CborMap)) {
26
+ throw new errors_1.TransactionValidationError('Witness set must be CBOR map per Cardano spec');
27
+ }
28
+ // The wallet signs with vkey witnesses (map key 0) or, for Byron addresses, bootstrap witnesses (key 2)
29
+ const isSignatureKey = (k) => k instanceof cbor_1.CborUInt && (Number(k.num) === 0 || Number(k.num) === 2);
30
+ const walletSignatures = walletWsObj.map.filter(e => isSignatureKey(e.k));
34
31
  let witnessCount = 0;
35
- if (origWs instanceof cbor_1.CborMap && walletWsObj instanceof cbor_1.CborMap) {
36
- // Find wallet's VKey witnesses (map key 0)
37
- const walletVkeyEntry = walletWsObj.map.find(e => e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0);
38
- if (walletVkeyEntry) {
39
- // Merge: keep all original entries (redeemers, datums, scripts at keys 3-7),
40
- // remove any existing key 0, then add wallet's key 0 (VKey witnesses)
41
- const mergedEntries = origWs.map
42
- .filter(e => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0))
43
- .concat([walletVkeyEntry]);
44
- // Construct new witness set CborMap preserving the original's encoding style
45
- txObj.array[1] = new cbor_1.CborMap(mergedEntries, {
46
- indefinite: origWs.indefinite,
47
- });
48
- // Count VKey witnesses — value may be CborArray or CborTag(258, CborArray) in Conway era
49
- const vkeyValue = walletVkeyEntry.v;
50
- if (vkeyValue instanceof cbor_1.CborArray) {
51
- witnessCount = vkeyValue.array.length;
52
- }
53
- else if (vkeyValue instanceof cbor_1.CborTag && vkeyValue.data instanceof cbor_1.CborArray) {
54
- witnessCount = vkeyValue.data.array.length;
55
- }
56
- else {
57
- throw new errors_1.TransactionValidationError('Unexpected VKey witness format in witness set');
58
- }
59
- }
32
+ for (const { v } of walletSignatures) {
33
+ // CborArray, or CborTag(258, CborArray) in Conway
34
+ const items = v instanceof cbor_1.CborArray ? v.array : v instanceof cbor_1.CborTag && v.data instanceof cbor_1.CborArray ? v.data.array : undefined;
35
+ if (!items)
36
+ throw new errors_1.TransactionValidationError('Unexpected witness format in witness set');
37
+ witnessCount += items.length;
60
38
  }
61
- else {
62
- throw new errors_1.TransactionValidationError('Witness set must be CBOR map per Cardano spec');
39
+ if (witnessCount === 0) {
40
+ throw new errors_1.TransactionValidationError('Witness set carries no vkey or bootstrap witness; the wallet did not sign');
63
41
  }
64
- // Re-encode the tx as a NEW outer CborArray so the encoder cannot short-circuit
65
- // to the original full-tx bytes via the outer value's subCborRef (which no longer
66
- // matches now that the witness set changed). The INNER element subCborRefs are
67
- // deliberately kept: that byte-preserves the body (array[0]), so the tx body hash
68
- // the witnesses signed stays identical.
42
+ // Keep original entries (redeemers, datums, scripts at keys 3-7), take the signatures from the wallet
43
+ const mergedEntries = origWs.map.filter(e => !isSignatureKey(e.k)).concat(walletSignatures);
44
+ // New witness set map preserving the original's encoding style
45
+ txObj.array[1] = new cbor_1.CborMap(mergedEntries, { indefinite: origWs.indefinite });
46
+ // New outer CborArray so the encoder cannot reuse the stale outer subCborRef; the inner
47
+ // subCborRefs are kept so the body bytes (and thus the signed body hash) stay identical.
69
48
  const signedTxCbor = (0, uint8array_utils_1.toHex)(cbor_1.Cbor.encode(new cbor_1.CborArray(txObj.array, { indefinite: txObj.indefinite })));
70
49
  logger.info({
71
50
  unsignedTxLength: unsignedTxCbor.length,
@@ -81,27 +60,19 @@ function combineTransactionWithWitnesses(unsignedTxCbor, witnessSetCbor) {
81
60
  throw new errors_1.TransactionValidationError(`Failed to combine transaction with witnesses: ${msg}`);
82
61
  }
83
62
  }
84
- /**
85
- * Check if a CBOR string is a witness set (vs a full transaction)
86
- *
87
- * CIP-30 returns witness sets, not full transactions.
88
- * This helps detect when we need to call combineTransactionWithWitnesses.
89
- *
90
- * @param cborHex - CBOR hex string
91
- * @returns true if it's a witness set, false if it's a full transaction
92
- */
63
+ // A witness set is a CBOR map, a full transaction an array. Only the first byte is read.
64
+ // A malformed map fails later in the combine step.
93
65
  function isWitnessSetCbor(cborHex) {
94
- try {
95
- const obj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(cborHex));
96
- // A full transaction is a CBOR array ([body, witness_set, is_valid, aux_data]);
97
- // a CIP-30 witness set is a CBOR map. The two shapes are unambiguous.
98
- if (obj instanceof cbor_1.CborArray)
99
- return false;
100
- return obj instanceof cbor_1.CborMap;
101
- }
102
- catch {
103
- // Invalid / unparseable CBOR
66
+ if (!/^[0-9a-f]{2}/i.test(cborHex))
104
67
  return false;
105
- }
68
+ return parseInt(cborHex.slice(0, 2), 16) >> 5 === 5;
69
+ }
70
+ /** The signed transaction: as given, or the unsigned one plus a CIP-30 witness set. */
71
+ function toSignedTransaction(unsignedTxCbor, signedTxOrWitnessSet) {
72
+ if (!isWitnessSetCbor(signedTxOrWitnessSet))
73
+ return signedTxOrWitnessSet;
74
+ if (!unsignedTxCbor)
75
+ throw new errors_1.TransactionValidationError('No unsigned transaction to add the witness set to');
76
+ return combineTransactionWithWitnesses(unsignedTxCbor, signedTxOrWitnessSet);
106
77
  }
107
78
  //# sourceMappingURL=signing-helper.js.map