@odatano/core 1.9.1 → 1.9.3
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/package.json +8 -6
- package/srv/blockchain/backends/koios-backend.d.ts +10 -0
- package/srv/blockchain/backends/koios-backend.js +30 -1
- package/srv/blockchain/backends/ogmios-backend.d.ts +28 -0
- package/srv/blockchain/backends/ogmios-backend.js +50 -4
- package/srv/blockchain/cardano-client.d.ts +16 -0
- package/srv/blockchain/cardano-client.js +39 -2
- package/srv/utils/tx-build-helper.d.ts +34 -3
- package/srv/utils/tx-build-helper.js +76 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@odatano/core",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.3",
|
|
4
4
|
"description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
|
|
5
5
|
"imports": {
|
|
6
6
|
"#cds-models/*": "./@cds-models/*/index.js"
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"@blockfrost/blockfrost-js": "~6.0.0",
|
|
28
28
|
"@cap-js/hana": "^2",
|
|
29
29
|
"@cardano-ogmios/client": "^6.14.0",
|
|
30
|
-
"@harmoniclabs/buildooor": "
|
|
30
|
+
"@harmoniclabs/buildooor": "0.2.6",
|
|
31
31
|
"@harmoniclabs/cardano-costmodels-ts": "~1.4.0",
|
|
32
32
|
"@harmoniclabs/cardano-ledger-ts": "^0.5.1",
|
|
33
33
|
"@harmoniclabs/cbor": "^2.0.1",
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
"eslint": "^9.39.2",
|
|
62
62
|
"jest": "^29.6.1",
|
|
63
63
|
"nock": "^13.5.6",
|
|
64
|
+
"patch-package": "8.0.1",
|
|
64
65
|
"ts-jest": "^29.4.5",
|
|
65
66
|
"ts-node": "^10.9.2",
|
|
66
67
|
"tsx": "^4.21.0",
|
|
@@ -105,6 +106,7 @@
|
|
|
105
106
|
}
|
|
106
107
|
},
|
|
107
108
|
"scripts": {
|
|
109
|
+
"postinstall": "patch-package",
|
|
108
110
|
"clean": "node -e \"require('glob').sync('{srv,db,src}/**/*.{js,js.map,d.ts,d.ts.map}',{ignore:'**/node_modules/**'}).forEach(f=>require('fs').unlinkSync(f));console.log('Clean complete')\"",
|
|
109
111
|
"clean:models": "node -e \"require('fs').rmSync('@cds-models',{recursive:true,force:true});console.log('Removed @cds-models')\"",
|
|
110
112
|
"build": "npm run cds:types && tsc",
|
|
@@ -118,10 +120,10 @@
|
|
|
118
120
|
"typecheck": "tsc --noEmit",
|
|
119
121
|
"db:deploy": "cds deploy",
|
|
120
122
|
"pretest": "npm run cds:types && npm run db:deploy",
|
|
121
|
-
"test": "jest --runInBand",
|
|
122
|
-
"test:coverage": "jest --runInBand --coverage",
|
|
123
|
-
"test:ci": "jest --runInBand --testPathIgnorePatterns=core-ogmios.test.ts",
|
|
124
|
-
"test:ci:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=core-ogmios.test.ts",
|
|
123
|
+
"test": "jest --runInBand --forceExit",
|
|
124
|
+
"test:coverage": "jest --runInBand --coverage --forceExit",
|
|
125
|
+
"test:ci": "jest --runInBand --testPathIgnorePatterns=core-ogmios.test.ts --forceExit",
|
|
126
|
+
"test:ci:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=core-ogmios.test.ts --forceExit",
|
|
125
127
|
"test:integration": "npm test -- --testPathPattern=integration",
|
|
126
128
|
"test:integration:blockfrost": "npm test -- --testPathPattern=core.blockfrost.test.ts",
|
|
127
129
|
"test:integration:koios": "npm test -- --testPathPattern=core.koios.test.ts",
|
|
@@ -24,6 +24,16 @@ export declare class KoiosBackend implements CardanoBackend {
|
|
|
24
24
|
* epoch lookups, so we retry with increasing delays (500 → 1000 → 2000 ms).
|
|
25
25
|
*/
|
|
26
26
|
private fetchWithRetryOnEmpty;
|
|
27
|
+
/**
|
|
28
|
+
* Koios runs several load-balanced grest instances and they are occasionally
|
|
29
|
+
* version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
|
|
30
|
+
* of query does not match function result type", e.g. `out_sum_lovelace`
|
|
31
|
+
* word128 vs numeric on /epoch_info) while healthy instances serve the
|
|
32
|
+
* IDENTICAL request fine. The same request therefore flips 200/400 between
|
|
33
|
+
* calls. Retrying a few times lands on a healthy instance. Scoped strictly to
|
|
34
|
+
* the 42804 type-skew error so genuine 400s (bad params) still fail fast.
|
|
35
|
+
*/
|
|
36
|
+
private getWithRetryOn42804;
|
|
27
37
|
/**
|
|
28
38
|
* Get Transaction Data for specified transaction hash
|
|
29
39
|
* @param hash transaction hash (hex)
|
|
@@ -116,6 +116,35 @@ class KoiosBackend {
|
|
|
116
116
|
}
|
|
117
117
|
return [];
|
|
118
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Koios runs several load-balanced grest instances and they are occasionally
|
|
121
|
+
* version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
|
|
122
|
+
* of query does not match function result type", e.g. `out_sum_lovelace`
|
|
123
|
+
* word128 vs numeric on /epoch_info) while healthy instances serve the
|
|
124
|
+
* IDENTICAL request fine. The same request therefore flips 200/400 between
|
|
125
|
+
* calls. Retrying a few times lands on a healthy instance. Scoped strictly to
|
|
126
|
+
* the 42804 type-skew error so genuine 400s (bad params) still fail fast.
|
|
127
|
+
*/
|
|
128
|
+
async getWithRetryOn42804(url, config, label) {
|
|
129
|
+
const maxRetries = 8;
|
|
130
|
+
const baseDelayMs = 300;
|
|
131
|
+
for (let attempt = 0;; attempt++) {
|
|
132
|
+
try {
|
|
133
|
+
return await this.api.get(url, config);
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
const e = err;
|
|
137
|
+
const isSkew = e?.response?.status === 400 &&
|
|
138
|
+
(e.response.data?.code === '42804' ||
|
|
139
|
+
/structure of query does not match function result type/i.test(e.response.data?.message ?? ''));
|
|
140
|
+
if (!isSkew || attempt >= maxRetries)
|
|
141
|
+
throw err;
|
|
142
|
+
const delay = baseDelayMs * (attempt + 1);
|
|
143
|
+
logger.warn(`${label}: Koios transient 42804 (grest version skew), retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
|
|
144
|
+
await new Promise(r => setTimeout(r, delay));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
119
148
|
/**
|
|
120
149
|
* Get Transaction Data for specified transaction hash
|
|
121
150
|
* @param hash transaction hash (hex)
|
|
@@ -174,7 +203,7 @@ class KoiosBackend {
|
|
|
174
203
|
*/
|
|
175
204
|
async getEpoch(epochNumber) {
|
|
176
205
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
177
|
-
const results = await this.fetchWithRetryOnEmpty(() => this.
|
|
206
|
+
const results = await this.fetchWithRetryOnEmpty(() => this.getWithRetryOn42804('/epoch_info', { params: { _epoch_no: epochNumber } }, `getEpoch(${epochNumber})`), `getEpoch(${epochNumber})`);
|
|
178
207
|
if (!results || results.length === 0) {
|
|
179
208
|
throw new errors_1.NotFoundError('Epoch', this.name);
|
|
180
209
|
}
|
|
@@ -38,8 +38,36 @@ export declare class OgmiosBackend implements EvaluatingBackend {
|
|
|
38
38
|
* Constructor
|
|
39
39
|
*/
|
|
40
40
|
constructor(network: Network, timeoutMs: number, ogmiosUrl: string);
|
|
41
|
+
/**
|
|
42
|
+
* Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
|
|
43
|
+
*
|
|
44
|
+
* createInteractionContext() opens the WebSocket, but FIRST probes
|
|
45
|
+
* `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
|
|
46
|
+
* → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
|
|
47
|
+
* keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
|
|
48
|
+
* server on Node 22/24 a reused socket the server has already half-closed
|
|
49
|
+
* yields "Invalid response body … Premature close" the instant the body is
|
|
50
|
+
* read — deterministically (Node 20's older http client tolerated it; `curl`
|
|
51
|
+
* does too, so the /health response itself is well-formed and the node is
|
|
52
|
+
* healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
|
|
53
|
+
* an agent into that internal fetch, so we neutralise keep-alive process-wide
|
|
54
|
+
* for `http://`. Blast radius is tiny: the only `http://` consumer is the local
|
|
55
|
+
* Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
|
|
56
|
+
* and are unaffected. Runs once, lazily, only when Ogmios is actually used.
|
|
57
|
+
*/
|
|
58
|
+
private static keepAliveDisabled;
|
|
59
|
+
private static disableHttpKeepAlive;
|
|
41
60
|
/** Validate Ogmios URL scheme and reject dangerous protocols */
|
|
42
61
|
private static validateOgmiosUrl;
|
|
62
|
+
/**
|
|
63
|
+
* Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
|
|
64
|
+
* node is alive but too busy catching up to answer) would otherwise block
|
|
65
|
+
* forever — there is no built-in connect timeout — hanging the whole
|
|
66
|
+
* app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
|
|
67
|
+
* with a message containing "timeout" so the orchestrator's transient-error
|
|
68
|
+
* retry picks it up instead of dying.
|
|
69
|
+
*/
|
|
70
|
+
private withInitTimeout;
|
|
43
71
|
/**
|
|
44
72
|
* Initialize the Ogmios backend connection
|
|
45
73
|
*/
|
|
@@ -7,6 +7,7 @@ exports.OgmiosBackend = void 0;
|
|
|
7
7
|
exports.resolveOgmiosTip = resolveOgmiosTip;
|
|
8
8
|
exports.resolveOgmiosHeight = resolveOgmiosHeight;
|
|
9
9
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
|
+
const node_http_1 = __importDefault(require("node:http"));
|
|
10
11
|
const client_1 = require("@cardano-ogmios/client");
|
|
11
12
|
const backend_request_handler_1 = require("../../utils/backend-request-handler");
|
|
12
13
|
const errors_1 = require("../../utils/errors");
|
|
@@ -115,6 +116,30 @@ class OgmiosBackend {
|
|
|
115
116
|
this.timeoutMs = timeoutMs;
|
|
116
117
|
this.ogmiosUrl = ogmiosUrl;
|
|
117
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
|
|
121
|
+
*
|
|
122
|
+
* createInteractionContext() opens the WebSocket, but FIRST probes
|
|
123
|
+
* `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
|
|
124
|
+
* → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
|
|
125
|
+
* keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
|
|
126
|
+
* server on Node 22/24 a reused socket the server has already half-closed
|
|
127
|
+
* yields "Invalid response body … Premature close" the instant the body is
|
|
128
|
+
* read — deterministically (Node 20's older http client tolerated it; `curl`
|
|
129
|
+
* does too, so the /health response itself is well-formed and the node is
|
|
130
|
+
* healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
|
|
131
|
+
* an agent into that internal fetch, so we neutralise keep-alive process-wide
|
|
132
|
+
* for `http://`. Blast radius is tiny: the only `http://` consumer is the local
|
|
133
|
+
* Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
|
|
134
|
+
* and are unaffected. Runs once, lazily, only when Ogmios is actually used.
|
|
135
|
+
*/
|
|
136
|
+
static keepAliveDisabled = false;
|
|
137
|
+
static disableHttpKeepAlive() {
|
|
138
|
+
if (OgmiosBackend.keepAliveDisabled)
|
|
139
|
+
return;
|
|
140
|
+
node_http_1.default.globalAgent = new node_http_1.default.Agent({ keepAlive: false });
|
|
141
|
+
OgmiosBackend.keepAliveDisabled = true;
|
|
142
|
+
}
|
|
118
143
|
/** Validate Ogmios URL scheme and reject dangerous protocols */
|
|
119
144
|
static validateOgmiosUrl(rawUrl) {
|
|
120
145
|
const url = new URL(rawUrl);
|
|
@@ -133,10 +158,31 @@ class OgmiosBackend {
|
|
|
133
158
|
throw new errors_1.BackendInitError('ogmios', new Error('Ogmios URL must not point to a link-local or metadata address'));
|
|
134
159
|
}
|
|
135
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
|
|
163
|
+
* node is alive but too busy catching up to answer) would otherwise block
|
|
164
|
+
* forever — there is no built-in connect timeout — hanging the whole
|
|
165
|
+
* app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
|
|
166
|
+
* with a message containing "timeout" so the orchestrator's transient-error
|
|
167
|
+
* retry picks it up instead of dying.
|
|
168
|
+
*/
|
|
169
|
+
withInitTimeout(p, label) {
|
|
170
|
+
// Keep this SHORT: the orchestrator retries init a few times within the
|
|
171
|
+
// integration suite's 20s cds.test() hook, so each attempt must be brief.
|
|
172
|
+
// Still bounds a genuinely hung connect in production.
|
|
173
|
+
const ms = Math.min(this.timeoutMs, 4000);
|
|
174
|
+
let timer;
|
|
175
|
+
const timeout = new Promise((_, reject) => {
|
|
176
|
+
timer = setTimeout(() => reject(new Error(`Ogmios init timeout after ${ms}ms (${label})`)), ms);
|
|
177
|
+
timer.unref?.();
|
|
178
|
+
});
|
|
179
|
+
return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
|
|
180
|
+
}
|
|
136
181
|
/**
|
|
137
182
|
* Initialize the Ogmios backend connection
|
|
138
183
|
*/
|
|
139
184
|
async init() {
|
|
185
|
+
OgmiosBackend.disableHttpKeepAlive();
|
|
140
186
|
OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
|
|
141
187
|
const url = new URL(this.ogmiosUrl);
|
|
142
188
|
const connection = {
|
|
@@ -144,7 +190,7 @@ class OgmiosBackend {
|
|
|
144
190
|
port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80),
|
|
145
191
|
tls: url.protocol === 'wss:'
|
|
146
192
|
};
|
|
147
|
-
const context = await (0, client_1.createInteractionContext)(
|
|
193
|
+
const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
|
|
148
194
|
/* c8 ignore next */
|
|
149
195
|
(err) => logger.error(`[OgmiosBackend] Interaction context error: ${err.message}`), () => {
|
|
150
196
|
// Socket closed: clear the clients so the next request reconnects via
|
|
@@ -155,10 +201,10 @@ class OgmiosBackend {
|
|
|
155
201
|
logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
|
|
156
202
|
this.stateQueryClient = null;
|
|
157
203
|
this.txSubmissionClient = null;
|
|
158
|
-
}, { connection });
|
|
204
|
+
}, { connection }), 'createInteractionContext');
|
|
159
205
|
try {
|
|
160
|
-
this.stateQueryClient = await (0, client_1.createLedgerStateQueryClient)(context);
|
|
161
|
-
this.txSubmissionClient = await (0, client_1.createTransactionSubmissionClient)(context);
|
|
206
|
+
this.stateQueryClient = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'ledgerStateQueryClient');
|
|
207
|
+
this.txSubmissionClient = await this.withInitTimeout((0, client_1.createTransactionSubmissionClient)(context), 'txSubmissionClient');
|
|
162
208
|
}
|
|
163
209
|
catch (err) {
|
|
164
210
|
// don't leak the WebSocket when client creation fails mid-init
|
|
@@ -57,6 +57,22 @@ export declare class CardanoClient {
|
|
|
57
57
|
* @returns {Promise<void>}
|
|
58
58
|
*/
|
|
59
59
|
private ensureInitialized;
|
|
60
|
+
/**
|
|
61
|
+
* Transient (retryable) init failures: a backend momentarily unreachable at
|
|
62
|
+
* startup — e.g. Ogmios's /health response cut short while the node processes
|
|
63
|
+
* a freshly-arrived block ("Premature close"), or the socket still coming up
|
|
64
|
+
* (ECONNREFUSED). Config/validation errors are NOT transient.
|
|
65
|
+
*/
|
|
66
|
+
private static isTransientInitError;
|
|
67
|
+
/**
|
|
68
|
+
* Init a backend, retrying brief transient failures. Deliberately SMALL: the
|
|
69
|
+
* integration suites bootstrap under a 20s cds.test() hook, so total retry
|
|
70
|
+
* time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
|
|
71
|
+
* ≈ 14s worst case; in practice "Premature close" returns sub-second). With
|
|
72
|
+
* the node at tip these failures are momentary block-processing blips, so a
|
|
73
|
+
* couple of quick retries ride over them; a sustained outage still fails fast.
|
|
74
|
+
*/
|
|
75
|
+
private initBackendWithRetry;
|
|
60
76
|
/**
|
|
61
77
|
* Initialize all backends from configuration.
|
|
62
78
|
* Backends that fail to initialize are KEPT (previously removed permanently)
|
|
@@ -117,6 +117,43 @@ class CardanoClient {
|
|
|
117
117
|
});
|
|
118
118
|
await this.initPromise;
|
|
119
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Transient (retryable) init failures: a backend momentarily unreachable at
|
|
122
|
+
* startup — e.g. Ogmios's /health response cut short while the node processes
|
|
123
|
+
* a freshly-arrived block ("Premature close"), or the socket still coming up
|
|
124
|
+
* (ECONNREFUSED). Config/validation errors are NOT transient.
|
|
125
|
+
*/
|
|
126
|
+
static isTransientInitError(err) {
|
|
127
|
+
const e = err;
|
|
128
|
+
const code = e?.code ?? e?.cause?.code ?? '';
|
|
129
|
+
const msg = `${e?.message ?? ''} ${e?.cause?.message ?? ''}`.toLowerCase();
|
|
130
|
+
if (['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_SOCKET'].includes(code))
|
|
131
|
+
return true;
|
|
132
|
+
return /premature close|socket hang up|econnreset|econnrefused|etimedout|timeout|fetch failed|terminated|other side closed/.test(msg);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Init a backend, retrying brief transient failures. Deliberately SMALL: the
|
|
136
|
+
* integration suites bootstrap under a 20s cds.test() hook, so total retry
|
|
137
|
+
* time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
|
|
138
|
+
* ≈ 14s worst case; in practice "Premature close" returns sub-second). With
|
|
139
|
+
* the node at tip these failures are momentary block-processing blips, so a
|
|
140
|
+
* couple of quick retries ride over them; a sustained outage still fails fast.
|
|
141
|
+
*/
|
|
142
|
+
async initBackendWithRetry(backend) {
|
|
143
|
+
const maxAttempts = 3;
|
|
144
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
145
|
+
try {
|
|
146
|
+
await backend.init();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (attempt >= maxAttempts || !CardanoClient.isTransientInitError(err))
|
|
151
|
+
throw err;
|
|
152
|
+
logger.warn(`Init of ${backend.name} failed (attempt ${attempt}/${maxAttempts}) — transient, retrying in 1s`, err);
|
|
153
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
120
157
|
/**
|
|
121
158
|
* Initialize all backends from configuration.
|
|
122
159
|
* Backends that fail to initialize are KEPT (previously removed permanently)
|
|
@@ -131,7 +168,7 @@ class CardanoClient {
|
|
|
131
168
|
if (this.liveBackend) {
|
|
132
169
|
try {
|
|
133
170
|
logger.debug(`Initializing live backend: ${this.liveBackend.name}`);
|
|
134
|
-
await this.liveBackend
|
|
171
|
+
await this.initBackendWithRetry(this.liveBackend);
|
|
135
172
|
this.uninitializedBackends.delete(this.liveBackend);
|
|
136
173
|
logger.debug(`Live backend initialized: ${this.liveBackend.name}`);
|
|
137
174
|
}
|
|
@@ -145,7 +182,7 @@ class CardanoClient {
|
|
|
145
182
|
for (const backend of this.historicalBackends) {
|
|
146
183
|
try {
|
|
147
184
|
logger.debug(`Initializing historical backend: ${backend.name}`);
|
|
148
|
-
await
|
|
185
|
+
await this.initBackendWithRetry(backend);
|
|
149
186
|
this.uninitializedBackends.delete(backend);
|
|
150
187
|
logger.debug(`Historical backend initialized: ${backend.name}`);
|
|
151
188
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { UTxO as OdatanoUtxo, JSONValue } from '../utils/types';
|
|
2
2
|
import { type Data } from '@harmoniclabs/plutus-data';
|
|
3
|
+
import { UPLCConst } from '@harmoniclabs/uplc';
|
|
3
4
|
/**
|
|
4
5
|
* Extract lovelace amount from UTxO
|
|
5
6
|
* @param u UTxO to extract from
|
|
@@ -65,11 +66,41 @@ export declare function jsonToPlutusData(json: JSONValue): Data;
|
|
|
65
66
|
* shapes rather than throwing — backend mappers must not crash on malformed data.
|
|
66
67
|
*/
|
|
67
68
|
export declare function inlineDatumToHex(datum: unknown): string | null;
|
|
69
|
+
/** UPLC type tag for a typed script parameter (see {@link encodeScriptParam}). */
|
|
70
|
+
export type ScriptParamUplcType = 'data' | 'bytes' | 'int' | 'bool' | 'unit';
|
|
71
|
+
/**
|
|
72
|
+
* Encode a single script parameter into the UPLC constant the parameterized
|
|
73
|
+
* script expects.
|
|
74
|
+
*
|
|
75
|
+
* A script parameter is applied as a UPLC constant whose TYPE must match what
|
|
76
|
+
* the compiled validator expects for that parameter. Two input shapes are
|
|
77
|
+
* accepted:
|
|
78
|
+
*
|
|
79
|
+
* 1. Typed — `{ "uplc": "<type>", "value": <...> }`:
|
|
80
|
+
* - `"data"` → `UPLCConst.data(...)` value: PlutusData JSON ("constr"/cardano-cli form)
|
|
81
|
+
* - `"bytes"` → `UPLCConst.byteString(...)` value: even-length hex string
|
|
82
|
+
* - `"int"` → `UPLCConst.int(...)` value: number | numeric string
|
|
83
|
+
* - `"bool"` → `UPLCConst.bool(...)` value: boolean
|
|
84
|
+
* - `"unit"` → `UPLCConst.unit` value: omitted
|
|
85
|
+
* Required for compilers whose scalar params are NATIVE-typed rather than
|
|
86
|
+
* Data-wrapped (e.g. Pebble: `param x: PubKeyHash` expects a native
|
|
87
|
+
* `bytestring`, not a `Data` bytestring).
|
|
88
|
+
*
|
|
89
|
+
* 2. Bare PlutusData object (e.g. `{ "bytes": "ab.." }`, `{ "constructor": 0, ... }`)
|
|
90
|
+
* — shorthand for `{ "uplc": "data", "value": <object> }`. This is the
|
|
91
|
+
* Aiken / CIP-57 blueprint convention, where every parameter is Data.
|
|
92
|
+
*/
|
|
93
|
+
export declare function encodeScriptParam(param: JSONValue): UPLCConst;
|
|
68
94
|
/**
|
|
69
95
|
* Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC).
|
|
70
|
-
* Each parameter
|
|
71
|
-
*
|
|
72
|
-
*
|
|
96
|
+
* Each parameter becomes a successive UPLC Application wrapping the program body.
|
|
97
|
+
*
|
|
98
|
+
* Parameters are applied in their declared UPLC type via {@link encodeScriptParam}:
|
|
99
|
+
* pass `{ uplc, value }` entries for native-typed params (e.g. Pebble scalars),
|
|
100
|
+
* or bare PlutusData objects for the Data convention (Aiken / CIP-57 blueprints).
|
|
101
|
+
*
|
|
102
|
+
* @param scriptHex CBOR hex of the unapplied Plutus script (as output by Aiken/Pebble/Plutus compilers)
|
|
103
|
+
* @param params Array of script parameters (typed `{uplc,value}` and/or bare PlutusData JSON) to apply in order
|
|
73
104
|
* @returns CBOR hex of the applied script (ready for transaction building)
|
|
74
105
|
*/
|
|
75
106
|
export declare function applyScriptParameters(scriptHex: string, params: JSONValue[]): string;
|
|
@@ -7,6 +7,7 @@ exports.mapBuilderError = mapBuilderError;
|
|
|
7
7
|
exports.parseAssetUnit = parseAssetUnit;
|
|
8
8
|
exports.jsonToPlutusData = jsonToPlutusData;
|
|
9
9
|
exports.inlineDatumToHex = inlineDatumToHex;
|
|
10
|
+
exports.encodeScriptParam = encodeScriptParam;
|
|
10
11
|
exports.applyScriptParameters = applyScriptParameters;
|
|
11
12
|
const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
|
|
12
13
|
const crypto_1 = require("@harmoniclabs/crypto");
|
|
@@ -222,11 +223,81 @@ function inlineDatumToHex(datum) {
|
|
|
222
223
|
return null;
|
|
223
224
|
}
|
|
224
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Encode a single script parameter into the UPLC constant the parameterized
|
|
228
|
+
* script expects.
|
|
229
|
+
*
|
|
230
|
+
* A script parameter is applied as a UPLC constant whose TYPE must match what
|
|
231
|
+
* the compiled validator expects for that parameter. Two input shapes are
|
|
232
|
+
* accepted:
|
|
233
|
+
*
|
|
234
|
+
* 1. Typed — `{ "uplc": "<type>", "value": <...> }`:
|
|
235
|
+
* - `"data"` → `UPLCConst.data(...)` value: PlutusData JSON ("constr"/cardano-cli form)
|
|
236
|
+
* - `"bytes"` → `UPLCConst.byteString(...)` value: even-length hex string
|
|
237
|
+
* - `"int"` → `UPLCConst.int(...)` value: number | numeric string
|
|
238
|
+
* - `"bool"` → `UPLCConst.bool(...)` value: boolean
|
|
239
|
+
* - `"unit"` → `UPLCConst.unit` value: omitted
|
|
240
|
+
* Required for compilers whose scalar params are NATIVE-typed rather than
|
|
241
|
+
* Data-wrapped (e.g. Pebble: `param x: PubKeyHash` expects a native
|
|
242
|
+
* `bytestring`, not a `Data` bytestring).
|
|
243
|
+
*
|
|
244
|
+
* 2. Bare PlutusData object (e.g. `{ "bytes": "ab.." }`, `{ "constructor": 0, ... }`)
|
|
245
|
+
* — shorthand for `{ "uplc": "data", "value": <object> }`. This is the
|
|
246
|
+
* Aiken / CIP-57 blueprint convention, where every parameter is Data.
|
|
247
|
+
*/
|
|
248
|
+
function encodeScriptParam(param) {
|
|
249
|
+
if (param !== null &&
|
|
250
|
+
typeof param === 'object' &&
|
|
251
|
+
!Array.isArray(param) &&
|
|
252
|
+
'uplc' in param) {
|
|
253
|
+
const { uplc, value } = param;
|
|
254
|
+
switch (uplc) {
|
|
255
|
+
case 'data':
|
|
256
|
+
return uplc_1.UPLCConst.data(jsonToPlutusData(value));
|
|
257
|
+
case 'bytes': {
|
|
258
|
+
if (typeof value !== 'string' || !/^([0-9a-fA-F]{2})*$/.test(value)) {
|
|
259
|
+
throw new Error('Script param of uplc type "bytes" requires an even-length hex string "value"');
|
|
260
|
+
}
|
|
261
|
+
return uplc_1.UPLCConst.byteString((0, uint8array_utils_1.fromHex)(value));
|
|
262
|
+
}
|
|
263
|
+
case 'int': {
|
|
264
|
+
if (typeof value !== 'number' && typeof value !== 'string') {
|
|
265
|
+
throw new Error('Script param of uplc type "int" requires a number or numeric-string "value"');
|
|
266
|
+
}
|
|
267
|
+
let n;
|
|
268
|
+
try {
|
|
269
|
+
n = BigInt(value);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
throw new Error(`Script param of uplc type "int" has a non-integer "value": ${String(value)}`);
|
|
273
|
+
}
|
|
274
|
+
return uplc_1.UPLCConst.int(n);
|
|
275
|
+
}
|
|
276
|
+
case 'bool': {
|
|
277
|
+
if (typeof value !== 'boolean') {
|
|
278
|
+
throw new Error('Script param of uplc type "bool" requires a boolean "value"');
|
|
279
|
+
}
|
|
280
|
+
return uplc_1.UPLCConst.bool(value);
|
|
281
|
+
}
|
|
282
|
+
case 'unit':
|
|
283
|
+
return uplc_1.UPLCConst.unit;
|
|
284
|
+
default:
|
|
285
|
+
throw new Error(`Unknown script param uplc type "${String(uplc)}"; expected one of: data, bytes, int, bool, unit`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
// Bare PlutusData → apply as Data (Aiken / blueprint convention)
|
|
289
|
+
return uplc_1.UPLCConst.data(jsonToPlutusData(param));
|
|
290
|
+
}
|
|
225
291
|
/**
|
|
226
292
|
* Apply parameters to a parameterized PlutusV3 script (CBOR-wrapped flat UPLC).
|
|
227
|
-
* Each parameter
|
|
228
|
-
*
|
|
229
|
-
*
|
|
293
|
+
* Each parameter becomes a successive UPLC Application wrapping the program body.
|
|
294
|
+
*
|
|
295
|
+
* Parameters are applied in their declared UPLC type via {@link encodeScriptParam}:
|
|
296
|
+
* pass `{ uplc, value }` entries for native-typed params (e.g. Pebble scalars),
|
|
297
|
+
* or bare PlutusData objects for the Data convention (Aiken / CIP-57 blueprints).
|
|
298
|
+
*
|
|
299
|
+
* @param scriptHex CBOR hex of the unapplied Plutus script (as output by Aiken/Pebble/Plutus compilers)
|
|
300
|
+
* @param params Array of script parameters (typed `{uplc,value}` and/or bare PlutusData JSON) to apply in order
|
|
230
301
|
* @returns CBOR hex of the applied script (ready for transaction building)
|
|
231
302
|
*/
|
|
232
303
|
function applyScriptParameters(scriptHex, params) {
|
|
@@ -238,11 +309,10 @@ function applyScriptParameters(scriptHex, params) {
|
|
|
238
309
|
const flatBytes = cborObj.bytes;
|
|
239
310
|
// 2. Flat-decode → UPLCProgram
|
|
240
311
|
const program = uplc_1.UPLCDecoder.parse(flatBytes, 'flat');
|
|
241
|
-
// 3. Apply each parameter as Application(body,
|
|
312
|
+
// 3. Apply each parameter as Application(body, <typed UPLC constant>)
|
|
242
313
|
let body = program.body;
|
|
243
314
|
for (const param of params) {
|
|
244
|
-
|
|
245
|
-
body = new uplc_1.Application(body, uplc_1.UPLCConst.data(paramData));
|
|
315
|
+
body = new uplc_1.Application(body, encodeScriptParam(param));
|
|
246
316
|
}
|
|
247
317
|
// 4. Create new program with applied body, flat-encode, CBOR-wrap
|
|
248
318
|
const applied = new uplc_1.UPLCProgram(program.version, body);
|