@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@cds-models/CardanoAgentService/index.d.ts +1 -5
- package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
- package/@cds-models/CardanoIndexerService/index.js +7 -0
- package/package.json +1 -1
- package/src/index.d.ts +4 -10
- package/src/index.js +6 -16
- package/src/plugin.js +11 -27
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +39 -150
- package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
- package/srv/blockchain/backends/cardano-backend.js +1 -5
- package/srv/blockchain/backends/koios-backend.d.ts +26 -71
- package/srv/blockchain/backends/koios-backend.js +50 -132
- package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
- package/srv/blockchain/backends/ogmios-backend.js +71 -179
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
- package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
- package/srv/blockchain/cardano-client.d.ts +43 -216
- package/srv/blockchain/cardano-client.js +49 -234
- package/srv/blockchain/cardano-indexer.d.ts +79 -357
- package/srv/blockchain/cardano-indexer.js +98 -406
- package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
- package/srv/blockchain/cardano-tx-builder.js +21 -107
- package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
- package/srv/blockchain/crawler/certificate-backfill.js +150 -0
- package/srv/blockchain/crawler/crawler.d.ts +41 -145
- package/srv/blockchain/crawler/crawler.js +57 -172
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +2 -6
- package/srv/blockchain/crawler/index.js +4 -9
- package/srv/blockchain/crawler/sync-state.d.ts +17 -39
- package/srv/blockchain/crawler/sync-state.js +23 -55
- package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
- package/srv/blockchain/crawler/utxo-set-import.js +8 -28
- package/srv/blockchain/ledger-state.d.ts +3 -12
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -48
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
- package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +9 -22
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
- package/srv/cardano-agent-service.cds +1 -5
- package/srv/cardano-agent-service.js +3 -7
- package/srv/cardano-indexer-service.cds +32 -4
- package/srv/cardano-indexer-service.js +83 -15
- package/srv/cardano-service.js +36 -98
- package/srv/cardano-sign-service.cds +1 -1
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +1 -1
- package/srv/cardano-tx-service.js +54 -174
- package/srv/cardano-worker-service.js +7 -15
- package/srv/server.d.ts +27 -86
- package/srv/server.js +52 -148
- package/srv/utils/agent-grants-config.d.ts +11 -50
- package/srv/utils/agent-grants-config.js +12 -45
- package/srv/utils/agent-grants.d.ts +34 -123
- package/srv/utils/agent-grants.js +57 -156
- package/srv/utils/agent-token-auth.d.ts +2 -5
- package/srv/utils/agent-token-auth.js +2 -5
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +19 -68
- package/srv/utils/const.js +20 -69
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +2 -7
- package/srv/utils/db-indexes.js +7 -34
- package/srv/utils/db-sanitize.d.ts +5 -18
- package/srv/utils/db-sanitize.js +6 -19
- package/srv/utils/error-codes.d.ts +18 -73
- package/srv/utils/error-codes.js +17 -70
- package/srv/utils/errors.d.ts +29 -191
- package/srv/utils/errors.js +44 -229
- package/srv/utils/liveness.d.ts +2 -9
- package/srv/utils/liveness.js +3 -11
- package/srv/utils/mappers.d.ts +50 -298
- package/srv/utils/mappers.js +80 -386
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-order-nulls.js +4 -23
- package/srv/utils/plutus-placeholders.d.ts +6 -18
- package/srv/utils/plutus-placeholders.js +6 -20
- package/srv/utils/rate-limiter.d.ts +6 -17
- package/srv/utils/rate-limiter.js +5 -15
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +18 -92
- package/srv/utils/tx-build-helper.js +32 -123
- package/srv/utils/tx-request-parsers.d.ts +7 -26
- package/srv/utils/tx-request-parsers.js +7 -26
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +67 -206
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +19 -89
- package/srv/utils/validators.js +31 -138
|
@@ -18,20 +18,12 @@ const plutus_data_1 = require("@harmoniclabs/plutus-data");
|
|
|
18
18
|
const uplc_1 = require("@harmoniclabs/uplc");
|
|
19
19
|
const cbor_1 = require("@harmoniclabs/cbor");
|
|
20
20
|
const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
|
|
21
|
-
/**
|
|
22
|
-
* Extract lovelace amount from UTxO
|
|
23
|
-
* @param u UTxO to extract from
|
|
24
|
-
* @returns {bigint} lovelace amount
|
|
25
|
-
*/
|
|
21
|
+
/** Lovelace amount of a UTxO. */
|
|
26
22
|
function getLovelace(u) {
|
|
27
23
|
const entry = u.amount.find(a => (a.unit).toLowerCase() === "lovelace");
|
|
28
24
|
return BigInt(entry?.quantity ?? "0");
|
|
29
25
|
}
|
|
30
|
-
/**
|
|
31
|
-
* Assert that UTxO contains only ADA (lovelace)
|
|
32
|
-
* @param u UTxO to check
|
|
33
|
-
* @throws {MixedAssetsError} if UTxO contains non-ADA assets
|
|
34
|
-
*/
|
|
26
|
+
/** Throws MixedAssetsError when the UTxO carries non-ADA assets. */
|
|
35
27
|
function assertAdaOnly(u) {
|
|
36
28
|
const nonAda = u.amount.filter(a => (a.unit).toLowerCase() !== "lovelace" && BigInt(a.quantity) !== 0n);
|
|
37
29
|
if (nonAda.length > 0) {
|
|
@@ -39,27 +31,18 @@ function assertAdaOnly(u) {
|
|
|
39
31
|
}
|
|
40
32
|
}
|
|
41
33
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* @param txCbor transaction in CBOR hex format
|
|
45
|
-
* @returns {string} transaction hash (64 character hex string)
|
|
46
|
-
* @throws {Error} if CBOR is invalid or transaction hash cannot be extracted
|
|
34
|
+
* Transaction hash of a signed or unsigned tx CBOR: blake2b-256 over the body bytes, so witnesses do not affect it.
|
|
35
|
+
* @returns 64-char hex string
|
|
47
36
|
*/
|
|
48
37
|
function getTxHashFromCbor(txCbor) {
|
|
49
38
|
if (!txCbor || typeof txCbor !== 'string') {
|
|
50
39
|
throw new Error('Invalid input: txCbor must be a non-empty string');
|
|
51
40
|
}
|
|
52
|
-
//
|
|
53
|
-
// so an odd-length string is malformed and would otherwise surface as a confusing
|
|
54
|
-
// "Failed to parse transaction CBOR" from fromHex/Cbor.parse rather than a clear
|
|
55
|
-
// input-validation error.
|
|
41
|
+
// Even length: an odd hex string would otherwise fail later as a confusing parse error
|
|
56
42
|
if (!/^[a-fA-F0-9]+$/.test(txCbor) || txCbor.length % 2 !== 0) {
|
|
57
43
|
throw new Error('Invalid input: txCbor must be a valid hex string');
|
|
58
44
|
}
|
|
59
|
-
//
|
|
60
|
-
// subCborRef.toBuffer() returns the exact bytes as received — no re-serialization, so
|
|
61
|
-
// the hash matches what was signed. We stay at the raw-CBOR level (never instantiate
|
|
62
|
-
// the high-level Tx type) for that byte-exactness.
|
|
45
|
+
// Hash the ORIGINAL body bytes via subCborRef (no re-serialization), so it matches what was signed
|
|
63
46
|
try {
|
|
64
47
|
const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
|
|
65
48
|
if (!(tx instanceof cbor_1.CborArray) || tx.array.length < 1 || !tx.array[0].subCborRef) {
|
|
@@ -69,21 +52,12 @@ function getTxHashFromCbor(txCbor) {
|
|
|
69
52
|
return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(bodyBytes));
|
|
70
53
|
}
|
|
71
54
|
catch (err) {
|
|
72
|
-
// typed 400 — a plain Error here surfaced as a 500 to the consumer
|
|
73
55
|
throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
|
|
74
56
|
}
|
|
75
57
|
}
|
|
76
58
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
* UTxO cache. Works at the raw-CBOR level for the same reason as
|
|
80
|
-
* getTxHashFromCbor (byte-exact, no high-level Tx round-trip).
|
|
81
|
-
*
|
|
82
|
-
* Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
|
|
83
|
-
* addresses) are skipped — invalidation is best-effort per address.
|
|
84
|
-
*
|
|
85
|
-
* @param txCbor transaction in CBOR hex format
|
|
86
|
-
* @throws {TransactionValidationError} if the CBOR is not a transaction
|
|
59
|
+
* Consumed input refs and output addresses of a tx CBOR: the UTxO-cache rows a submit makes stale.
|
|
60
|
+
* Outputs whose address bytes cannot be decoded (Byron) are skipped.
|
|
87
61
|
*/
|
|
88
62
|
function extractTxCacheTargets(txCbor) {
|
|
89
63
|
let body;
|
|
@@ -98,7 +72,7 @@ function extractTxCacheTargets(txCbor) {
|
|
|
98
72
|
throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
|
|
99
73
|
}
|
|
100
74
|
const bodyValue = (key) => body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v;
|
|
101
|
-
// key 0: inputs
|
|
75
|
+
// key 0: inputs, plain array or CBOR tag-258 set (Conway)
|
|
102
76
|
const inputs = [];
|
|
103
77
|
let inputsObj = bodyValue(0);
|
|
104
78
|
if (inputsObj instanceof cbor_1.CborTag)
|
|
@@ -112,7 +86,7 @@ function extractTxCacheTargets(txCbor) {
|
|
|
112
86
|
}
|
|
113
87
|
}
|
|
114
88
|
}
|
|
115
|
-
// key 1: outputs
|
|
89
|
+
// key 1: outputs, post-Alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
|
|
116
90
|
const outputAddresses = new Set();
|
|
117
91
|
const outputsObj = bodyValue(1);
|
|
118
92
|
if (outputsObj instanceof cbor_1.CborArray) {
|
|
@@ -126,29 +100,18 @@ function extractTxCacheTargets(txCbor) {
|
|
|
126
100
|
outputAddresses.add(cardano_ledger_ts_1.Address.fromBuffer(addrObj.bytes).toString());
|
|
127
101
|
}
|
|
128
102
|
catch {
|
|
129
|
-
// non-Shelley address bytes
|
|
103
|
+
// non-Shelley address bytes: nothing cached under a bech32 key
|
|
130
104
|
}
|
|
131
105
|
}
|
|
132
106
|
}
|
|
133
107
|
return { inputs, outputAddresses: [...outputAddresses] };
|
|
134
108
|
}
|
|
135
109
|
/**
|
|
136
|
-
* Maps
|
|
137
|
-
*
|
|
138
|
-
* When no assetUnit is provided, extracts it from the error message if possible
|
|
139
|
-
* (e.g. "not enough <policyId.assetName>"), falling back to 'lovelace'.
|
|
140
|
-
* @param err Error from builder
|
|
141
|
-
* @param assetUnit Optional asset unit override (auto-extracted from error message if omitted)
|
|
142
|
-
* @param context Optional build-flow context (e.g. the collateral/funding partition)
|
|
143
|
-
* appended to the consumer-facing message — the builder's own message
|
|
144
|
-
* has no way of knowing it
|
|
145
|
-
* @throws {InsufficientFundsError} if error is related to insufficient funds
|
|
146
|
-
* @throws {Error} original error if not mappable
|
|
110
|
+
* Maps Buildooor errors to typed BackendErrors. Asset unit is parsed from "not enough <unit>" when not given;
|
|
111
|
+
* `context` (e.g. the collateral partition) is appended to the consumer-facing message.
|
|
147
112
|
*/
|
|
148
113
|
function mapBuilderError(err, assetUnit, context) {
|
|
149
|
-
//
|
|
150
|
-
// validation details) — re-wrapping them into a generic InsufficientFundsError
|
|
151
|
-
// because their MESSAGE happens to contain "balance"/"insufficient" destroys that.
|
|
114
|
+
// Typed errors keep their own status and payload
|
|
152
115
|
if (err instanceof errors_1.BackendError) {
|
|
153
116
|
throw err;
|
|
154
117
|
}
|
|
@@ -162,24 +125,19 @@ function mapBuilderError(err, assetUnit, context) {
|
|
|
162
125
|
const match = msg.match(/not enough\s+([a-f0-9.]+)/i);
|
|
163
126
|
return match?.[1] || 'lovelace';
|
|
164
127
|
})();
|
|
165
|
-
//
|
|
166
|
-
// context) instead of a meaningless "required 0, available 0".
|
|
128
|
+
// No amounts known here: surface the builder's own message instead of "required 0, available 0"
|
|
167
129
|
throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err, context ? `${rawMsg} (${context})` : rawMsg);
|
|
168
130
|
}
|
|
169
131
|
throw err;
|
|
170
132
|
}
|
|
171
|
-
/**
|
|
172
|
-
* Parse asset unit string into policyId and assetName
|
|
173
|
-
* Format: policyId (56 hex chars) + assetName (remaining hex)
|
|
174
|
-
* Used by the Buildooor transaction builder
|
|
175
|
-
*/
|
|
133
|
+
/** Split an asset unit into policyId (56 hex chars) and assetName (remaining hex). */
|
|
176
134
|
function parseAssetUnit(assetUnit) {
|
|
177
135
|
return {
|
|
178
136
|
policyId: assetUnit.substring(0, 56),
|
|
179
137
|
assetName: assetUnit.substring(56)
|
|
180
138
|
};
|
|
181
139
|
}
|
|
182
|
-
/** Allowed keys in PlutusData JSON
|
|
140
|
+
/** Allowed keys in PlutusData JSON; anything else is stripped */
|
|
183
141
|
const PLUTUS_DATA_ALLOWED_KEYS = new Set([
|
|
184
142
|
'constructor', 'constr', 'fields', 'int', 'bytes', 'list', 'map', 'k', 'v'
|
|
185
143
|
]);
|
|
@@ -193,11 +151,7 @@ function sanitizePlutusKeys(obj) {
|
|
|
193
151
|
}
|
|
194
152
|
return clean;
|
|
195
153
|
}
|
|
196
|
-
/**
|
|
197
|
-
* Normalize PlutusData JSON from cardano-cli format ("constructor") to
|
|
198
|
-
* Buildooor format ("constr"), recursively through fields/list/map.
|
|
199
|
-
* Also strips unrecognized keys for safety.
|
|
200
|
-
*/
|
|
154
|
+
/** Normalize cardano-cli "constructor" to Buildooor "constr" recursively; strips unknown keys. */
|
|
201
155
|
function normalizeConstructorKey(obj) {
|
|
202
156
|
const safe = sanitizePlutusKeys(obj);
|
|
203
157
|
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
@@ -222,17 +176,7 @@ function normalizeConstructorKey(obj) {
|
|
|
222
176
|
}
|
|
223
177
|
return safe;
|
|
224
178
|
}
|
|
225
|
-
/**
|
|
226
|
-
* Convert JSON value to Buildooor PlutusData (Data type).
|
|
227
|
-
* Accepts both cardano-cli format ("constructor") and Buildooor format ("constr").
|
|
228
|
-
* - { "int": 42 } → DataI(42)
|
|
229
|
-
* - { "bytes": "deadbeef" } → DataB("deadbeef")
|
|
230
|
-
* - { "list": [...] } → DataList([...])
|
|
231
|
-
* - { "map": [{ "k": ..., "v": ... }] } → DataMap([...])
|
|
232
|
-
* - { "constructor": 0, "fields": [...] } or { "constr": 0, "fields": [...] } → DataConstr(0, [...])
|
|
233
|
-
* @param json JSON value representing PlutusData
|
|
234
|
-
* @returns Buildooor Data object
|
|
235
|
-
*/
|
|
179
|
+
/** JSON (`int` / `bytes` / `list` / `map` / `constructor`|`constr`) to Buildooor PlutusData. */
|
|
236
180
|
function jsonToPlutusData(json) {
|
|
237
181
|
if (json === null || json === undefined) {
|
|
238
182
|
throw new Error('PlutusData JSON cannot be null or undefined');
|
|
@@ -244,21 +188,13 @@ function jsonToPlutusData(json) {
|
|
|
244
188
|
throw new Error(`Unsupported PlutusData JSON format: expected an object with "int", "bytes", "list", "map", or "constructor" key`);
|
|
245
189
|
}
|
|
246
190
|
/**
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
* Backends report inline datums in different shapes:
|
|
250
|
-
* - Blockfrost: hex CBOR string (e.g. "19a6aa")
|
|
251
|
-
* - Koios (_extended): wrapper { bytes: "<hex>", value: { ...PlutusData JSON... } }
|
|
252
|
-
* - Koios (sometimes empty): { bytes: null, value: null }
|
|
253
|
-
* - Some endpoints: raw PlutusData JSON ({ "int": 42 } / { "constructor": 0, "fields": [] })
|
|
254
|
-
*
|
|
255
|
-
* Returns hex CBOR (lowercase) or null. Defensive: returns null on unknown
|
|
256
|
-
* shapes rather than throwing — backend mappers must not crash on malformed data.
|
|
191
|
+
* Backend inline datum to lowercase CBOR hex: hex string (Blockfrost), `{ bytes, value }` wrapper (Koios)
|
|
192
|
+
* or raw PlutusData JSON. Returns null on unknown shapes instead of throwing.
|
|
257
193
|
*/
|
|
258
194
|
function inlineDatumToHex(datum) {
|
|
259
195
|
if (datum === null || datum === undefined)
|
|
260
196
|
return null;
|
|
261
|
-
// Already hex CBOR
|
|
197
|
+
// Already hex CBOR
|
|
262
198
|
if (typeof datum === 'string') {
|
|
263
199
|
const s = datum.trim();
|
|
264
200
|
if (!s)
|
|
@@ -268,8 +204,7 @@ function inlineDatumToHex(datum) {
|
|
|
268
204
|
if (typeof datum !== 'object' || Array.isArray(datum))
|
|
269
205
|
return null;
|
|
270
206
|
const obj = datum;
|
|
271
|
-
// Koios wrapper
|
|
272
|
-
// Distinguished from raw PlutusData {bytes:"deadbeef"} by the presence of `value`.
|
|
207
|
+
// Koios wrapper { bytes, value }; `value` distinguishes it from raw PlutusData { bytes }
|
|
273
208
|
if ('value' in obj && typeof obj.bytes === 'string' && obj.bytes.length > 0) {
|
|
274
209
|
const hex = obj.bytes.trim();
|
|
275
210
|
return /^[0-9a-fA-F]+$/.test(hex) && hex.length % 2 === 0 ? hex.toLowerCase() : null;
|
|
@@ -290,26 +225,9 @@ function inlineDatumToHex(datum) {
|
|
|
290
225
|
}
|
|
291
226
|
}
|
|
292
227
|
/**
|
|
293
|
-
* Encode a
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
* A script parameter is applied as a UPLC constant whose TYPE must match what
|
|
297
|
-
* the compiled validator expects for that parameter. Two input shapes are
|
|
298
|
-
* accepted:
|
|
299
|
-
*
|
|
300
|
-
* 1. Typed — `{ "uplc": "<type>", "value": <...> }`:
|
|
301
|
-
* - `"data"` → `UPLCConst.data(...)` value: PlutusData JSON ("constr"/cardano-cli form)
|
|
302
|
-
* - `"bytes"` → `UPLCConst.byteString(...)` value: even-length hex string
|
|
303
|
-
* - `"int"` → `UPLCConst.int(...)` value: number | numeric string
|
|
304
|
-
* - `"bool"` → `UPLCConst.bool(...)` value: boolean
|
|
305
|
-
* - `"unit"` → `UPLCConst.unit` value: omitted
|
|
306
|
-
* Required for compilers whose scalar params are NATIVE-typed rather than
|
|
307
|
-
* Data-wrapped (e.g. Pebble: `param x: PubKeyHash` expects a native
|
|
308
|
-
* `bytestring`, not a `Data` bytestring).
|
|
309
|
-
*
|
|
310
|
-
* 2. Bare PlutusData object (e.g. `{ "bytes": "ab.." }`, `{ "constructor": 0, ... }`)
|
|
311
|
-
* — shorthand for `{ "uplc": "data", "value": <object> }`. This is the
|
|
312
|
-
* Aiken / CIP-57 blueprint convention, where every parameter is Data.
|
|
228
|
+
* Encode a script parameter as the UPLC constant of the type the validator expects: typed
|
|
229
|
+
* `{ uplc: data|bytes|int|bool|unit, value }` for native-typed params, or a bare PlutusData object
|
|
230
|
+
* (Aiken / CIP-57 convention) as shorthand for `uplc: "data"`.
|
|
313
231
|
*/
|
|
314
232
|
function encodeScriptParam(param) {
|
|
315
233
|
if (param !== null &&
|
|
@@ -351,36 +269,27 @@ function encodeScriptParam(param) {
|
|
|
351
269
|
throw new Error(`Unknown script param uplc type "${String(uplc)}"; expected one of: data, bytes, int, bool, unit`);
|
|
352
270
|
}
|
|
353
271
|
}
|
|
354
|
-
// Bare PlutusData
|
|
272
|
+
// Bare PlutusData: apply as Data
|
|
355
273
|
return uplc_1.UPLCConst.data(jsonToPlutusData(param));
|
|
356
274
|
}
|
|
357
275
|
/**
|
|
358
|
-
* Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC)
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
* Parameters are applied in their declared UPLC type via {@link encodeScriptParam}:
|
|
362
|
-
* pass `{ uplc, value }` entries for native-typed params (e.g. Pebble scalars),
|
|
363
|
-
* or bare PlutusData objects for the Data convention (Aiken / CIP-57 blueprints).
|
|
364
|
-
*
|
|
365
|
-
* @param scriptHex CBOR hex of the unapplied Plutus script (as output by Aiken/Pebble/Plutus compilers)
|
|
366
|
-
* @param params Array of script parameters (typed `{uplc,value}` and/or bare PlutusData JSON) to apply in order
|
|
367
|
-
* @returns CBOR hex of the applied script (ready for transaction building)
|
|
276
|
+
* Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC): each parameter becomes a
|
|
277
|
+
* UPLC Application around the program body, encoded via {@link encodeScriptParam}.
|
|
278
|
+
* @returns CBOR hex of the applied script
|
|
368
279
|
*/
|
|
369
280
|
function applyScriptParameters(scriptHex, params) {
|
|
370
281
|
if (!Array.isArray(params) || params.length === 0) {
|
|
371
282
|
throw new Error('Script parameters must be a non-empty array');
|
|
372
283
|
}
|
|
373
|
-
//
|
|
284
|
+
// CBOR-unwrap to the flat UPLC bytes
|
|
374
285
|
const cborObj = cbor_1.Cbor.parse(scriptHex);
|
|
375
286
|
const flatBytes = cborObj.bytes;
|
|
376
|
-
// 2. Flat-decode → UPLCProgram
|
|
377
287
|
const program = uplc_1.UPLCDecoder.parse(flatBytes, 'flat');
|
|
378
|
-
// 3. Apply each parameter as Application(body, <typed UPLC constant>)
|
|
379
288
|
let body = program.body;
|
|
380
289
|
for (const param of params) {
|
|
381
290
|
body = new uplc_1.Application(body, encodeScriptParam(param));
|
|
382
291
|
}
|
|
383
|
-
//
|
|
292
|
+
// Flat-encode the applied program and CBOR-wrap it again
|
|
384
293
|
const applied = new uplc_1.UPLCProgram(program.version, body);
|
|
385
294
|
const appliedFlatBytes = (0, uplc_1.compileUPLC)(applied);
|
|
386
295
|
const cborEncoded = cbor_1.Cbor.encode(new cbor_1.CborBytes(appliedFlatBytes));
|
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import type { JSONValue } from './types';
|
|
2
2
|
/**
|
|
3
|
-
* Shared parsers for the Build*-action JSON payload fields
|
|
4
|
-
*
|
|
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.
|
|
3
|
+
* Shared parsers for the Build*-action JSON payload fields (transaction service and wallet worker).
|
|
4
|
+
* Result contract: `{ parsed }` on success (undefined for absent/empty input) or `{ error }` with a client message.
|
|
10
5
|
*/
|
|
11
6
|
export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson'): {
|
|
12
7
|
parsed?: Array<{
|
|
@@ -15,19 +10,12 @@ export declare function parseUtxoRefArray(json: string | undefined, fieldName: '
|
|
|
15
10
|
}>;
|
|
16
11
|
error?: string;
|
|
17
12
|
};
|
|
18
|
-
/**
|
|
19
|
-
* Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
|
|
20
|
-
* Same result contract as the other parse* helpers.
|
|
21
|
-
*/
|
|
13
|
+
/** Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes). */
|
|
22
14
|
export declare function parseRequiredSigners(requiredSignersJson: string | undefined): {
|
|
23
15
|
parsed?: string[];
|
|
24
16
|
error?: string;
|
|
25
17
|
};
|
|
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
|
-
*/
|
|
18
|
+
/** Parse and validate an assetsJson array of `{unit, quantity}` entries. */
|
|
31
19
|
export declare function parseAssetsArray(assetsJson: string | undefined, fieldName: string): {
|
|
32
20
|
parsed?: Array<{
|
|
33
21
|
unit: string;
|
|
@@ -47,21 +35,14 @@ export interface ParsedExtraOutput {
|
|
|
47
35
|
inlineDatum?: JSONValue;
|
|
48
36
|
referenceScript?: string;
|
|
49
37
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
|
|
52
|
-
* for empty array → no-op) or { error } on validation failure.
|
|
53
|
-
*/
|
|
38
|
+
/** Parse and validate extraOutputsJson (undefined for an empty array). */
|
|
54
39
|
export declare function parseExtraOutputs(extraOutputsJson: string | undefined): {
|
|
55
40
|
parsed?: ParsedExtraOutput[];
|
|
56
41
|
error?: string;
|
|
57
42
|
};
|
|
58
43
|
/**
|
|
59
|
-
* Parse the optional
|
|
60
|
-
*
|
|
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.
|
|
44
|
+
* Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
|
|
45
|
+
* applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
|
|
65
46
|
*/
|
|
66
47
|
export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number): {
|
|
67
48
|
script?: string;
|
|
@@ -8,13 +8,8 @@ exports.parseExtraOutputs = parseExtraOutputs;
|
|
|
8
8
|
exports.parseMintActionPolicyFields = parseMintActionPolicyFields;
|
|
9
9
|
const validators_1 = require("./validators");
|
|
10
10
|
/**
|
|
11
|
-
* Shared parsers for the Build*-action JSON payload fields
|
|
12
|
-
*
|
|
13
|
-
* request transformation (srv/blockchain/wallet-worker/build-request.ts) so
|
|
14
|
-
* both paths accept exactly the same payload shape.
|
|
15
|
-
*
|
|
16
|
-
* Result contract: { parsed } on success (undefined for absent/empty input →
|
|
17
|
-
* no-op) or { error } with a caller-presentable message.
|
|
11
|
+
* Shared parsers for the Build*-action JSON payload fields (transaction service and wallet worker).
|
|
12
|
+
* Result contract: `{ parsed }` on success (undefined for absent/empty input) or `{ error }` with a client message.
|
|
18
13
|
*/
|
|
19
14
|
function parseUtxoRefArray(json, fieldName) {
|
|
20
15
|
if (!json)
|
|
@@ -44,10 +39,7 @@ function parseUtxoRefArray(json, fieldName) {
|
|
|
44
39
|
}
|
|
45
40
|
return { parsed: refs };
|
|
46
41
|
}
|
|
47
|
-
/**
|
|
48
|
-
* Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
|
|
49
|
-
* Same result contract as the other parse* helpers.
|
|
50
|
-
*/
|
|
42
|
+
/** Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes). */
|
|
51
43
|
function parseRequiredSigners(requiredSignersJson) {
|
|
52
44
|
if (!requiredSignersJson)
|
|
53
45
|
return { parsed: undefined };
|
|
@@ -61,11 +53,7 @@ function parseRequiredSigners(requiredSignersJson) {
|
|
|
61
53
|
return { error: err instanceof Error ? err.message : String(err) };
|
|
62
54
|
}
|
|
63
55
|
}
|
|
64
|
-
/**
|
|
65
|
-
* Parse and validate an assetsJson array ({unit, quantity} entries) with the same
|
|
66
|
-
* per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
|
|
67
|
-
* into the builder and surfaced as 500s.
|
|
68
|
-
*/
|
|
56
|
+
/** Parse and validate an assetsJson array of `{unit, quantity}` entries. */
|
|
69
57
|
function parseAssetsArray(assetsJson, fieldName) {
|
|
70
58
|
if (!assetsJson)
|
|
71
59
|
return { parsed: undefined };
|
|
@@ -92,10 +80,7 @@ function parseAssetsArray(assetsJson, fieldName) {
|
|
|
92
80
|
}
|
|
93
81
|
/** Upper bound on extra outputs per transaction (defence against tx-size blow-up). */
|
|
94
82
|
exports.MAX_EXTRA_OUTPUTS = 32;
|
|
95
|
-
/**
|
|
96
|
-
* Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
|
|
97
|
-
* for empty array → no-op) or { error } on validation failure.
|
|
98
|
-
*/
|
|
83
|
+
/** Parse and validate extraOutputsJson (undefined for an empty array). */
|
|
99
84
|
function parseExtraOutputs(extraOutputsJson) {
|
|
100
85
|
if (!extraOutputsJson)
|
|
101
86
|
return { parsed: undefined };
|
|
@@ -169,12 +154,8 @@ function parseExtraOutputs(extraOutputsJson) {
|
|
|
169
154
|
return { parsed: out };
|
|
170
155
|
}
|
|
171
156
|
/**
|
|
172
|
-
* Parse the optional
|
|
173
|
-
*
|
|
174
|
-
* parameterized per-action script must be pre-applied by the caller) and
|
|
175
|
-
* `redeemerJson` (a JSON-encoded string, same convention as extraOutputs'
|
|
176
|
-
* inlineDatumJson). Absent fields fall back to the action's top-level
|
|
177
|
-
* script/redeemer at build time.
|
|
157
|
+
* Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
|
|
158
|
+
* applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
|
|
178
159
|
*/
|
|
179
160
|
function parseMintActionPolicyFields(entry, i) {
|
|
180
161
|
let script;
|
package/srv/utils/tx-utils.d.ts
CHANGED
|
@@ -2,32 +2,13 @@ import cds from '@sap/cds';
|
|
|
2
2
|
/** Default acquire budget for detached bookkeeping transactions. */
|
|
3
3
|
export declare const DETACHED_TX_TIMEOUT_MS = 10000;
|
|
4
4
|
/**
|
|
5
|
-
* Run `fn` with `cds.context` cleared
|
|
6
|
-
*
|
|
7
|
-
* Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
|
|
8
|
-
* connection free during long awaits (NIGHTGATE lesson 2; used by the
|
|
9
|
-
* wallet-worker job loops).
|
|
5
|
+
* Run `fn` with `cds.context` cleared so inner `db.run` calls get short-lived transactions instead of
|
|
6
|
+
* joining a long-lived ambient one; keeps the single sqlite connection free during long awaits.
|
|
10
7
|
*/
|
|
11
8
|
export declare function runWithoutAmbientTx<T>(fn: () => Promise<T>): Promise<T>;
|
|
12
9
|
/**
|
|
13
|
-
* `cds.tx(fn)` with a deadlock guard:
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* Why: the sign-service must commit its submit bookkeeping (claim, finalize,
|
|
17
|
-
* failure marker) independently of the caller's request transaction. When an
|
|
18
|
-
* in-process consumer awaits the action while its own request transaction
|
|
19
|
-
* holds the single pooled sqlite connection, the acquire can never succeed —
|
|
20
|
-
* without this guard that is a silent, zero-CPU, infinite hang.
|
|
21
|
-
*
|
|
22
|
-
* Guarantees:
|
|
23
|
-
* - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
|
|
24
|
-
* diagnosis pointing at KNOWN_ISSUES #11.
|
|
25
|
-
* - A late connection grant (after the timeout already fired) performs NO
|
|
26
|
-
* work: the callback forces the acquire via an explicit `begin()` and
|
|
27
|
-
* checks the abort flag right after it, so it rolls back immediately and
|
|
28
|
-
* the caller never observes an error for work that then silently happened
|
|
29
|
-
* anyway. (A flag check at callback ENTRY would run long before the lazy
|
|
30
|
-
* acquire and miss the timeout.)
|
|
10
|
+
* `cds.tx(fn)` as a new root transaction with a deadlock guard: throws BackendError 503
|
|
11
|
+
* `ODATANO_NESTED_TX_TIMEOUT` when no pooled connection arrives in time, and a late grant does no work.
|
|
31
12
|
*/
|
|
32
13
|
export declare function detachedTx<T>(label: string, fn: (db: cds.Transaction) => Promise<T>, timeoutMs?: number): Promise<T>;
|
|
33
14
|
//# sourceMappingURL=tx-utils.d.ts.map
|
package/srv/utils/tx-utils.js
CHANGED
|
@@ -10,29 +10,20 @@ const cds_1 = __importDefault(require("@sap/cds"));
|
|
|
10
10
|
const errors_1 = require("./errors");
|
|
11
11
|
const error_codes_1 = require("./error-codes");
|
|
12
12
|
/**
|
|
13
|
-
* Transaction
|
|
14
|
-
*
|
|
15
|
-
* Context: @cap-js/sqlite runs on a SINGLE pooled connection. A request
|
|
16
|
-
* transaction begins lazily on its first CQL statement and holds that
|
|
17
|
-
* connection until the request commits. Any code that then needs a NEW ROOT
|
|
18
|
-
* transaction (detached committed bookkeeping) waits on the pool — forever,
|
|
19
|
-
* if the waiter is awaited by the very request holding the connection
|
|
20
|
-
* (docs/KNOWN_ISSUES.md issue 11).
|
|
13
|
+
* Transaction helpers for the sign-service and background workers. @cap-js/sqlite has a single pooled
|
|
14
|
+
* connection held by the request tx, so a new root tx awaited by that request would wait forever.
|
|
21
15
|
*/
|
|
22
16
|
const logger = cds_1.default.log('tx-utils');
|
|
23
17
|
/** Default acquire budget for detached bookkeeping transactions. */
|
|
24
18
|
exports.DETACHED_TX_TIMEOUT_MS = 10_000;
|
|
25
|
-
/**
|
|
19
|
+
/** ODATANO_DETACHED_TX_TIMEOUT_MS override, else the default; read per call. */
|
|
26
20
|
function effectiveTimeoutMs() {
|
|
27
21
|
const fromEnv = Number(process.env.ODATANO_DETACHED_TX_TIMEOUT_MS);
|
|
28
22
|
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : exports.DETACHED_TX_TIMEOUT_MS;
|
|
29
23
|
}
|
|
30
24
|
/**
|
|
31
|
-
* Run `fn` with `cds.context` cleared
|
|
32
|
-
*
|
|
33
|
-
* Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
|
|
34
|
-
* connection free during long awaits (NIGHTGATE lesson 2; used by the
|
|
35
|
-
* wallet-worker job loops).
|
|
25
|
+
* Run `fn` with `cds.context` cleared so inner `db.run` calls get short-lived transactions instead of
|
|
26
|
+
* joining a long-lived ambient one; keeps the single sqlite connection free during long awaits.
|
|
36
27
|
*/
|
|
37
28
|
function runWithoutAmbientTx(fn) {
|
|
38
29
|
return cds_1.default._with(undefined, fn);
|
|
@@ -45,34 +36,16 @@ class DetachedTxAbortedError extends Error {
|
|
|
45
36
|
}
|
|
46
37
|
}
|
|
47
38
|
/**
|
|
48
|
-
* `cds.tx(fn)` with a deadlock guard:
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* Why: the sign-service must commit its submit bookkeeping (claim, finalize,
|
|
52
|
-
* failure marker) independently of the caller's request transaction. When an
|
|
53
|
-
* in-process consumer awaits the action while its own request transaction
|
|
54
|
-
* holds the single pooled sqlite connection, the acquire can never succeed —
|
|
55
|
-
* without this guard that is a silent, zero-CPU, infinite hang.
|
|
56
|
-
*
|
|
57
|
-
* Guarantees:
|
|
58
|
-
* - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
|
|
59
|
-
* diagnosis pointing at KNOWN_ISSUES #11.
|
|
60
|
-
* - A late connection grant (after the timeout already fired) performs NO
|
|
61
|
-
* work: the callback forces the acquire via an explicit `begin()` and
|
|
62
|
-
* checks the abort flag right after it, so it rolls back immediately and
|
|
63
|
-
* the caller never observes an error for work that then silently happened
|
|
64
|
-
* anyway. (A flag check at callback ENTRY would run long before the lazy
|
|
65
|
-
* acquire and miss the timeout.)
|
|
39
|
+
* `cds.tx(fn)` as a new root transaction with a deadlock guard: throws BackendError 503
|
|
40
|
+
* `ODATANO_NESTED_TX_TIMEOUT` when no pooled connection arrives in time, and a late grant does no work.
|
|
66
41
|
*/
|
|
67
42
|
async function detachedTx(label, fn, timeoutMs) {
|
|
68
43
|
const effectiveTimeout = timeoutMs ?? effectiveTimeoutMs();
|
|
69
44
|
let timedOut = false;
|
|
70
45
|
let timer;
|
|
71
46
|
const work = cds_1.default.tx(async (db) => {
|
|
72
|
-
//
|
|
73
|
-
//
|
|
74
|
-
// the abort flag — a late grant (after the caller already received the
|
|
75
|
-
// timeout error) must roll back before doing any work.
|
|
47
|
+
// The connection is acquired lazily by the first statement: force it now, then check the abort
|
|
48
|
+
// flag so a grant after the timeout rolls back before doing any work.
|
|
76
49
|
await db.begin();
|
|
77
50
|
if (timedOut)
|
|
78
51
|
throw new DetachedTxAbortedError(label);
|
|
@@ -84,8 +57,8 @@ async function detachedTx(label, fn, timeoutMs) {
|
|
|
84
57
|
reject(new errors_1.BackendError(`${label}: could not begin a detached DB transaction within ${effectiveTimeout}ms. ` +
|
|
85
58
|
`Most likely the calling request still holds the pooled DB connection open ` +
|
|
86
59
|
`(in-process nested call — do not await this action while your request ` +
|
|
87
|
-
`transaction is open; detach your reads into a committed cds.tx first
|
|
88
|
-
`
|
|
60
|
+
`transaction is open; detach your reads into a committed cds.tx first). ` +
|
|
61
|
+
`Alternatively the connection pool is exhausted.`, 503, error_codes_1.ERROR_CODES.NESTED_TX_TIMEOUT));
|
|
89
62
|
}, effectiveTimeout);
|
|
90
63
|
});
|
|
91
64
|
try {
|
|
@@ -95,9 +68,7 @@ async function detachedTx(label, fn, timeoutMs) {
|
|
|
95
68
|
if (timer)
|
|
96
69
|
clearTimeout(timer);
|
|
97
70
|
if (timedOut) {
|
|
98
|
-
// The orphaned acquire may still be granted
|
|
99
|
-
// itself via the flag. Observe the rejection so it never surfaces as an
|
|
100
|
-
// unhandled promise rejection.
|
|
71
|
+
// The orphaned acquire may still be granted; observe its rejection so it is never unhandled.
|
|
101
72
|
work.catch((e) => {
|
|
102
73
|
if (!(e instanceof DetachedTxAbortedError)) {
|
|
103
74
|
logger.warn(`Orphaned detached tx '${label}' failed after timeout: ${e instanceof Error ? e.message : String(e)}`);
|