@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
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 +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -4,45 +4,39 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.BuildooorTxBuilder = void 0;
|
|
7
|
-
// Coin selection uses this.txBuilder.keepRelevant again since buildooor 0.2.9
|
|
8
|
-
// ships the fixed implementation (our PR); the vendored keep-relevant.ts is gone.
|
|
9
7
|
const buildooor_1 = require("@harmoniclabs/buildooor");
|
|
10
8
|
const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
|
|
9
|
+
const crypto_1 = require("@harmoniclabs/crypto");
|
|
11
10
|
const tx_build_helper_1 = require("../../utils/tx-build-helper");
|
|
12
11
|
const errors_1 = require("../../utils/errors");
|
|
13
12
|
const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
|
|
14
13
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
15
14
|
const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
|
|
16
|
-
// Metadata classes
|
|
17
|
-
//
|
|
18
|
-
// dist-class identities, which differ from the package-root re-exports. Mixing
|
|
19
|
-
// root + dist identities breaks those checks at runtime. (See cbor-parse.test.)
|
|
15
|
+
// Metadata classes come from the dist paths on purpose. Buildooor's `instanceof` checks
|
|
16
|
+
// match these exact classes, not the package-root re-exports.
|
|
20
17
|
const TxMetadata_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadata");
|
|
21
18
|
const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadatum");
|
|
22
19
|
const plutus_data_1 = require("@harmoniclabs/plutus-data");
|
|
23
20
|
const const_1 = require("../../utils/const");
|
|
21
|
+
const reference_script_1 = require("../../utils/reference-script");
|
|
24
22
|
const logger = cds_1.default.log('BuildooorTxBuilder');
|
|
25
23
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* Buildooor evaluates every Plutus script locally during `build()` and unconditionally
|
|
29
|
-
* stamps each redeemer with the budget its local CEK run consumed (`onEvaluationResult`
|
|
30
|
-
* in TxBuilder) — execution units passed in the build args are never read. Without an
|
|
31
|
-
* `onScriptInvalid` handler a local evaluation failure aborts the build; *with* one the
|
|
32
|
-
* redeemer is left carrying the partial budget consumed up to the error, which would
|
|
33
|
-
* fail phase-2 on-chain and forfeit the collateral if signed and submitted.
|
|
34
|
-
*
|
|
35
|
-
* We therefore only record local failures here; `_buildScriptTx` decides afterwards:
|
|
36
|
-
* an authoritative Ogmios evaluation overrides the local result (so local false
|
|
37
|
-
* negatives — e.g. cost-model drift — don't block the build), while a failure without
|
|
38
|
-
* Ogmios aborts with a clear error instead of returning an unsubmittable transaction.
|
|
24
|
+
* Records local script failures instead of aborting, so `_buildScriptTx` can let Ogmios decide.
|
|
39
25
|
*/
|
|
40
26
|
function makeScriptBuildOpts(failures) {
|
|
27
|
+
// The machine's message comes with the result, which Buildooor reports before onScriptInvalid.
|
|
28
|
+
const machineErrors = new Map();
|
|
41
29
|
return {
|
|
30
|
+
onScriptResult: (rdmr, result) => {
|
|
31
|
+
const msg = result?.msg;
|
|
32
|
+
if (typeof msg === 'string' && msg)
|
|
33
|
+
machineErrors.set(redeemerKey(rdmr.tag, rdmr.index), msg);
|
|
34
|
+
},
|
|
42
35
|
onScriptInvalid: (rdmr, logs) => {
|
|
43
|
-
|
|
36
|
+
const error = machineErrors.get(redeemerKey(rdmr.tag, rdmr.index)) ?? null;
|
|
37
|
+
failures.push({ tag: rdmr.tag, index: rdmr.index, logs: logs.slice(), error });
|
|
44
38
|
logger.warn(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(rdmr.tag)}:${rdmr.index}); ` +
|
|
45
|
-
`deferring to Ogmios evaluation if available. Logs: [${logs.join(', ')}]`);
|
|
39
|
+
`deferring to Ogmios evaluation if available. Machine error: ${error ?? 'none reported'}. Logs: [${logs.join(', ')}]`);
|
|
46
40
|
}
|
|
47
41
|
};
|
|
48
42
|
}
|
|
@@ -74,41 +68,29 @@ function ceilDiv(a, b) {
|
|
|
74
68
|
function maxBig(a, b) {
|
|
75
69
|
return a > b ? a : b;
|
|
76
70
|
}
|
|
77
|
-
/**
|
|
78
|
-
* Parse a ledger protocol-parameter value (number or decimal string) into a
|
|
79
|
-
* non-negative safe integer. Returns undefined for null/undefined/empty/invalid
|
|
80
|
-
* input so callers can fall back to library defaults instead of silently
|
|
81
|
-
* coercing to 0 (which e.g. disables min-ADA when applied to utxoCostPerByte).
|
|
82
|
-
*/
|
|
71
|
+
/** Non-negative safe integer, or undefined so callers keep library defaults instead of 0. */
|
|
83
72
|
function toUInt(value) {
|
|
84
73
|
if (value === null || value === undefined || value === '')
|
|
85
74
|
return undefined;
|
|
86
75
|
const n = Number(value);
|
|
87
76
|
return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
|
|
88
77
|
}
|
|
89
|
-
/**
|
|
78
|
+
/** Strictly positive finite number, else undefined. */
|
|
90
79
|
function toPositiveNumber(value) {
|
|
91
80
|
if (value === null || value === undefined || value === '')
|
|
92
81
|
return undefined;
|
|
93
82
|
const n = Number(value);
|
|
94
83
|
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
95
84
|
}
|
|
96
|
-
/**
|
|
97
|
-
* Stable identity of a protocol-parameter set. Params only change at epoch
|
|
98
|
-
* boundaries, so network#epoch is sufficient; fall back to full JSON when
|
|
99
|
-
* either field is missing.
|
|
100
|
-
*/
|
|
85
|
+
/** Stable identity of a protocol-parameter set: network#epoch (params change per epoch), else full JSON. */
|
|
101
86
|
function protocolParamsFingerprint(p) {
|
|
102
87
|
if (p.network && p.epoch !== undefined && p.epoch !== null)
|
|
103
88
|
return `${p.network}#${p.epoch}`;
|
|
104
89
|
return JSON.stringify(p);
|
|
105
90
|
}
|
|
106
|
-
/** Ledger limit for
|
|
91
|
+
/** Ledger limit for one text or bytes metadatum, counted in bytes. */
|
|
107
92
|
const METADATA_BYTE_LIMIT = 64;
|
|
108
|
-
/**
|
|
109
|
-
* Split a string into pieces of at most maxBytes UTF-8 bytes each, never
|
|
110
|
-
* splitting inside a code point (which would produce invalid UTF-8 on-chain).
|
|
111
|
-
*/
|
|
93
|
+
/** Split a string into pieces of at most maxBytes UTF-8 bytes without splitting a code point. */
|
|
112
94
|
function chunkUtf8(str, maxBytes) {
|
|
113
95
|
const chunks = [];
|
|
114
96
|
let current = '';
|
|
@@ -129,27 +111,22 @@ function chunkUtf8(str, maxBytes) {
|
|
|
129
111
|
chunks.push(current);
|
|
130
112
|
return chunks;
|
|
131
113
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
114
|
+
// Script.fromCbor keeps the compiler bytes, but an output's script_ref needs the ledger form.
|
|
115
|
+
// Rebuilding the script gives that form. The hash stays the same.
|
|
116
|
+
function ledgerScript(script) {
|
|
117
|
+
return new cardano_ledger_ts_1.Script(script.type, script.bytes);
|
|
118
|
+
}
|
|
119
|
+
const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
|
|
120
|
+
/** CardanoTxBuilder implementation on top of Buildooor. */
|
|
135
121
|
class BuildooorTxBuilder {
|
|
136
122
|
name = 'BuildooorTxBuilder';
|
|
137
123
|
txBuilder;
|
|
138
124
|
cardanoClient;
|
|
139
125
|
genesisInfos;
|
|
140
126
|
paramsFingerprint;
|
|
141
|
-
/**
|
|
142
|
-
* Chain cost-model arrays kept verbatim for language-view hashing. Maintained by
|
|
143
|
-
* _mapCostModels (in lockstep with the named-key models the TxBuilder is built
|
|
144
|
-
* with); consumed by _languageViewCostModels. Empty when the current parameters
|
|
145
|
-
* carry no usable cost models (library defaults in effect).
|
|
146
|
-
*/
|
|
127
|
+
/** Chain cost-model arrays kept verbatim for language-view hashing. */
|
|
147
128
|
rawCostModelArrays = {};
|
|
148
|
-
/**
|
|
149
|
-
* Initialize the builder
|
|
150
|
-
* @param client - The CardanoClient instance
|
|
151
|
-
* @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
|
|
152
|
-
*/
|
|
129
|
+
/** Initialize the builder. Protocol parameters are fetched when omitted. */
|
|
153
130
|
async init(client, protocolParams) {
|
|
154
131
|
this.cardanoClient = client;
|
|
155
132
|
const params = protocolParams ?? await client.getProtocolParameters();
|
|
@@ -161,13 +138,7 @@ class BuildooorTxBuilder {
|
|
|
161
138
|
this._applyProtocolParameters(params, protocolParamsFingerprint(params));
|
|
162
139
|
logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
|
|
163
140
|
}
|
|
164
|
-
/**
|
|
165
|
-
* Rebuild the TxBuilder when the per-request protocol parameters differ from
|
|
166
|
-
* the ones the current TxBuilder was constructed with. Buildooor's TxBuilder
|
|
167
|
-
* has no setter for protocol params, but its constructor is cheap, so we
|
|
168
|
-
* rebuild on change (effectively once per epoch) instead of staying frozen
|
|
169
|
-
* at init-time parameters for the process lifetime.
|
|
170
|
-
*/
|
|
141
|
+
/** TxBuilder has no setter, so it is rebuilt when the protocol parameters change. */
|
|
171
142
|
_ensureCurrentProtocolParameters(ctx) {
|
|
172
143
|
const params = ctx.protocolParameters;
|
|
173
144
|
if (!params)
|
|
@@ -182,25 +153,16 @@ class BuildooorTxBuilder {
|
|
|
182
153
|
this.txBuilder = new buildooor_1.TxBuilder(this._mapLedgerParametersToBuildooorParams(params), this.genesisInfos);
|
|
183
154
|
this.paramsFingerprint = fingerprint;
|
|
184
155
|
}
|
|
185
|
-
/**
|
|
186
|
-
* Build unsigned transfer transaction (ADA-only or with native assets).
|
|
187
|
-
*/
|
|
156
|
+
/** Build an unsigned transfer transaction (ADA-only or with native assets). */
|
|
188
157
|
buildUnsignedTransfer(req, ctx) {
|
|
189
|
-
return this._buildSimpleTransfer(req, ctx, 'transfer');
|
|
158
|
+
return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'transfer', include));
|
|
190
159
|
}
|
|
191
|
-
/**
|
|
192
|
-
* Build unsigned transfer transaction with attached metadata.
|
|
193
|
-
*/
|
|
160
|
+
/** Build an unsigned transfer transaction with attached metadata. */
|
|
194
161
|
buildUnsignedTransactionWithMetadata(req, ctx) {
|
|
195
|
-
return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
|
|
162
|
+
return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'metadata transfer', include));
|
|
196
163
|
}
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
* the optional pieces of the request they carry (assets/outputDatum on the
|
|
200
|
-
* plain-transfer path, metadataJson on the metadata path) — all handled here
|
|
201
|
-
* conditionally on the field being present, so behaviour matches both.
|
|
202
|
-
*/
|
|
203
|
-
async _buildSimpleTransfer(req, ctx, label) {
|
|
164
|
+
/** Shared non-script transfer build. */
|
|
165
|
+
async _buildSimpleTransfer(req, ctx, label, includeRefScriptUtxos) {
|
|
204
166
|
try {
|
|
205
167
|
this._ensureCurrentProtocolParameters(ctx);
|
|
206
168
|
if (!ctx.utxos || ctx.utxos.length === 0) {
|
|
@@ -209,15 +171,30 @@ class BuildooorTxBuilder {
|
|
|
209
171
|
const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
|
|
210
172
|
const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
|
|
211
173
|
const amount = BigInt(String(req.lovelaceAmount));
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
if (req.assets && req.assets.length > 0) {
|
|
215
|
-
outputValue = this._buildLedgerValue(amount, req.assets);
|
|
174
|
+
if (req.outputDatum !== undefined && req.outputDatumCbor !== undefined) {
|
|
175
|
+
throw new errors_1.TransactionValidationError('outputDatum and outputDatumCbor exclude each other; pass one');
|
|
216
176
|
}
|
|
177
|
+
// a datum given as CBOR keeps its bytes
|
|
178
|
+
const datum = req.outputDatumCbor !== undefined ? (0, plutus_data_1.dataFromCbor)(req.outputDatumCbor) : undefined;
|
|
217
179
|
const refScript = this._parseReferenceScript(req.referenceScript);
|
|
218
|
-
const
|
|
180
|
+
const recipientOut = (lovelace) => {
|
|
181
|
+
const value = this._buildLedgerValue(lovelace, req.assets);
|
|
182
|
+
return datum
|
|
183
|
+
? new cardano_ledger_ts_1.TxOut({ address: recipientAddress, value, datum, ...(refScript && { refScript }) })
|
|
184
|
+
: this._buildTxOut(recipientAddress, value, req.outputDatum, refScript);
|
|
185
|
+
};
|
|
186
|
+
let recipient = recipientOut(amount);
|
|
187
|
+
const minLovelace = this._minOutputLovelace(recipient);
|
|
188
|
+
if (amount < minLovelace) {
|
|
189
|
+
if (!req.ensureMinAda) {
|
|
190
|
+
throw new errors_1.TransactionValidationError(`recipient output needs at least ${minLovelace.toString()} lovelace (has ${amount.toString()}); raise lovelaceAmount or set ensureMinAda`);
|
|
191
|
+
}
|
|
192
|
+
recipient = recipientOut(this._minOutputLovelace(recipient, true));
|
|
193
|
+
}
|
|
194
|
+
const outputValue = recipient.value;
|
|
195
|
+
const outputs = [recipient];
|
|
219
196
|
// Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
|
|
220
|
-
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
197
|
+
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
|
|
221
198
|
const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
|
|
222
199
|
const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
|
|
223
200
|
// Coin selection on candidates only; forced inputs are prepended unconditionally
|
|
@@ -233,21 +210,24 @@ class BuildooorTxBuilder {
|
|
|
233
210
|
return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
|
|
234
211
|
}
|
|
235
212
|
catch (err) {
|
|
236
|
-
|
|
213
|
+
// one requested output; Buildooor appends the change after it
|
|
214
|
+
(0, tx_build_helper_1.mapBuilderError)(err, undefined, undefined, 1);
|
|
237
215
|
}
|
|
238
216
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
217
|
+
buildUnsignedMintTransaction(req, ctx) {
|
|
218
|
+
return this._withRefScriptFallback(ctx.utxos, (include) => this._buildMintTransaction(req, ctx, include));
|
|
219
|
+
}
|
|
220
|
+
async _buildMintTransaction(req, ctx, includeRefScriptUtxos) {
|
|
221
|
+
// Set once the collateral partition is known: it explains insufficient-funds rejections
|
|
222
|
+
// that the builder's own message cannot attribute.
|
|
242
223
|
let coinSelectionContext;
|
|
224
|
+
let requestedOutputs;
|
|
243
225
|
try {
|
|
244
226
|
this._ensureCurrentProtocolParameters(ctx);
|
|
245
227
|
const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
|
|
246
228
|
const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
|
|
247
|
-
// Parse the minting policy script once
|
|
248
229
|
const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
|
|
249
|
-
//
|
|
250
|
-
// Multi-policy mint FR: each action mints under ITS script (own or top-level).
|
|
230
|
+
// Total mint value for the output (positive quantities only); each action mints under its own policy script.
|
|
251
231
|
let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
|
|
252
232
|
for (const [index, mintAction] of req.mintActions.entries()) {
|
|
253
233
|
const quantity = BigInt(mintAction.quantity);
|
|
@@ -258,27 +238,25 @@ class BuildooorTxBuilder {
|
|
|
258
238
|
}
|
|
259
239
|
}
|
|
260
240
|
// Partition forced vs candidate UTxOs. Forced inputs are already committed;
|
|
261
|
-
//
|
|
262
|
-
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
241
|
+
// coin selection operates on the remainder only.
|
|
242
|
+
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
|
|
263
243
|
const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
|
|
264
|
-
//
|
|
265
|
-
|
|
266
|
-
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
|
|
267
|
-
const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
|
|
268
|
-
const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
|
|
269
|
-
// Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
|
|
270
|
-
// thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
|
|
271
|
-
// demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
|
|
272
|
-
// from the wallet).
|
|
244
|
+
// Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
|
|
245
|
+
// demand the mint itself does not cover.
|
|
273
246
|
let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
|
|
274
247
|
if (req.extraOutputs && req.extraOutputs.length > 0) {
|
|
275
248
|
const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
|
|
276
249
|
requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
|
|
277
250
|
}
|
|
251
|
+
// Collateral + funding separation from the candidates; a forced input is collateral only as a fallback
|
|
252
|
+
const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress);
|
|
253
|
+
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
|
|
254
|
+
const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
|
|
255
|
+
const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
|
|
278
256
|
const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
|
|
279
257
|
const inputs = [...forcedInputs, ...selectedFunding];
|
|
280
258
|
logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
|
|
281
|
-
//
|
|
259
|
+
// Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
|
|
282
260
|
const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
|
|
283
261
|
...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
|
|
284
262
|
...this._extractFundingRefs(selectedFunding)
|
|
@@ -291,10 +269,8 @@ class BuildooorTxBuilder {
|
|
|
291
269
|
? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
|
|
292
270
|
: undefined;
|
|
293
271
|
const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
// token on its own output with its own datum, e.g. datum-bound predicate
|
|
297
|
-
// tokens), so the primary output stays ADA(+datum)-only.
|
|
272
|
+
// Primary output: minted assets + min ADA. With extra outputs declared, those carry
|
|
273
|
+
// the minted assets and the primary output stays ADA(+datum)-only.
|
|
298
274
|
let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
|
|
299
275
|
if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
|
|
300
276
|
outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
|
|
@@ -303,23 +279,20 @@ class BuildooorTxBuilder {
|
|
|
303
279
|
const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
|
|
304
280
|
// Append extra outputs, each independently min-ADA checked.
|
|
305
281
|
this._appendExtraOutputs(outputs, resolvedExtraOutputs);
|
|
306
|
-
|
|
307
|
-
//
|
|
308
|
-
//
|
|
309
|
-
|
|
310
|
-
const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
|
|
282
|
+
requestedOutputs = outputs.length;
|
|
283
|
+
// Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
|
|
284
|
+
// stamped post-build by _buildScriptTx.
|
|
285
|
+
const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
|
|
311
286
|
// CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
|
|
312
287
|
const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
|
|
313
|
-
//
|
|
314
|
-
// and fee computation stay consistent (a mismatch would force re-evaluation).
|
|
288
|
+
// Both passes must share the validity bounds so redeemer ExUnits and fee stay consistent.
|
|
315
289
|
const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
|
|
316
|
-
// CIP-20
|
|
317
|
-
//
|
|
290
|
+
// Auxiliary metadata (CIP-20, label 674, ...) must be identical across eval + final passes:
|
|
291
|
+
// it affects tx size (fee) and the script data hash.
|
|
318
292
|
const mintMetadata = req.metadataJson
|
|
319
293
|
? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
|
|
320
294
|
: undefined;
|
|
321
|
-
//
|
|
322
|
-
// validity bounds and metadata so redeemer ExUnits and fee stay consistent.
|
|
295
|
+
// One set of build args shared by both internal passes and the Ogmios evaluation.
|
|
323
296
|
const buildParams = {
|
|
324
297
|
inputs, outputs, changeAddress, mints,
|
|
325
298
|
collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
|
|
@@ -333,23 +306,24 @@ class BuildooorTxBuilder {
|
|
|
333
306
|
return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
|
|
334
307
|
}
|
|
335
308
|
catch (err) {
|
|
336
|
-
(0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
|
|
309
|
+
(0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
|
|
337
310
|
}
|
|
338
311
|
}
|
|
339
|
-
|
|
340
|
-
|
|
312
|
+
buildUnsignedPlutusSpendTransaction(req, ctx) {
|
|
313
|
+
return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusSpendTransaction(req, ctx, include));
|
|
314
|
+
}
|
|
315
|
+
async _buildPlutusSpendTransaction(req, ctx, includeRefScriptUtxos) {
|
|
316
|
+
// Same collateral-partition context as in _buildMintTransaction.
|
|
341
317
|
let coinSelectionContext;
|
|
318
|
+
let requestedOutputs;
|
|
342
319
|
try {
|
|
343
320
|
this._ensureCurrentProtocolParameters(ctx);
|
|
344
321
|
const { plutusScriptExecution } = req;
|
|
345
|
-
// Parse the validator script
|
|
346
322
|
const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
|
|
347
323
|
if (!plutusScriptExecution.datum) {
|
|
348
|
-
//
|
|
349
|
-
|
|
350
|
-
logger.debug('No datumJson provided — expecting inline datum on script UTxO');
|
|
324
|
+
// Without an explicit datum the script UTxO must carry an inline datum.
|
|
325
|
+
logger.debug('No datumJson provided, expecting inline datum on script UTxO');
|
|
351
326
|
}
|
|
352
|
-
// Find the specific script UTxO in the provided context UTxOs
|
|
353
327
|
const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
|
|
354
328
|
const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
|
|
355
329
|
if (!scriptOdatanoUtxo) {
|
|
@@ -360,35 +334,38 @@ class BuildooorTxBuilder {
|
|
|
360
334
|
const senderUtxos = ctx.utxos.filter(u => !(u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex));
|
|
361
335
|
const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
|
|
362
336
|
const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
|
|
363
|
-
//
|
|
337
|
+
// A forced input that matches the script UTxO is silently ignored.
|
|
364
338
|
const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
|
|
365
|
-
const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
|
|
339
|
+
const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
|
|
366
340
|
const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
|
|
367
|
-
//
|
|
368
|
-
|
|
369
|
-
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
|
|
370
|
-
const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
|
|
371
|
-
// Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
|
|
372
|
-
// Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
|
|
373
|
-
// already provides will net out, so over-requesting is harmless — keepRelevant prefers smaller sets.
|
|
374
|
-
const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
|
|
341
|
+
// Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
|
|
342
|
+
// assets the script UTxO already provides net out, so over-requesting is harmless.
|
|
375
343
|
let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
|
|
376
344
|
if (req.extraOutputs && req.extraOutputs.length > 0) {
|
|
377
345
|
for (const extra of req.extraOutputs) {
|
|
378
346
|
requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
|
|
379
347
|
}
|
|
380
348
|
}
|
|
349
|
+
// Collateral + funding separation from the candidates; a forced input is collateral only as a fallback.
|
|
350
|
+
// The script UTxO pays its part of the outputs, so the collateral check counts only the rest.
|
|
351
|
+
const fundingGap = requiredFundingValue.lovelaces - (0, tx_build_helper_1.getLovelace)(scriptOdatanoUtxo);
|
|
352
|
+
const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, fundingGap > 0n ? fundingGap : 0n, forced, req.senderAddress);
|
|
353
|
+
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
|
|
354
|
+
const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
|
|
355
|
+
const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
|
|
381
356
|
const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
|
|
382
357
|
logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
|
|
383
|
-
//
|
|
384
|
-
|
|
385
|
-
const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
|
|
358
|
+
// Resolve __INPUT_IDX__ placeholders against Buildooor's input order before PlutusData encoding.
|
|
359
|
+
const sortedInputs = this._computeSortedInputs([scriptUtxoRef], forced, this._extractFundingRefs(selectedFundingInputs));
|
|
386
360
|
const resolveCtx = { sortedInputs };
|
|
387
361
|
const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
|
|
388
362
|
const redeemerData = (0, tx_build_helper_1.jsonToPlutusData)(resolvedRedeemer);
|
|
389
363
|
const datum = plutusScriptExecution.datum
|
|
390
364
|
? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.datum, resolveCtx))
|
|
391
365
|
: "inline";
|
|
366
|
+
if (datum !== "inline") {
|
|
367
|
+
this._checkWitnessDatum(scriptOdatanoUtxo, (0, plutus_data_1.dataToCbor)(datum), 'datumJson', '; BuildPlutusTransaction takes the datum as datumCbor with the bytes the UTxO was locked with');
|
|
368
|
+
}
|
|
392
369
|
const resolvedPrimaryInlineDatum = req.inlineDatum
|
|
393
370
|
? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
|
|
394
371
|
: undefined;
|
|
@@ -396,7 +373,7 @@ class BuildooorTxBuilder {
|
|
|
396
373
|
const resolvedMintRedeemer = req.mintRedeemer
|
|
397
374
|
? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
|
|
398
375
|
: undefined;
|
|
399
|
-
//
|
|
376
|
+
// Combined spend+mint: with mintActions present, mints are built alongside the spend input.
|
|
400
377
|
const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
|
|
401
378
|
let mintScript;
|
|
402
379
|
let mintScriptHash;
|
|
@@ -404,7 +381,7 @@ class BuildooorTxBuilder {
|
|
|
404
381
|
mintScript = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
|
|
405
382
|
mintScriptHash = mintScript.hash.toString();
|
|
406
383
|
}
|
|
407
|
-
//
|
|
384
|
+
// The continuing output carries the multi-assets of the script UTxO.
|
|
408
385
|
const scriptNonAdaAssets = scriptOdatanoUtxo.amount.filter(a => a.unit.toLowerCase() !== 'lovelace' && BigInt(a.quantity) > 0n);
|
|
409
386
|
let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
|
|
410
387
|
if (scriptNonAdaAssets.length > 0) {
|
|
@@ -423,14 +400,13 @@ class BuildooorTxBuilder {
|
|
|
423
400
|
}
|
|
424
401
|
const primaryRefScript = this._parseReferenceScript(req.referenceScript);
|
|
425
402
|
const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedPrimaryInlineDatum, primaryRefScript)];
|
|
426
|
-
// Append extra outputs
|
|
427
|
-
// get a clear, field-attributed error before Buildooor's coin selection runs.
|
|
403
|
+
// Append extra outputs, each independently min-ADA checked.
|
|
428
404
|
this._appendExtraOutputs(outputs, resolvedExtraOutputs);
|
|
429
|
-
|
|
430
|
-
//
|
|
431
|
-
//
|
|
405
|
+
requestedOutputs = outputs.length;
|
|
406
|
+
// Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
|
|
407
|
+
// units, the real ones are stamped post-build by _buildScriptTx.
|
|
432
408
|
const mints = hasMint
|
|
433
|
-
? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
|
|
409
|
+
? this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, mintScript, i) }), resolvedMintRedeemer, resolveCtx)
|
|
434
410
|
: undefined;
|
|
435
411
|
const scriptInput = {
|
|
436
412
|
utxo: scriptLedgerUtxo,
|
|
@@ -439,11 +415,9 @@ class BuildooorTxBuilder {
|
|
|
439
415
|
const inputs = [scriptInput, ...forcedInputs, ...selectedFundingInputs];
|
|
440
416
|
// CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
|
|
441
417
|
const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
|
|
442
|
-
//
|
|
443
|
-
// and fee computation stay consistent (a mismatch would force re-evaluation).
|
|
418
|
+
// Both passes must share the validity bounds so redeemer ExUnits and fee stay consistent.
|
|
444
419
|
const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
|
|
445
|
-
//
|
|
446
|
-
// validity bounds so redeemer ExUnits and fee stay consistent.
|
|
420
|
+
// One set of build args shared by both internal passes and the Ogmios evaluation.
|
|
447
421
|
const buildParams = {
|
|
448
422
|
inputs, outputs, changeAddress,
|
|
449
423
|
mints,
|
|
@@ -462,9 +436,269 @@ class BuildooorTxBuilder {
|
|
|
462
436
|
});
|
|
463
437
|
}
|
|
464
438
|
catch (err) {
|
|
465
|
-
(0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
|
|
439
|
+
(0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
|
|
466
440
|
}
|
|
467
441
|
}
|
|
442
|
+
// Several script inputs, each with its own redeemer and an inline or referenced validator.
|
|
443
|
+
// Outputs keep the given order, change comes after them.
|
|
444
|
+
buildUnsignedPlutusTransaction(req, ctx) {
|
|
445
|
+
return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusTransaction(req, ctx, include));
|
|
446
|
+
}
|
|
447
|
+
async _buildPlutusTransaction(req, ctx, includeRefScriptUtxos) {
|
|
448
|
+
let coinSelectionContext;
|
|
449
|
+
let requestedOutputs;
|
|
450
|
+
try {
|
|
451
|
+
this._ensureCurrentProtocolParameters(ctx);
|
|
452
|
+
const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
|
|
453
|
+
const utxoByKey = new Map(ctx.utxos.map(u => [keyOf(u), u]));
|
|
454
|
+
const refUtxoByKey = new Map((ctx.referenceInputUtxos ?? []).map(u => [keyOf(u), u]));
|
|
455
|
+
const scriptKeys = new Set(req.scriptInputs.map(keyOf));
|
|
456
|
+
// Scripts the reference inputs already carry: the ledger rejects the same script again as a
|
|
457
|
+
// witness (ExtraneousScriptWitnesses), so an inline validator with such a hash uses the reference.
|
|
458
|
+
const referencedByHash = new Map();
|
|
459
|
+
for (const u of ctx.referenceInputUtxos ?? []) {
|
|
460
|
+
const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(u);
|
|
461
|
+
const hash = ledgerUtxo.resolved.refScript?.hash.toString();
|
|
462
|
+
if (hash && !referencedByHash.has(hash))
|
|
463
|
+
referencedByHash.set(hash, ledgerUtxo);
|
|
464
|
+
}
|
|
465
|
+
// Script inputs: each UTxO with its script (inline, or the ledger UTxO carrying it)
|
|
466
|
+
const scriptEntries = req.scriptInputs.map((si, i) => {
|
|
467
|
+
const utxo = utxoByKey.get(keyOf(si));
|
|
468
|
+
if (!utxo)
|
|
469
|
+
throw new errors_1.TransactionValidationError(`scriptInputs[${i}] ${keyOf(si)} not found on-chain or already spent`);
|
|
470
|
+
if (si.validatorScript) {
|
|
471
|
+
const script = this._parsePlutusV3Script(si.validatorScript, `scriptInputs[${i}].validatorScript`);
|
|
472
|
+
const scriptHash = script.hash.toString();
|
|
473
|
+
const referenced = referencedByHash.get(scriptHash);
|
|
474
|
+
return referenced ? { si, utxo, refLedgerUtxo: referenced, scriptHash } : { si, utxo, script };
|
|
475
|
+
}
|
|
476
|
+
const refKey = keyOf(si.referenceScript);
|
|
477
|
+
const refUtxo = refUtxoByKey.get(refKey);
|
|
478
|
+
if (!refUtxo)
|
|
479
|
+
throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} not found on-chain or already spent`);
|
|
480
|
+
const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
|
|
481
|
+
if (!refLedgerUtxo.resolved.refScript) {
|
|
482
|
+
throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
|
|
483
|
+
`from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
|
|
484
|
+
}
|
|
485
|
+
return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
|
|
486
|
+
});
|
|
487
|
+
// Withdrawals: the staking script inline, by reference, or the one a reference input carries
|
|
488
|
+
const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
|
|
489
|
+
w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
|
|
490
|
+
...this._resolveScriptWitness({ script: w.stakingScript, referenceScript: w.referenceScript }, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
|
|
491
|
+
}));
|
|
492
|
+
// Certificates: the credential from the stake address; a script runs under the Certifying purpose
|
|
493
|
+
const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
|
|
494
|
+
const certEntries = (req.certificates ?? []).map((c, i) => {
|
|
495
|
+
const at = `certificates[${i}]`;
|
|
496
|
+
const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
|
|
497
|
+
const credentialHash = stake.credentials.toString().toLowerCase();
|
|
498
|
+
const witness = this._resolveScriptWitness({ script: c.stakingScript, referenceScript: c.referenceScript }, at, referencedByHash, refUtxoByKey);
|
|
499
|
+
const scripted = Boolean(witness.script || witness.refLedgerUtxo);
|
|
500
|
+
const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
|
|
501
|
+
if (stake.type === 'script') {
|
|
502
|
+
if (scripted && witnessHash !== credentialHash) {
|
|
503
|
+
throw new errors_1.TransactionValidationError(`${at} staking script hash ${witnessHash} is not the credential of ${c.stakeAddress} (${credentialHash})`);
|
|
504
|
+
}
|
|
505
|
+
if (!scripted && c.type === 'deregisterStake') {
|
|
506
|
+
throw new errors_1.TransactionValidationError(`${at} deregisters the script credential ${c.stakeAddress}; its staking script and redeemer are needed`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if (scripted) {
|
|
510
|
+
throw new errors_1.TransactionValidationError(`${at} ${c.stakeAddress} is a key credential; it takes no staking script`);
|
|
511
|
+
}
|
|
512
|
+
const stakeCredential = stake.type === 'script' ? cardano_ledger_ts_1.Credential.script(stake.credentials) : cardano_ledger_ts_1.Credential.keyHash(stake.credentials);
|
|
513
|
+
const deposit = c.deposit ? BigInt(c.deposit) : stakeDeposit;
|
|
514
|
+
// Without a script the witness-free legacy registration; the deposit forms need the witness
|
|
515
|
+
const cert = c.type === 'registerStake'
|
|
516
|
+
? (scripted ? new cardano_ledger_ts_1.CertRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeRegistration({ stakeCredential }))
|
|
517
|
+
: (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
|
|
518
|
+
return { c, cert, deposit, ...witness };
|
|
519
|
+
});
|
|
520
|
+
// Mints: each policy inline, by reference, or the one a reference input carries
|
|
521
|
+
const mintEntries = (req.mintActions ?? []).map((m, i) => {
|
|
522
|
+
const at = `mintActions[${i}]`;
|
|
523
|
+
const witness = this._resolveScriptWitness({ script: m.mintingPolicyScript, referenceScript: m.referenceScript }, at, referencedByHash, refUtxoByKey, 'mintingPolicyScript');
|
|
524
|
+
const policyId = (witness.script?.hash ?? witness.refLedgerUtxo.resolved.refScript.hash).toString().toLowerCase();
|
|
525
|
+
if (!m.assetUnit.toLowerCase().startsWith(policyId)) {
|
|
526
|
+
throw new errors_1.TransactionValidationError(`${at}.assetUnit ${m.assetUnit} is not under the policy ${policyId} of its script`);
|
|
527
|
+
}
|
|
528
|
+
return { m, policyId, ...witness };
|
|
529
|
+
});
|
|
530
|
+
// one policy runs from one place: once any action of it uses a reference script, all do
|
|
531
|
+
const mintRefByPolicy = new Map();
|
|
532
|
+
for (const e of mintEntries)
|
|
533
|
+
if (e.refLedgerUtxo && !mintRefByPolicy.has(e.policyId))
|
|
534
|
+
mintRefByPolicy.set(e.policyId, e.refLedgerUtxo);
|
|
535
|
+
for (const e of mintEntries) {
|
|
536
|
+
const ref = mintRefByPolicy.get(e.policyId);
|
|
537
|
+
if (ref) {
|
|
538
|
+
e.refLedgerUtxo = ref;
|
|
539
|
+
e.script = undefined;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
|
|
543
|
+
const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
|
|
544
|
+
const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
|
|
545
|
+
if (scriptKeyClash)
|
|
546
|
+
throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
|
|
547
|
+
const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs, includeRefScriptUtxos);
|
|
548
|
+
this._checkForeignForcedInputs(forced, req);
|
|
549
|
+
const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
|
|
550
|
+
// Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
|
|
551
|
+
// withdrawals (keepRelevant adds its own lovelace margin for fee and change).
|
|
552
|
+
const need = new Map();
|
|
553
|
+
const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
|
|
554
|
+
for (const o of req.outputs) {
|
|
555
|
+
add('lovelace', BigInt(o.lovelaceAmount));
|
|
556
|
+
for (const a of o.assets ?? [])
|
|
557
|
+
add(a.unit, BigInt(a.quantity));
|
|
558
|
+
}
|
|
559
|
+
for (const u of [...scriptEntries.map(e => e.utxo), ...forced]) {
|
|
560
|
+
for (const a of u.amount)
|
|
561
|
+
add(a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit, -BigInt(a.quantity));
|
|
562
|
+
}
|
|
563
|
+
for (const m of req.mintActions ?? [])
|
|
564
|
+
add(m.assetUnit, -BigInt(m.quantity));
|
|
565
|
+
for (const { w } of withdrawalEntries)
|
|
566
|
+
add('lovelace', -BigInt(w.lovelace));
|
|
567
|
+
// a registration locks the deposit, a deregistration refunds it
|
|
568
|
+
for (const { c, deposit } of certEntries)
|
|
569
|
+
add('lovelace', c.type === 'registerStake' ? deposit : -deposit);
|
|
570
|
+
let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
|
|
571
|
+
for (const [unit, qty] of need) {
|
|
572
|
+
if (qty <= 0n)
|
|
573
|
+
continue;
|
|
574
|
+
requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, unit === 'lovelace'
|
|
575
|
+
? cardano_ledger_ts_1.Value.lovelaces(qty)
|
|
576
|
+
: this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
|
|
577
|
+
}
|
|
578
|
+
// Collateral only when a Plutus script runs; Buildooor writes given collaterals into any body.
|
|
579
|
+
const runsScript = scriptEntries.length > 0 || mintEntries.length > 0 ||
|
|
580
|
+
[...withdrawalEntries, ...certEntries].some(e => e.script || e.refLedgerUtxo);
|
|
581
|
+
const { collateralUtxos, fundingUtxos, collateralReturn } = runsScript
|
|
582
|
+
? this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress)
|
|
583
|
+
: { collateralUtxos: [], fundingUtxos: rest, collateralReturn: undefined };
|
|
584
|
+
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
|
|
585
|
+
const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
|
|
586
|
+
const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
|
|
587
|
+
// Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
|
|
588
|
+
const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries, ...mintEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
|
|
589
|
+
const callerRefUtxos = (ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u)));
|
|
590
|
+
const readonlyRefInputs = this._mapReferenceInputs(callerRefUtxos);
|
|
591
|
+
const sortedReferenceInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
|
|
592
|
+
...callerRefUtxos.map(u => ({ txHash: u.txHash.toLowerCase(), outputIndex: u.outputIndex })),
|
|
593
|
+
...[...refScriptKeys].map(k => { const [txHash, idx] = k.split('#'); return { txHash, outputIndex: Number(idx) }; }),
|
|
594
|
+
]);
|
|
595
|
+
// Placeholders resolve against the final input, reference-input and withdrawal order
|
|
596
|
+
const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
|
|
597
|
+
const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
|
|
598
|
+
const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
|
|
599
|
+
const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }, i) => {
|
|
600
|
+
const redeemer = si.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(si.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.redeemer, resolveCtx));
|
|
601
|
+
let datum = "inline";
|
|
602
|
+
if (si.datumCbor) {
|
|
603
|
+
const bytes = Buffer.from(si.datumCbor, 'hex');
|
|
604
|
+
this._checkWitnessDatum(utxo, bytes, `scriptInputs[${i}].datumCbor`, '');
|
|
605
|
+
datum = (0, plutus_data_1.dataFromCbor)(bytes);
|
|
606
|
+
}
|
|
607
|
+
else if (si.datum !== undefined) {
|
|
608
|
+
datum = (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx));
|
|
609
|
+
this._checkWitnessDatum(utxo, (0, plutus_data_1.dataToCbor)(datum), `scriptInputs[${i}].datumJson`, '; pass datumCbor with the bytes the UTxO was locked with');
|
|
610
|
+
}
|
|
611
|
+
const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
|
|
612
|
+
return script
|
|
613
|
+
? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
|
|
614
|
+
: { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
|
|
615
|
+
});
|
|
616
|
+
const outputs = [];
|
|
617
|
+
this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
|
|
618
|
+
...o,
|
|
619
|
+
inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
|
|
620
|
+
})));
|
|
621
|
+
requestedOutputs = outputs.length;
|
|
622
|
+
const mints = mintEntries.length > 0
|
|
623
|
+
? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
|
|
624
|
+
: undefined;
|
|
625
|
+
// Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
|
|
626
|
+
const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
|
|
627
|
+
const withdrawal = { rewardAccount, amount: BigInt(w.lovelace) };
|
|
628
|
+
if (!script && !refLedgerUtxo)
|
|
629
|
+
return { withdrawal };
|
|
630
|
+
const redeemer = w.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(w.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(w.redeemer ?? null, resolveCtx));
|
|
631
|
+
return { withdrawal, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
|
|
632
|
+
});
|
|
633
|
+
// Certificates in the given order; a scripted one carries its redeemer under the Cert purpose
|
|
634
|
+
const certificates = certEntries.map(({ c, cert, script, refLedgerUtxo }) => {
|
|
635
|
+
if (!script && !refLedgerUtxo)
|
|
636
|
+
return { cert };
|
|
637
|
+
const redeemer = c.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(c.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(c.redeemer ?? null, resolveCtx));
|
|
638
|
+
return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
|
|
639
|
+
});
|
|
640
|
+
const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
|
|
641
|
+
const buildParams = {
|
|
642
|
+
inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
|
|
643
|
+
outputs, changeAddress, mints,
|
|
644
|
+
collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
|
|
645
|
+
invalidBefore, invalidAfter,
|
|
646
|
+
...(collateralReturn && { collateralReturn }),
|
|
647
|
+
...(readonlyRefInputs.length > 0 && { readonlyRefInputs }),
|
|
648
|
+
...(withdrawals.length > 0 && { withdrawals }),
|
|
649
|
+
...(certificates.length > 0 && { certificates })
|
|
650
|
+
};
|
|
651
|
+
const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
|
|
652
|
+
const details = this._extractTxDetails(tx);
|
|
653
|
+
const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
|
|
654
|
+
if (details.sizeBytes > maxTxSize) {
|
|
655
|
+
const inline = scriptEntries.filter(e => e.script).length;
|
|
656
|
+
throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
|
|
657
|
+
(inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
|
|
658
|
+
}
|
|
659
|
+
// the first script that runs: a spend, else a mint policy, else a withdrawal or certificate script
|
|
660
|
+
const scriptHashes = [
|
|
661
|
+
...scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash),
|
|
662
|
+
...mintEntries.map(e => e.policyId),
|
|
663
|
+
...[...withdrawalEntries, ...certEntries].flatMap(e => {
|
|
664
|
+
const hash = e.script?.hash ?? e.refLedgerUtxo?.resolved.refScript?.hash;
|
|
665
|
+
return hash ? [hash.toString()] : [];
|
|
666
|
+
}),
|
|
667
|
+
];
|
|
668
|
+
logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
|
|
669
|
+
return this._buildResult(req, ctx, details, {
|
|
670
|
+
scriptHash: scriptHashes[0],
|
|
671
|
+
forcedInputsUsed: forcedInputs.length,
|
|
672
|
+
referenceInputsUsed: readonlyRefInputs.length + refScriptKeys.size
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
catch (err) {
|
|
676
|
+
(0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
/** Appends the outputs in order. A CBOR inline datum keeps its bytes. */
|
|
680
|
+
_appendPlutusOutputs(outputs, list) {
|
|
681
|
+
for (let i = 0; i < list.length; i++) {
|
|
682
|
+
const o = list[i];
|
|
683
|
+
const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
|
|
684
|
+
const refScript = this._parseReferenceScript(o.referenceScript);
|
|
685
|
+
const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : o.inlineDatumCbor ? (0, plutus_data_1.dataFromCbor)(o.inlineDatumCbor) : undefined;
|
|
686
|
+
const txOut = datum
|
|
687
|
+
? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
|
|
688
|
+
: this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
|
|
689
|
+
const minLovelaces = this._minOutputLovelace(txOut);
|
|
690
|
+
if (BigInt(o.lovelaceAmount) < minLovelaces) {
|
|
691
|
+
throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
|
|
692
|
+
}
|
|
693
|
+
outputs.push(txOut);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// `forAnyAmount` sizes the coin field for the largest amount, so the result holds for any amount.
|
|
697
|
+
_minOutputLovelace(txOut, forAnyAmount = false) {
|
|
698
|
+
return forAnyAmount
|
|
699
|
+
? this.txBuilder.minimizeLovelaces(txOut).value.lovelaces
|
|
700
|
+
: this.txBuilder.getMinimumOutputLovelaces(txOut);
|
|
701
|
+
}
|
|
468
702
|
//---------------------------------------------------------------------------
|
|
469
703
|
// Shared Helper Methods
|
|
470
704
|
//---------------------------------------------------------------------------
|
|
@@ -484,6 +718,12 @@ class BuildooorTxBuilder {
|
|
|
484
718
|
address: o.address?.toString?.() ?? "",
|
|
485
719
|
lovelace: o.value?.lovelaces?.toString?.() ?? "0"
|
|
486
720
|
})),
|
|
721
|
+
redeemers: (tx.witnesses.redeemers ?? []).map((r) => ({
|
|
722
|
+
tag: (0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag),
|
|
723
|
+
index: r.index,
|
|
724
|
+
mem: r.execUnits.mem.toString(),
|
|
725
|
+
steps: r.execUnits.cpu.toString(),
|
|
726
|
+
})),
|
|
487
727
|
};
|
|
488
728
|
}
|
|
489
729
|
/** Build the standard TxBuildResult object */
|
|
@@ -507,55 +747,34 @@ class BuildooorTxBuilder {
|
|
|
507
747
|
feeLovelace: txDetails.feeLovelace,
|
|
508
748
|
inputs,
|
|
509
749
|
outputs: txDetails.outputs,
|
|
750
|
+
...(txDetails.redeemers.length > 0 ? { redeemers: txDetails.redeemers } : {}),
|
|
510
751
|
...extra,
|
|
511
752
|
warnings: [],
|
|
512
753
|
};
|
|
513
754
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
* whose fee covers them.
|
|
517
|
-
*
|
|
518
|
-
* Background (verified against the vendored Buildooor source): `initTxBuild` constructs
|
|
519
|
-
* every redeemer with a dummy budget — caller-supplied execution units in the build args
|
|
520
|
-
* are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
|
|
521
|
-
* the budget the local CEK run consumed, even when the script failed (partial budget).
|
|
522
|
-
* So the declared units are whatever the *local* evaluation produced, and any cushion
|
|
523
|
-
* passed into the args silently evaporates. This method makes the declared units real:
|
|
524
|
-
*
|
|
525
|
-
* 1. First pass: build once; redeemers now carry the local CEK budgets.
|
|
526
|
-
* 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
|
|
527
|
-
* budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
|
|
528
|
-
* 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
|
|
529
|
-
* without an Ogmios result aborts — see makeScriptBuildOpts).
|
|
530
|
-
* 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
|
|
531
|
-
* from its own local budgets, so the floor adds the price + encoding-size delta).
|
|
532
|
-
* 5. Stamp the target units into the redeemers and recompute scriptDataHash.
|
|
533
|
-
*/
|
|
755
|
+
// Buildooor stamps local CEK budgets and ignores caller units. So build once, evaluate via Ogmios,
|
|
756
|
+
// rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
|
|
534
757
|
async _buildScriptTx(buildParams, evaluator) {
|
|
535
758
|
const pass1Failures = [];
|
|
536
759
|
const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
|
|
537
760
|
if (!tx1) {
|
|
538
|
-
throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null
|
|
761
|
+
throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null; check inputs, datum, and collateral configuration');
|
|
539
762
|
}
|
|
540
763
|
const rdmrs1 = tx1.witnesses.redeemers ?? [];
|
|
541
764
|
if (rdmrs1.length === 0) {
|
|
542
|
-
// Defensive
|
|
543
|
-
// and Buildooor's calcMinFee already budgets the vkey witnesses to come.
|
|
765
|
+
// Defensive: callers always attach a script; nothing to evaluate or stamp.
|
|
544
766
|
return tx1;
|
|
545
767
|
}
|
|
546
|
-
// The first-pass CBOR
|
|
547
|
-
// (identical args ⇒ identical tx, since passed ExUnits are ignored anyway).
|
|
768
|
+
// The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
|
|
548
769
|
const evaluatedUnits = evaluator
|
|
549
770
|
? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
|
|
550
771
|
: undefined;
|
|
551
772
|
if (!evaluator) {
|
|
552
|
-
logger.debug('No evaluator available
|
|
773
|
+
logger.debug('No evaluator available, falling back to buffered local execution units');
|
|
553
774
|
}
|
|
554
775
|
const targets1 = this._resolveTargetExUnits(rdmrs1, evaluatedUnits, pass1Failures);
|
|
555
|
-
// Fee floor: Buildooor's fee covers
|
|
556
|
-
//
|
|
557
|
-
// delta of the stamped units, their (slightly longer) CBOR encoding, and a small
|
|
558
|
-
// pad for change-output size wobble between the two passes.
|
|
776
|
+
// Fee floor: Buildooor's fee already covers local budgets and future vkey witnesses; add the
|
|
777
|
+
// price delta of the stamped units, their longer CBOR encoding, and a pad for change-size wobble.
|
|
559
778
|
const feeFloor = BigInt(tx1.body.fee.toString())
|
|
560
779
|
+ this._exUnitsPriceDelta(rdmrs1, targets1)
|
|
561
780
|
+ this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
|
|
@@ -566,13 +785,8 @@ class BuildooorTxBuilder {
|
|
|
566
785
|
const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
|
|
567
786
|
return this._stampExecUnits(tx2, targets2);
|
|
568
787
|
}
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
* (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
|
|
572
|
-
* failure, empty result) so callers fall back to buffered local units. A
|
|
573
|
-
* TransactionValidationError or ScriptValidationError from the evaluator is
|
|
574
|
-
* authoritative (the script really failed on the ledger) and is rethrown.
|
|
575
|
-
*/
|
|
788
|
+
// Cushioned Ogmios budgets keyed `tag:index`. Undefined when the evaluation is unusable.
|
|
789
|
+
// Validation errors are rethrown.
|
|
576
790
|
async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
|
|
577
791
|
try {
|
|
578
792
|
const evalResults = await evaluator(evalTxCbor);
|
|
@@ -585,7 +799,7 @@ class BuildooorTxBuilder {
|
|
|
585
799
|
let purpose;
|
|
586
800
|
let index;
|
|
587
801
|
if (typeof v === 'string') {
|
|
588
|
-
//
|
|
802
|
+
// "purpose:index" string form
|
|
589
803
|
const [p, i] = v.split(':');
|
|
590
804
|
purpose = p;
|
|
591
805
|
index = Number(i);
|
|
@@ -605,11 +819,8 @@ class BuildooorTxBuilder {
|
|
|
605
819
|
}
|
|
606
820
|
catch (evalError) {
|
|
607
821
|
if (evalError instanceof errors_1.TransactionValidationError || evalError instanceof errors_1.ScriptValidationError) {
|
|
608
|
-
// Authoritative:
|
|
609
|
-
//
|
|
610
|
-
// ScriptValidationError (PlutusFailure / CekError / budget overspend). Falling
|
|
611
|
-
// back to local buffered units here would hand back a transaction the node has
|
|
612
|
-
// already rejected — so propagate the failure instead.
|
|
822
|
+
// Authoritative: the ledger executed and rejected the script; falling back to local
|
|
823
|
+
// units would hand back a transaction the node has already rejected.
|
|
613
824
|
throw evalError;
|
|
614
825
|
}
|
|
615
826
|
const msg = evalError instanceof Error ? evalError.message : String(evalError);
|
|
@@ -617,25 +828,15 @@ class BuildooorTxBuilder {
|
|
|
617
828
|
return undefined;
|
|
618
829
|
}
|
|
619
830
|
}
|
|
620
|
-
|
|
621
|
-
* Combined cushion: relative multiplier catches proportional drift on large
|
|
622
|
-
* validators, absolute floor catches sub-percent drift on small ones (observed
|
|
623
|
-
* when metadata affects the real tx body vs the evaluator's ScriptContext).
|
|
624
|
-
*/
|
|
831
|
+
// The multiplier covers drift on large validators, the absolute floor covers small ones.
|
|
625
832
|
_applyExUnitBuffer(mem, cpu) {
|
|
626
833
|
return {
|
|
627
834
|
mem: BigInt(Math.ceil(Number(mem) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER),
|
|
628
835
|
cpu: BigInt(Math.ceil(Number(cpu) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER)
|
|
629
836
|
};
|
|
630
837
|
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
* - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
|
|
634
|
-
* - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
|
|
635
|
-
* - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
|
|
636
|
-
* - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
|
|
637
|
-
* collateral of whoever signs and submits the returned CBOR.
|
|
638
|
-
*/
|
|
838
|
+
// Per redeemer: max of local and Ogmios, else buffered local, else Ogmios after a local failure.
|
|
839
|
+
// A local failure without Ogmios aborts, since unreliable units would forfeit the collateral.
|
|
639
840
|
_resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
|
|
640
841
|
return rdmrs.map(r => {
|
|
641
842
|
const local = { mem: BigInt(r.execUnits.mem), cpu: BigInt(r.execUnits.cpu) };
|
|
@@ -645,9 +846,9 @@ class BuildooorTxBuilder {
|
|
|
645
846
|
if (!evaluated) {
|
|
646
847
|
throw new errors_1.TransactionValidationError(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag)}:${r.index}) ` +
|
|
647
848
|
`and no Ogmios evaluation is available to certify its execution units. Refusing to return a ` +
|
|
648
|
-
`transaction with unreliable execution units
|
|
849
|
+
`transaction with unreliable execution units. Signing and submitting it would forfeit the collateral. ` +
|
|
649
850
|
`Configure an Ogmios backend for authoritative script evaluation, or fix the script/datum/redeemer. ` +
|
|
650
|
-
`Script logs: [${failure.logs.join(', ')}]`);
|
|
851
|
+
`Machine error: ${failure.error ?? 'none reported'}. Script logs: [${failure.logs.join(', ')}]`);
|
|
651
852
|
}
|
|
652
853
|
return evaluated;
|
|
653
854
|
}
|
|
@@ -691,17 +892,8 @@ class BuildooorTxBuilder {
|
|
|
691
892
|
_txFeePerByte() {
|
|
692
893
|
return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
|
|
693
894
|
}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
*
|
|
697
|
-
* Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
|
|
698
|
-
* 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
|
|
699
|
-
* builder's named-key cost models, which clamp the chain array to the parameter
|
|
700
|
-
* count the library release knows — wrong whenever the on-chain cost model has
|
|
701
|
-
* grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
|
|
702
|
-
* _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
|
|
703
|
-
* is recomputed here even when the target units already match.
|
|
704
|
-
*/
|
|
895
|
+
// Recomputes scriptDataHash with the raw chain cost-model arrays, even when units match.
|
|
896
|
+
// TxBuilder.overrideTxRedeemers hashes clamped models, which breaks once the chain model grows.
|
|
705
897
|
_stampExecUnits(tx, targets) {
|
|
706
898
|
const rdmrs = tx.witnesses.redeemers ?? [];
|
|
707
899
|
const unchanged = rdmrs.every((r, i) => BigInt(r.execUnits.mem) === targets[i].mem && BigInt(r.execUnits.cpu) === targets[i].cpu);
|
|
@@ -712,8 +904,7 @@ class BuildooorTxBuilder {
|
|
|
712
904
|
execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
|
|
713
905
|
}));
|
|
714
906
|
const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
|
|
715
|
-
const
|
|
716
|
-
const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
|
|
907
|
+
const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, this._languageViews(tx)) });
|
|
717
908
|
const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
|
|
718
909
|
if (!unchanged) {
|
|
719
910
|
logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
|
|
@@ -721,11 +912,22 @@ class BuildooorTxBuilder {
|
|
|
721
912
|
}
|
|
722
913
|
return finalTx;
|
|
723
914
|
}
|
|
724
|
-
/**
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
915
|
+
/** Language views the scriptDataHash covers, from the chain's cost models. */
|
|
916
|
+
_languageViews(tx) {
|
|
917
|
+
return (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
|
|
918
|
+
}
|
|
919
|
+
// The ledger finds a witness datum by the hash of its bytes, so it must match the UTxO's datum hash.
|
|
920
|
+
// Inline-datum UTxOs need no witness datum.
|
|
921
|
+
_checkWitnessDatum(utxo, datum, field, hint) {
|
|
922
|
+
if (!utxo.datumHash || utxo.inlineDatum)
|
|
923
|
+
return;
|
|
924
|
+
const hash = (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(datum));
|
|
925
|
+
if (hash !== utxo.datumHash.toLowerCase()) {
|
|
926
|
+
throw new errors_1.TransactionValidationError(`${field} hashes to ${hash}, but ${utxo.txHash}#${utxo.outputIndex} is locked with datum hash ${utxo.datumHash}${hint}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
// Mirrors Buildooor's initTxBuild, which flags the languages of executed scripts.
|
|
930
|
+
// Scripts are attached inline here, so the witness set carries every executed script.
|
|
729
931
|
_usedLanguageViewOpts(tx) {
|
|
730
932
|
const w = tx.witnesses;
|
|
731
933
|
const opts = {
|
|
@@ -737,56 +939,154 @@ class BuildooorTxBuilder {
|
|
|
737
939
|
opts.mustHaveV3 = true;
|
|
738
940
|
return opts;
|
|
739
941
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
* constructed with clamp the chain array to the parameter count this costmodels-ts
|
|
743
|
-
* release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
|
|
744
|
-
* entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
|
|
745
|
-
* array form through unclamped, so substitute the raw chain arrays where we have
|
|
746
|
-
* them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
|
|
747
|
-
*/
|
|
942
|
+
// Named-key models are clamped to the parameter count the library knows.
|
|
943
|
+
// The ledger hashes every served entry, so the raw chain arrays win where available.
|
|
748
944
|
_languageViewCostModels() {
|
|
749
945
|
const models = this.txBuilder.protocolParamters.costModels;
|
|
750
946
|
if (Object.keys(this.rawCostModelArrays).length === 0)
|
|
751
947
|
return models;
|
|
752
948
|
return { ...models, ...this.rawCostModelArrays };
|
|
753
949
|
}
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
950
|
+
// Builds without the sender's reference-script UTxOs first, since their script bytes raise the fee.
|
|
951
|
+
// When funds are short, builds again with them in the pool.
|
|
952
|
+
async _withRefScriptFallback(utxos, build) {
|
|
953
|
+
try {
|
|
954
|
+
return await build(false);
|
|
955
|
+
}
|
|
956
|
+
catch (err) {
|
|
957
|
+
if (!(err instanceof errors_1.InsufficientFundsError) || !(utxos ?? []).some(hasRefScript))
|
|
958
|
+
throw err;
|
|
959
|
+
logger.info('Funds short without the reference-script UTxOs, building again with them in the coin-selection pool');
|
|
960
|
+
return build(true);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
// Forced inputs must be consumed. Refs absent from utxos are ignored, upstream validates them.
|
|
964
|
+
_partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs, includeRefScriptUtxos = false) {
|
|
965
|
+
const excluded = (u) => !includeRefScriptUtxos && hasRefScript(u);
|
|
966
|
+
const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
|
|
967
|
+
const protectedKeys = new Set((protectInputs ?? []).map(key));
|
|
968
|
+
if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(excluded)) {
|
|
761
969
|
return { forced: [], rest: utxos };
|
|
762
|
-
|
|
970
|
+
}
|
|
971
|
+
const forcedKeys = new Set((forceInputs ?? []).map(key));
|
|
972
|
+
// a UTxO cannot be spent and referenced in one transaction
|
|
973
|
+
const clash = [...forcedKeys].find(k => referenced.has(k));
|
|
974
|
+
if (clash)
|
|
975
|
+
throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input; a UTxO cannot be spent and referenced in one transaction`);
|
|
976
|
+
const protectedClash = [...forcedKeys].find(k => protectedKeys.has(k));
|
|
977
|
+
if (protectedClash)
|
|
978
|
+
throw new errors_1.TransactionValidationError(`forceInputs ${protectedClash} is also in protectInputs`);
|
|
763
979
|
const forced = [];
|
|
764
980
|
const rest = [];
|
|
765
981
|
for (const u of utxos) {
|
|
766
|
-
if (forcedKeys.has(
|
|
982
|
+
if (forcedKeys.has(key(u)))
|
|
767
983
|
forced.push(u);
|
|
768
|
-
|
|
984
|
+
// reference inputs and protected UTxOs stay out of coin selection; UTxOs carrying a reference
|
|
985
|
+
// script too, until the other funds prove short (then their bytes are priced into the fee)
|
|
986
|
+
else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !excluded(u))
|
|
769
987
|
rest.push(u);
|
|
770
988
|
}
|
|
771
989
|
return { forced, rest };
|
|
772
990
|
}
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
991
|
+
// Script of a withdrawal, certificate or mint. Inline scripts are swapped for a reference input
|
|
992
|
+
// with the same hash. No script means a key witness.
|
|
993
|
+
_resolveScriptWitness(w, at, referencedByHash, refUtxoByKey, scriptField = 'stakingScript') {
|
|
994
|
+
if (w.script) {
|
|
995
|
+
const script = this._parsePlutusV3Script(w.script, `${at}.${scriptField}`);
|
|
996
|
+
const referenced = referencedByHash.get(script.hash.toString());
|
|
997
|
+
return referenced ? { refLedgerUtxo: referenced } : { script };
|
|
998
|
+
}
|
|
999
|
+
if (!w.referenceScript)
|
|
1000
|
+
return {};
|
|
1001
|
+
const refKey = `${w.referenceScript.txHash.toLowerCase()}#${w.referenceScript.outputIndex}`;
|
|
1002
|
+
const refUtxo = refUtxoByKey.get(refKey);
|
|
1003
|
+
if (!refUtxo)
|
|
1004
|
+
throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} not found on-chain or already spent`);
|
|
1005
|
+
const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
|
|
1006
|
+
if (!refLedgerUtxo.resolved.refScript) {
|
|
1007
|
+
throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
|
|
1008
|
+
`from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
|
|
1009
|
+
}
|
|
1010
|
+
return { refLedgerUtxo };
|
|
1011
|
+
}
|
|
1012
|
+
// Ledger order of withdrawal credential hashes, used by `__WDRL_IDX__`. Buildooor numbers
|
|
1013
|
+
// withdrawal redeemers by hash alone, so a build where the two orders differ is refused.
|
|
1014
|
+
_ledgerWithdrawalOrder(entries) {
|
|
1015
|
+
const withHash = entries.map(e => ({
|
|
1016
|
+
credentialHash: e.rewardAccount.credentials.toString().toLowerCase(),
|
|
1017
|
+
isScript: e.rewardAccount.type === 'script',
|
|
1018
|
+
scripted: Boolean(e.script || e.refLedgerUtxo),
|
|
1019
|
+
}));
|
|
1020
|
+
const ledger = (0, plutus_placeholders_1.sortWithdrawalsLikeLedger)(withHash).map(e => e.credentialHash);
|
|
1021
|
+
const buildooor = withHash.map(e => e.credentialHash).sort((a, b) => Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')));
|
|
1022
|
+
const misplaced = withHash.find(e => e.scripted && ledger.indexOf(e.credentialHash) !== buildooor.indexOf(e.credentialHash));
|
|
1023
|
+
if (misplaced) {
|
|
1024
|
+
throw new errors_1.TransactionValidationError(`withdrawals: the scripted withdrawal of credential ${misplaced.credentialHash} cannot be indexed correctly, ` +
|
|
1025
|
+
'because a key-credential withdrawal sorts before it by hash; move that key withdrawal into a separate transaction');
|
|
1026
|
+
}
|
|
1027
|
+
return ledger;
|
|
1028
|
+
}
|
|
1029
|
+
// A forced input of another key address needs its owner as required signer, and the outputs
|
|
1030
|
+
// must spend all it brings so nothing lands in the sender's change. Script addresses are refused.
|
|
1031
|
+
_checkForeignForcedInputs(forced, req) {
|
|
1032
|
+
const sender = req.senderAddress.toLowerCase();
|
|
1033
|
+
const foreign = forced.filter(u => u.address.toLowerCase() !== sender);
|
|
1034
|
+
if (foreign.length === 0)
|
|
1035
|
+
return;
|
|
1036
|
+
const signers = new Set((req.requiredSigners ?? []).map(s => s.toLowerCase()));
|
|
1037
|
+
const keyOf = (u) => `${u.txHash}#${u.outputIndex}`;
|
|
1038
|
+
const byAddress = new Map();
|
|
1039
|
+
for (const u of foreign)
|
|
1040
|
+
byAddress.set(u.address, [...(byAddress.get(u.address) ?? []), u]);
|
|
1041
|
+
for (const [address, utxos] of byAddress) {
|
|
1042
|
+
const creds = cardano_ledger_ts_1.Address.fromString(address).paymentCreds;
|
|
1043
|
+
const refs = utxos.map(keyOf).join(', ');
|
|
1044
|
+
if (creds.type !== cardano_ledger_ts_1.CredentialType.KeyHash) {
|
|
1045
|
+
throw new errors_1.TransactionValidationError(`forceInputs ${refs} are at the script address ${address}; spend script UTxOs via scriptInputs`);
|
|
1046
|
+
}
|
|
1047
|
+
const keyHash = creds.hash.toString().toLowerCase();
|
|
1048
|
+
if (!signers.has(keyHash)) {
|
|
1049
|
+
throw new errors_1.TransactionValidationError(`forceInputs ${refs} belong to ${address}; its payment key hash ${keyHash} must be in requiredSigners (the owner co-signs)`);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
const brought = new Map();
|
|
1053
|
+
for (const u of foreign) {
|
|
1054
|
+
for (const a of u.amount) {
|
|
1055
|
+
const unit = a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit;
|
|
1056
|
+
brought.set(unit, (brought.get(unit) ?? 0n) + BigInt(a.quantity));
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
const spent = new Map();
|
|
1060
|
+
for (const o of req.outputs) {
|
|
1061
|
+
spent.set('lovelace', (spent.get('lovelace') ?? 0n) + BigInt(o.lovelaceAmount));
|
|
1062
|
+
for (const a of o.assets ?? [])
|
|
1063
|
+
spent.set(a.unit, (spent.get(a.unit) ?? 0n) + BigInt(a.quantity));
|
|
1064
|
+
}
|
|
1065
|
+
for (const [unit, qty] of brought) {
|
|
1066
|
+
const out = spent.get(unit) ?? 0n;
|
|
1067
|
+
if (qty > out) {
|
|
1068
|
+
throw new errors_1.TransactionValidationError(`forceInputs of other addresses bring ${qty} ${unit} but the outputs spend only ${out}; ` +
|
|
1069
|
+
`the difference would go to the sender's change, return it to its owner in outputs`);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
/** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
|
|
1074
|
+
_referencedKeys(ctx, ...refs) {
|
|
1075
|
+
const keys = new Set();
|
|
1076
|
+
for (const u of ctx.referenceInputUtxos ?? [])
|
|
1077
|
+
keys.add(`${u.txHash.toLowerCase()}#${u.outputIndex}`);
|
|
1078
|
+
for (const list of refs)
|
|
1079
|
+
for (const r of list ?? [])
|
|
1080
|
+
keys.add(`${r.txHash.toLowerCase()}#${r.outputIndex}`);
|
|
1081
|
+
return keys;
|
|
1082
|
+
}
|
|
1083
|
+
/** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
|
|
777
1084
|
_mapReferenceInputs(referenceInputUtxos) {
|
|
778
1085
|
if (!referenceInputUtxos || referenceInputUtxos.length === 0)
|
|
779
1086
|
return [];
|
|
780
1087
|
return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
|
|
781
1088
|
}
|
|
782
|
-
|
|
783
|
-
* Funding requirement contributed by extra outputs on a mint build:
|
|
784
|
-
* the summed lovelace of all entries plus, per asset unit, the demand the
|
|
785
|
-
* transaction's own positive mints do NOT cover. Minted quantities are
|
|
786
|
-
* aggregated per unit and subtracted from the aggregated output demand;
|
|
787
|
-
* only a positive remainder is requested from the wallet (a fully covered
|
|
788
|
-
* unit is not requested at all — it does not exist before this tx).
|
|
789
|
-
*/
|
|
1089
|
+
// Extra outputs need their lovelace plus any asset amount the mints themselves do not cover.
|
|
790
1090
|
_extraOutputsFundingAfterMint(mintActions, extraOutputs) {
|
|
791
1091
|
const mintedByUnit = new Map();
|
|
792
1092
|
for (const action of mintActions) {
|
|
@@ -813,97 +1113,89 @@ class BuildooorTxBuilder {
|
|
|
813
1113
|
}
|
|
814
1114
|
return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
|
|
815
1115
|
}
|
|
816
|
-
/**
|
|
817
|
-
* The script an individual mint action executes under: its own
|
|
818
|
-
* per-action policy when set (multi-policy mint FR), else the request's
|
|
819
|
-
* top-level policy script.
|
|
820
|
-
*/
|
|
1116
|
+
/** Per-action policy script when set, else the request's policy script. */
|
|
821
1117
|
_mintActionScript(action, defaultScript, index) {
|
|
822
1118
|
if (!action.mintingPolicyScript)
|
|
823
1119
|
return defaultScript;
|
|
824
1120
|
return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
|
|
825
1121
|
}
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
* they are stamped into the redeemers post-build by _buildScriptTx).
|
|
830
|
-
*
|
|
831
|
-
* Multi-policy mint FR: each action may carry its own policy script and
|
|
832
|
-
* redeemer; absent fields fall back to the request-level ones. The ledger
|
|
833
|
-
* carries ONE redeemer per policy, so actions resolving to the same policy
|
|
834
|
-
* must agree on their redeemer, checked here.
|
|
835
|
-
*/
|
|
836
|
-
_buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
|
|
1122
|
+
// Mint entries for all mint flows. An action may carry its own redeemer, but the ledger holds
|
|
1123
|
+
// one redeemer per policy, so actions on the same policy must agree.
|
|
1124
|
+
_buildMintEntries(mintActions, scriptFor, resolvedMintRedeemer, resolveCtx) {
|
|
837
1125
|
const redeemerByPolicy = new Map();
|
|
838
1126
|
return mintActions.map((action, index) => {
|
|
839
|
-
const
|
|
1127
|
+
const source = scriptFor(action, index);
|
|
1128
|
+
const policyHash = 'inline' in source ? source.inline.hash : source.ref.resolved.refScript.hash;
|
|
840
1129
|
const actionRedeemer = action.redeemerJson !== undefined
|
|
841
1130
|
? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
|
|
842
1131
|
: resolvedMintRedeemer;
|
|
843
1132
|
const redeemerData = actionRedeemer !== undefined
|
|
844
1133
|
? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
|
|
845
1134
|
: new plutus_data_1.DataI(action.redeemer ?? 0);
|
|
846
|
-
const policyId =
|
|
1135
|
+
const policyId = policyHash.toString();
|
|
847
1136
|
// Canonical comparison over the encoded PlutusData: JSON key order must
|
|
848
1137
|
// not matter, and a JSON {int:0} equals the DataI(0) fallback.
|
|
849
1138
|
const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
|
|
850
1139
|
const seen = redeemerByPolicy.get(policyId);
|
|
851
1140
|
if (seen !== undefined && seen !== redeemerFingerprint) {
|
|
852
|
-
throw new Error(`mint actions under policy ${policyId} carry different redeemers
|
|
1141
|
+
throw new Error(`mint actions under policy ${policyId} carry different redeemers; the ledger allows one redeemer per policy; ` +
|
|
853
1142
|
'split them into separate transactions or align the redeemers');
|
|
854
1143
|
}
|
|
855
1144
|
redeemerByPolicy.set(policyId, redeemerFingerprint);
|
|
856
1145
|
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
|
|
857
1146
|
return {
|
|
858
|
-
value: cardano_ledger_ts_1.Value.singleAsset(
|
|
859
|
-
script: {
|
|
860
|
-
inline: script,
|
|
861
|
-
redeemer: redeemerData
|
|
862
|
-
}
|
|
1147
|
+
value: cardano_ledger_ts_1.Value.singleAsset(policyHash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
|
|
1148
|
+
script: { ...source, redeemer: redeemerData }
|
|
863
1149
|
};
|
|
864
1150
|
});
|
|
865
1151
|
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
* the funding pool, and without this the reservation is invisible ("but the
|
|
870
|
-
* address HAS enough ADA").
|
|
871
|
-
*/
|
|
872
|
-
_collateralPartitionContext(collateralUtxos, fundingUtxos) {
|
|
873
|
-
const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
|
|
1152
|
+
// The builder's insufficient-funds message counts only the funding pool.
|
|
1153
|
+
// This context makes the collateral reservation visible.
|
|
1154
|
+
_collateralPartitionContext(collateralUtxos, fundingUtxos, forced = []) {
|
|
874
1155
|
const fundingLovelace = fundingUtxos.reduce((s, u) => s + (0, tx_build_helper_1.getLovelace)(u), 0n);
|
|
875
|
-
|
|
876
|
-
|
|
1156
|
+
if (collateralUtxos.length === 0) {
|
|
1157
|
+
return `no script runs, so no collateral; ${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
|
|
1158
|
+
}
|
|
1159
|
+
const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
|
|
1160
|
+
const collateralKeys = new Set(collateralUtxos.map(u => `${u.utxoRef.id.toString()}#${u.utxoRef.index}`));
|
|
1161
|
+
const isCollateral = (u) => collateralKeys.has(`${u.txHash}#${u.outputIndex}`);
|
|
1162
|
+
const alsoFunding = fundingUtxos.some(isCollateral);
|
|
1163
|
+
const alsoForced = forced.some(isCollateral);
|
|
1164
|
+
return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral` +
|
|
1165
|
+
`${alsoFunding ? ' and also offered as funding' : alsoForced ? ' and also spent as a forced input' : ''}; ` +
|
|
1166
|
+
`${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
|
|
877
1167
|
}
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
* COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
|
|
884
|
-
* The previous "first ADA-only" pick failed both ways: a dust UTxO below
|
|
885
|
-
* collateralPercentage × fee is rejected at submit, and a large UTxO is
|
|
886
|
-
* fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
|
|
887
|
-
* for ADA-only collateral). Everything above the floor is therefore handed
|
|
888
|
-
* back via an explicit collateralReturn when the excess satisfies min-ADA.
|
|
889
|
-
*/
|
|
890
|
-
_setupCollateral(utxos) {
|
|
891
|
-
const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
|
|
892
|
-
if (adaOnly.length === 0) {
|
|
893
|
-
throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
|
|
894
|
-
}
|
|
895
|
-
const sorted = [...adaOnly].sort((a, b) => {
|
|
1168
|
+
// Smallest ADA-only UTxO covering COLLATERAL_LOVELACE, else a forced sender input. Buildooor sets no
|
|
1169
|
+
// collateralReturn for it, so the excess is returned here. When funds are short the collateral
|
|
1170
|
+
// UTxO also funds the transaction, which the ledger allows.
|
|
1171
|
+
_setupCollateral(utxos, requiredLovelace, forced = [], senderAddress = '') {
|
|
1172
|
+
const byLovelace = (a, b) => {
|
|
896
1173
|
const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
|
|
897
1174
|
return diff < 0n ? -1 : diff > 0n ? 1 : 0;
|
|
898
|
-
}
|
|
1175
|
+
};
|
|
1176
|
+
const coversFloor = (u) => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE;
|
|
1177
|
+
// ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
|
|
1178
|
+
const sorted = utxos.filter(tx_build_helper_1.isCollateralCandidate).sort(byLovelace);
|
|
1179
|
+
const sender = senderAddress.toLowerCase();
|
|
1180
|
+
const forcedChoice = sorted.some(coversFloor)
|
|
1181
|
+
? undefined
|
|
1182
|
+
: forced.filter(u => u.address.toLowerCase() === sender && (0, tx_build_helper_1.isCollateralCandidate)(u) && coversFloor(u)).sort(byLovelace)[0];
|
|
1183
|
+
if (sorted.length === 0 && !forcedChoice) {
|
|
1184
|
+
throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral; create one with SetCollateral.');
|
|
1185
|
+
}
|
|
899
1186
|
// smallest sufficient; if none reaches the floor, the largest available is the best bet
|
|
900
|
-
const chosen = sorted.find(
|
|
1187
|
+
const chosen = forcedChoice ?? sorted.find(coversFloor) ?? sorted[sorted.length - 1];
|
|
901
1188
|
if ((0, tx_build_helper_1.getLovelace)(chosen) < const_1.COLLATERAL_LOVELACE) {
|
|
902
1189
|
logger.warn(`Largest ADA-only UTxO (${(0, tx_build_helper_1.getLovelace)(chosen)} lovelace) is below the ${const_1.COLLATERAL_LOVELACE} lovelace ` +
|
|
903
|
-
`collateral floor
|
|
1190
|
+
`collateral floor; the node will reject the transaction if collateralPercentage × fee exceeds it`);
|
|
904
1191
|
}
|
|
905
1192
|
const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(chosen)];
|
|
906
|
-
const
|
|
1193
|
+
const rest = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
|
|
1194
|
+
const restLovelace = rest.reduce((sum, u) => sum + (0, tx_build_helper_1.getLovelace)(u), 0n);
|
|
1195
|
+
// a forced input is already spent, so it is never offered to coin selection as well
|
|
1196
|
+
const fundingUtxos = forcedChoice || restLovelace >= requiredLovelace + const_1.FEE_BUFFER_LOVELACE + BigInt(const_1.MIN_CHANGE_LOVELACE)
|
|
1197
|
+
? rest
|
|
1198
|
+
: [...rest, chosen];
|
|
907
1199
|
// Cap the at-risk amount at the floor: return the excess to the owner.
|
|
908
1200
|
let collateralReturn;
|
|
909
1201
|
const excess = (0, tx_build_helper_1.getLovelace)(chosen) - const_1.COLLATERAL_LOVELACE;
|
|
@@ -913,8 +1205,7 @@ class BuildooorTxBuilder {
|
|
|
913
1205
|
if (excess >= minAda) {
|
|
914
1206
|
collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
|
|
915
1207
|
}
|
|
916
|
-
// excess below min-ADA: no return output possible
|
|
917
|
-
// but by selection it is the smallest sufficient one.
|
|
1208
|
+
// excess below min-ADA: no return output possible, the whole UTxO stays at risk
|
|
918
1209
|
}
|
|
919
1210
|
return { collateralUtxos, fundingUtxos, collateralReturn };
|
|
920
1211
|
}
|
|
@@ -944,14 +1235,8 @@ class BuildooorTxBuilder {
|
|
|
944
1235
|
}
|
|
945
1236
|
return new cardano_ledger_ts_1.TxOut(params);
|
|
946
1237
|
}
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
* code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
|
|
950
|
-
* would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
|
|
951
|
-
* wrong policy IDs and unspendable script addresses with no error anywhere
|
|
952
|
-
* down the line. The UPLC version is the first three flat-encoded naturals
|
|
953
|
-
* of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
|
|
954
|
-
*/
|
|
1238
|
+
// Rejects UPLC 1.0.0 code. Script.fromCbor assumes V3 and would give a wrong script hash.
|
|
1239
|
+
// The UPLC version is the first three flat naturals of the unwrapped script.
|
|
955
1240
|
_parsePlutusV3Script(hex, field) {
|
|
956
1241
|
let script;
|
|
957
1242
|
try {
|
|
@@ -963,7 +1248,7 @@ class BuildooorTxBuilder {
|
|
|
963
1248
|
}
|
|
964
1249
|
const b = script.bytes;
|
|
965
1250
|
if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
|
|
966
|
-
throw new errors_1.TransactionValidationError(`${field} contains UPLC 1.0.0 code (PlutusV1/V2)
|
|
1251
|
+
throw new errors_1.TransactionValidationError(`${field} contains UPLC 1.0.0 code (PlutusV1/V2). ODATANO builds Plutus V3 transactions only. ` +
|
|
967
1252
|
`Hashing it as V3 would yield a different script hash (wrong policy ID / unspendable address).`);
|
|
968
1253
|
}
|
|
969
1254
|
return script;
|
|
@@ -972,27 +1257,27 @@ class BuildooorTxBuilder {
|
|
|
972
1257
|
_parseReferenceScript(hex) {
|
|
973
1258
|
if (!hex)
|
|
974
1259
|
return undefined;
|
|
975
|
-
return this._parsePlutusV3Script(hex, 'referenceScript');
|
|
1260
|
+
return ledgerScript(this._parsePlutusV3Script(hex, 'referenceScript'));
|
|
976
1261
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
* UTxO.scriptRef is overloaded across backends: Blockfrost/Ogmios set it to a 28-byte
|
|
980
|
-
* hash (56 hex chars), Koios sets it to the full CBOR script bytes. Only full bytes
|
|
981
|
-
* are usable here — hash-only entries are preserved only on-chain, not in local eval.
|
|
982
|
-
*/
|
|
1262
|
+
// Uses `scriptRefCbor`, else a full-CBOR `scriptRef`. With hash and size only, a placeholder
|
|
1263
|
+
// of that size stands in so the fee counts its bytes.
|
|
983
1264
|
_buildInputRefScript(utxo) {
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1265
|
+
const cbor = utxo.scriptRefCbor ?? (utxo.scriptRef && utxo.scriptRef.length > 56 ? utxo.scriptRef : undefined);
|
|
1266
|
+
if (!cbor) {
|
|
1267
|
+
if (utxo.scriptRef && utxo.scriptRefSize) {
|
|
1268
|
+
logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash and size only; fee counts ${utxo.scriptRefSize} bytes, local Plutus eval will not see the script`);
|
|
1269
|
+
return (0, reference_script_1.sizePlaceholderScript)(utxo.scriptRefSize);
|
|
1270
|
+
}
|
|
1271
|
+
if (utxo.scriptRef)
|
|
1272
|
+
logger.warn(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only; its reference-script fee cannot be counted, the node may reject the transaction as underpaid`);
|
|
988
1273
|
return undefined;
|
|
989
1274
|
}
|
|
990
1275
|
try {
|
|
991
|
-
const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(
|
|
992
|
-
//
|
|
1276
|
+
const script = ledgerScript(cardano_ledger_ts_1.Script.fromCbor(Buffer.from(cbor, 'hex')));
|
|
1277
|
+
// Chain data, not consumer input, so warn instead of rejecting.
|
|
993
1278
|
const b = script.bytes;
|
|
994
1279
|
if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
|
|
995
|
-
logger.warn(`Input refScript on ${utxo.txHash}#${utxo.outputIndex} is UPLC 1.0.0 (PlutusV1/V2)
|
|
1280
|
+
logger.warn(`Input refScript on ${utxo.txHash}#${utxo.outputIndex} is UPLC 1.0.0 (PlutusV1/V2), treated as V3, local eval may misbehave`);
|
|
996
1281
|
}
|
|
997
1282
|
return script;
|
|
998
1283
|
}
|
|
@@ -1002,15 +1287,10 @@ class BuildooorTxBuilder {
|
|
|
1002
1287
|
return undefined;
|
|
1003
1288
|
}
|
|
1004
1289
|
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
* same indices Buildooor will assign during build(). Order: script-input first by convention,
|
|
1008
|
-
* then forced + funding sorted lexicographically on (txHash, outputIndex).
|
|
1009
|
-
* Buildooor sorts ALL inputs together; we mirror that exact behaviour via sortInputsLikeBuildooor.
|
|
1010
|
-
*/
|
|
1011
|
-
_computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
|
|
1290
|
+
// Buildooor sorts all inputs by txHash and outputIndex. __INPUT_IDX__ resolves against that order.
|
|
1291
|
+
_computeSortedInputs(scriptUtxoRefs, forcedUtxos, fundingRefs) {
|
|
1012
1292
|
const all = [
|
|
1013
|
-
{ txHash:
|
|
1293
|
+
...scriptUtxoRefs.map(r => ({ txHash: r.txHash, outputIndex: r.outputIndex })),
|
|
1014
1294
|
...forcedUtxos.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
|
|
1015
1295
|
...fundingRefs
|
|
1016
1296
|
];
|
|
@@ -1023,10 +1303,7 @@ class BuildooorTxBuilder {
|
|
|
1023
1303
|
outputIndex: i.utxo.utxoRef.index
|
|
1024
1304
|
}));
|
|
1025
1305
|
}
|
|
1026
|
-
/**
|
|
1027
|
-
* Resolve __INPUT_IDX__ placeholders (FR-3) inside each extraOutput.inlineDatum.
|
|
1028
|
-
* Returns a new array with resolved datums; non-datum fields pass through unchanged.
|
|
1029
|
-
*/
|
|
1306
|
+
/** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
|
|
1030
1307
|
_resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
|
|
1031
1308
|
if (!extraOutputs || extraOutputs.length === 0)
|
|
1032
1309
|
return extraOutputs;
|
|
@@ -1037,11 +1314,7 @@ class BuildooorTxBuilder {
|
|
|
1037
1314
|
: undefined
|
|
1038
1315
|
}));
|
|
1039
1316
|
}
|
|
1040
|
-
/**
|
|
1041
|
-
* Append parsed extraOutputs (FR-2) to the outputs array, enforcing min-ADA per entry.
|
|
1042
|
-
* Throws TransactionValidationError with the required min-ADA in the message so consumers
|
|
1043
|
-
* can adjust without having to inspect Buildooor internals.
|
|
1044
|
-
*/
|
|
1317
|
+
/** Appends extra outputs. A rejection names the required min-ADA. */
|
|
1045
1318
|
_appendExtraOutputs(outputs, extraOutputs) {
|
|
1046
1319
|
if (!extraOutputs || extraOutputs.length === 0)
|
|
1047
1320
|
return;
|
|
@@ -1060,12 +1333,8 @@ class BuildooorTxBuilder {
|
|
|
1060
1333
|
//---------------------------------------------------------------------------
|
|
1061
1334
|
// UTxO Mapping & Configuration Helpers
|
|
1062
1335
|
//---------------------------------------------------------------------------
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
* Falls back to `now - 2 min` / `now + 1 h` when the request omits bounds.
|
|
1066
|
-
* Script-validated builds must call this; plain transfers pass their own
|
|
1067
|
-
* explicit bounds through (no defaulting) so replay behavior is opt-in.
|
|
1068
|
-
*/
|
|
1336
|
+
// Script builds default to two minutes ago until one hour ahead.
|
|
1337
|
+
// Plain transfers pass only explicit bounds through.
|
|
1069
1338
|
_resolveValiditySlots(req, mode) {
|
|
1070
1339
|
const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
|
|
1071
1340
|
const hasEnd = req.validityEndMs !== undefined && req.validityEndMs !== null && req.validityEndMs !== '';
|
|
@@ -1087,21 +1356,16 @@ class BuildooorTxBuilder {
|
|
|
1087
1356
|
invalidAfter: BigInt(endSlot),
|
|
1088
1357
|
};
|
|
1089
1358
|
}
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
*
|
|
1093
|
-
* Every field is null-guarded: a missing/null source value keeps the library
|
|
1094
|
-
* default instead of degrading to 0 (`Number(null) === 0` previously set
|
|
1095
|
-
* utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
|
|
1096
|
-
* execution-unit prices are mapped because they feed the scriptDataHash
|
|
1097
|
-
* (language views) and the fee/ExUnits math — stale defaults there cause
|
|
1098
|
-
* PPViewHashesDontMatch or fee underestimation on-chain.
|
|
1099
|
-
*/
|
|
1359
|
+
// A missing value keeps the library default instead of 0. For example, utxoCostPerByte = 0
|
|
1360
|
+
// would disable min-ADA.
|
|
1100
1361
|
_mapLedgerParametersToBuildooorParams(protocolParameters) {
|
|
1101
1362
|
const pp = protocolParameters;
|
|
1102
1363
|
const d = cardano_ledger_ts_1.defaultProtocolParameters;
|
|
1364
|
+
const major = toUInt(pp.protocolMajorVer);
|
|
1103
1365
|
const mapped = {
|
|
1104
1366
|
...d,
|
|
1367
|
+
// Buildooor prices builtins by protocol version. Without one it takes the latest it knows.
|
|
1368
|
+
protocolVersion: major ? { major, minor: toUInt(pp.protocolMinorVer) ?? 0 } : undefined,
|
|
1105
1369
|
txFeePerByte: toUInt(pp.minFeeA) ?? d.txFeePerByte,
|
|
1106
1370
|
txFeeFixed: toUInt(pp.minFeeB) ?? d.txFeeFixed,
|
|
1107
1371
|
utxoCostPerByte: toUInt(pp.coinsPerUtxoSize) ?? d.utxoCostPerByte,
|
|
@@ -1116,6 +1380,9 @@ class BuildooorTxBuilder {
|
|
|
1116
1380
|
stakePoolTargetNum: toUInt(pp.nOpt) ?? d.stakePoolTargetNum,
|
|
1117
1381
|
collateralPercentage: toUInt(pp.collateralPercent) ?? d.collateralPercentage,
|
|
1118
1382
|
maxCollateralInputs: toUInt(pp.maxCollateralInputs) ?? d.maxCollateralInputs,
|
|
1383
|
+
minfeeRefScriptCostPerByte: pp.minFeeRefScriptCostPerByte != null && Number(pp.minFeeRefScriptCostPerByte) > 0
|
|
1384
|
+
? Number(pp.minFeeRefScriptCostPerByte)
|
|
1385
|
+
: d.minfeeRefScriptCostPerByte,
|
|
1119
1386
|
};
|
|
1120
1387
|
const maxTxExMem = toUInt(pp.maxTxExMem);
|
|
1121
1388
|
const maxTxExSteps = toUInt(pp.maxTxExSteps);
|
|
@@ -1137,22 +1404,13 @@ class BuildooorTxBuilder {
|
|
|
1137
1404
|
mapped.costModels = costModels;
|
|
1138
1405
|
}
|
|
1139
1406
|
else {
|
|
1140
|
-
logger.warn('Protocol parameters carry no usable cost models
|
|
1407
|
+
logger.warn('Protocol parameters carry no usable cost models; keeping library defaults. ' +
|
|
1141
1408
|
'scriptDataHash of script transactions may not match the ledger (PPViewHashesDontMatch risk).');
|
|
1142
1409
|
}
|
|
1143
1410
|
return mapped;
|
|
1144
1411
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
* 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
|
|
1148
|
-
* CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
|
|
1149
|
-
* usable is found, so the caller can keep defaults and warn.
|
|
1150
|
-
*
|
|
1151
|
-
* Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
|
|
1152
|
-
* for the versions mapped here — the named-key conversion drops every entry past
|
|
1153
|
-
* the parameter count this costmodels-ts release knows, and the scriptDataHash
|
|
1154
|
-
* must cover all of them (see _languageViewCostModels).
|
|
1155
|
-
*/
|
|
1412
|
+
// Accepts the keys 'PlutusVN', 'plutus:vN' and 'PlutusScriptVN'. Also resets rawCostModelArrays,
|
|
1413
|
+
// since the scriptDataHash must cover the unclamped chain arrays.
|
|
1156
1414
|
_mapCostModels(costModelsJson) {
|
|
1157
1415
|
this.rawCostModelArrays = {};
|
|
1158
1416
|
if (!costModelsJson)
|
|
@@ -1172,7 +1430,7 @@ class BuildooorTxBuilder {
|
|
|
1172
1430
|
PlutusV2: 'PlutusScriptV2', 'plutus:v2': 'PlutusScriptV2', PlutusScriptV2: 'PlutusScriptV2',
|
|
1173
1431
|
PlutusV3: 'PlutusScriptV3', 'plutus:v3': 'PlutusScriptV3', PlutusScriptV3: 'PlutusScriptV3',
|
|
1174
1432
|
};
|
|
1175
|
-
// Buildooor's CEK
|
|
1433
|
+
// Buildooor's CEK machine rejects array-form cost models, so convert them to named-key objects.
|
|
1176
1434
|
const result = {};
|
|
1177
1435
|
const rawArrays = {};
|
|
1178
1436
|
for (const [key, value] of Object.entries(raw)) {
|
|
@@ -1193,22 +1451,20 @@ class BuildooorTxBuilder {
|
|
|
1193
1451
|
rawArrays[target] = arr;
|
|
1194
1452
|
}
|
|
1195
1453
|
catch {
|
|
1196
|
-
logger.warn(`Cost-model array for ${key} has unexpected length (${value.length})
|
|
1454
|
+
logger.warn(`Cost-model array for ${key} has unexpected length (${value.length}), skipping`);
|
|
1197
1455
|
}
|
|
1198
1456
|
}
|
|
1199
1457
|
if (Object.keys(result).length === 0)
|
|
1200
1458
|
return undefined;
|
|
1201
1459
|
if (!(0, buildooor_1.isCostModels)(result)) {
|
|
1202
|
-
// Buildooor would silently substitute default cost models
|
|
1203
|
-
logger.warn('Mapped cost models failed Buildooor validation
|
|
1460
|
+
// Buildooor would silently substitute default cost models, so surface it instead.
|
|
1461
|
+
logger.warn('Mapped cost models failed Buildooor validation, keeping library defaults');
|
|
1204
1462
|
return undefined;
|
|
1205
1463
|
}
|
|
1206
1464
|
this.rawCostModelArrays = rawArrays;
|
|
1207
1465
|
return result;
|
|
1208
1466
|
}
|
|
1209
|
-
/**
|
|
1210
|
-
* Map ODATANO UTxO to Ledger UTxO (ADA-only)
|
|
1211
|
-
*/
|
|
1467
|
+
/** Map an ADA-only UTxO to a Ledger UTxO. */
|
|
1212
1468
|
_mapOdatanoUtxoToLedgerUtxo(utxos) {
|
|
1213
1469
|
(0, tx_build_helper_1.assertAdaOnly)(utxos);
|
|
1214
1470
|
return new cardano_ledger_ts_1.UTxO({
|
|
@@ -1221,15 +1477,11 @@ class BuildooorTxBuilder {
|
|
|
1221
1477
|
})
|
|
1222
1478
|
});
|
|
1223
1479
|
}
|
|
1224
|
-
/**
|
|
1225
|
-
* Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
|
|
1226
|
-
*/
|
|
1480
|
+
/** Map a UTxO (with multi-assets) to a Ledger UTxO. */
|
|
1227
1481
|
_mapMultiAssetUtxoToLedgerUtxo(utxo) {
|
|
1228
1482
|
const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
|
|
1229
|
-
// Inline datum wins; otherwise carry the datum HASH
|
|
1230
|
-
//
|
|
1231
|
-
// spent output is marked with its Hash32 (pushWitDatum). Dropping the hash here
|
|
1232
|
-
// silently discards the preimage → MissingRequiredDatums on submit.
|
|
1483
|
+
// Inline datum wins; otherwise carry the datum HASH: Buildooor only puts a provided datum
|
|
1484
|
+
// preimage into the witness set when the spent output is marked with its Hash32.
|
|
1233
1485
|
const datumValue = utxo.inlineDatum
|
|
1234
1486
|
? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
|
|
1235
1487
|
: utxo.datumHash
|
|
@@ -1245,9 +1497,7 @@ class BuildooorTxBuilder {
|
|
|
1245
1497
|
})
|
|
1246
1498
|
});
|
|
1247
1499
|
}
|
|
1248
|
-
/**
|
|
1249
|
-
* Map ODATANO metadata JSON to Ledger TxMetadata
|
|
1250
|
-
*/
|
|
1500
|
+
/** Map metadata JSON (label -> value) to Ledger TxMetadata. */
|
|
1251
1501
|
_mapOdatanoMetadataToLedgerMetadata(metadataJson) {
|
|
1252
1502
|
if (!metadataJson) {
|
|
1253
1503
|
return new TxMetadata_1.TxMetadata({});
|
|
@@ -1255,32 +1505,18 @@ class BuildooorTxBuilder {
|
|
|
1255
1505
|
const metadata = {};
|
|
1256
1506
|
for (const [label, value] of Object.entries(metadataJson)) {
|
|
1257
1507
|
if (!/^\d+$/.test(label)) {
|
|
1258
|
-
throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}"
|
|
1508
|
+
throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}": labels must be non-negative integers`);
|
|
1259
1509
|
}
|
|
1260
1510
|
metadata[Number(label)] = this._jsonToTxMetadatum(value, label);
|
|
1261
1511
|
}
|
|
1262
1512
|
return new TxMetadata_1.TxMetadata(metadata);
|
|
1263
1513
|
}
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
*
|
|
1267
|
-
* Ledger rules enforced here (instead of a node-side rejection or a raw 500):
|
|
1268
|
-
* - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
|
|
1269
|
-
* - text and byte values are limited to 64 BYTES per metadatum — longer values
|
|
1270
|
-
* are chunked into a list of ≤64-byte pieces (the established convention,
|
|
1271
|
-
* e.g. CIP-25 long strings)
|
|
1272
|
-
* - strings prefixed with "0x" (even hex length) become byte metadata
|
|
1273
|
-
* - map keys are not auto-chunked (readers match on the literal key) — over-long
|
|
1274
|
-
* keys are rejected with a clear 400
|
|
1275
|
-
*
|
|
1276
|
-
* @param path position of `value` inside the metadata JSON (label-rooted, e.g.
|
|
1277
|
-
* "1155.result" or "721.files[0].src") — named in every rejection
|
|
1278
|
-
* so the consumer can locate the offending value.
|
|
1279
|
-
*/
|
|
1514
|
+
// Ledger rules: integers only, text over 64 bytes is chunked into a list, "0x" strings become bytes.
|
|
1515
|
+
// `path` is the position of `value`, for example "721.files[0].src", named in every rejection.
|
|
1280
1516
|
_jsonToTxMetadatum(value, path) {
|
|
1281
1517
|
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
1282
1518
|
if (typeof value === 'number' && !Number.isInteger(value)) {
|
|
1283
|
-
throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value} at ${path})
|
|
1519
|
+
throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value} at ${path}); encode decimals as strings`);
|
|
1284
1520
|
}
|
|
1285
1521
|
return new TxMetadatum_1.TxMetadatumInt(BigInt(value));
|
|
1286
1522
|
}
|
|
@@ -1317,7 +1553,7 @@ class BuildooorTxBuilder {
|
|
|
1317
1553
|
return new TxMetadatum_1.TxMetadatumMap(map);
|
|
1318
1554
|
}
|
|
1319
1555
|
throw new errors_1.TransactionValidationError(`Unsupported metadata value type: ${value === null ? 'null' : typeof value} at ${path}` +
|
|
1320
|
-
(typeof value === 'boolean' ? '
|
|
1556
|
+
(typeof value === 'boolean' ? '; on-chain metadata has no boolean, encode as string or 0/1' : ''));
|
|
1321
1557
|
}
|
|
1322
1558
|
}
|
|
1323
1559
|
exports.BuildooorTxBuilder = BuildooorTxBuilder;
|