@odatano/core 2.0.0-rc.26 → 2.0.0-rc.27

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.
@@ -413,11 +413,11 @@ export class UTxOAssets extends Array<UTxOAsset> {
413
413
 
414
414
  export declare const BuildSimpleAdaTransaction: {
415
415
  // positional
416
- (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, assetsJson: string | null, forceInputsJson: string | null, validatorScript: string | null, scriptParamsJson: string | null, lockOnScript: boolean | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
416
+ (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, assetsJson: string | null, forceInputsJson: string | null, protectInputsJson: string | null, validatorScript: string | null, scriptParamsJson: string | null, lockOnScript: boolean | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
417
417
  // named
418
- ({senderAddress, recipientAddress, lovelaceAmount, changeAddress, outputDatumJson, assetsJson, forceInputsJson, validatorScript, scriptParamsJson, lockOnScript, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
418
+ ({senderAddress, recipientAddress, lovelaceAmount, changeAddress, outputDatumJson, assetsJson, forceInputsJson, protectInputsJson, validatorScript, scriptParamsJson, lockOnScript, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
419
419
  // metadata (do not use)
420
- __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
420
+ __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
421
421
  kind: 'action'
422
422
  }
423
423
 
@@ -443,11 +443,11 @@ export declare const BuildMultiAssetTransaction: {
443
443
 
444
444
  export declare const BuildMintTransaction: {
445
445
  // positional
446
- (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, mintActionsJson: string | null, mintingPolicyScript: string | null, changeAddress: _.Bech32 | null, requiredSignersJson: string | null, scriptParamsJson: string | null, inlineDatumJson: string | null, mintRedeemerJson: string | null, lockOnScript: boolean | null, forceInputsJson: string | null, referenceInputsJson: string | null, extraOutputsJson: string | null, metadataJson: string | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
446
+ (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, mintActionsJson: string | null, mintingPolicyScript: string | null, changeAddress: _.Bech32 | null, requiredSignersJson: string | null, scriptParamsJson: string | null, inlineDatumJson: string | null, mintRedeemerJson: string | null, lockOnScript: boolean | null, forceInputsJson: string | null, protectInputsJson: string | null, referenceInputsJson: string | null, extraOutputsJson: string | null, metadataJson: string | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
447
447
  // named
448
- ({senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, changeAddress, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, extraOutputsJson, metadataJson, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, mintRedeemerJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, referenceInputsJson?: string | null, extraOutputsJson?: string | null, metadataJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
448
+ ({senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, changeAddress, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, protectInputsJson, referenceInputsJson, extraOutputsJson, metadataJson, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, mintRedeemerJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, protectInputsJson?: string | null, referenceInputsJson?: string | null, extraOutputsJson?: string | null, metadataJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
449
449
  // metadata (do not use)
450
- __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, mintRedeemerJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, referenceInputsJson?: string | null, extraOutputsJson?: string | null, metadataJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
450
+ __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, mintRedeemerJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, protectInputsJson?: string | null, referenceInputsJson?: string | null, extraOutputsJson?: string | null, metadataJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
451
451
  kind: 'action'
452
452
  }
453
453
 
@@ -483,21 +483,21 @@ export declare const SubmitSignedTransaction: {
483
483
 
484
484
  export declare const BuildPlutusSpendTransaction: {
485
485
  // positional
486
- (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, validatorScript: string | null, scriptTxHash: string | null, scriptOutputIndex: number | null, redeemerJson: string | null, datumJson: string | null, changeAddress: _.Bech32 | null, requiredSignersJson: string | null, scriptParamsJson: string | null, inlineDatumJson: string | null, lockOnScript: boolean | null, forceInputsJson: string | null, extraOutputsJson: string | null, mintActionsJson: string | null, mintingPolicyScript: string | null, mintRedeemerJson: string | null, referenceInputsJson: string | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
486
+ (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, validatorScript: string | null, scriptTxHash: string | null, scriptOutputIndex: number | null, redeemerJson: string | null, datumJson: string | null, changeAddress: _.Bech32 | null, requiredSignersJson: string | null, scriptParamsJson: string | null, inlineDatumJson: string | null, lockOnScript: boolean | null, forceInputsJson: string | null, protectInputsJson: string | null, extraOutputsJson: string | null, mintActionsJson: string | null, mintingPolicyScript: string | null, mintRedeemerJson: string | null, referenceInputsJson: string | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
487
487
  // named
488
- ({senderAddress, recipientAddress, lovelaceAmount, validatorScript, scriptTxHash, scriptOutputIndex, redeemerJson, datumJson, changeAddress, requiredSignersJson, scriptParamsJson, inlineDatumJson, lockOnScript, forceInputsJson, extraOutputsJson, mintActionsJson, mintingPolicyScript, mintRedeemerJson, referenceInputsJson, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, validatorScript?: string | null, scriptTxHash?: string | null, scriptOutputIndex?: number | null, redeemerJson?: string | null, datumJson?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, extraOutputsJson?: string | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, mintRedeemerJson?: string | null, referenceInputsJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
488
+ ({senderAddress, recipientAddress, lovelaceAmount, validatorScript, scriptTxHash, scriptOutputIndex, redeemerJson, datumJson, changeAddress, requiredSignersJson, scriptParamsJson, inlineDatumJson, lockOnScript, forceInputsJson, protectInputsJson, extraOutputsJson, mintActionsJson, mintingPolicyScript, mintRedeemerJson, referenceInputsJson, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, validatorScript?: string | null, scriptTxHash?: string | null, scriptOutputIndex?: number | null, redeemerJson?: string | null, datumJson?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, protectInputsJson?: string | null, extraOutputsJson?: string | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, mintRedeemerJson?: string | null, referenceInputsJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
489
489
  // metadata (do not use)
490
- __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, validatorScript?: string | null, scriptTxHash?: string | null, scriptOutputIndex?: number | null, redeemerJson?: string | null, datumJson?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, extraOutputsJson?: string | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, mintRedeemerJson?: string | null, referenceInputsJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
490
+ __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, validatorScript?: string | null, scriptTxHash?: string | null, scriptOutputIndex?: number | null, redeemerJson?: string | null, datumJson?: string | null, changeAddress?: _.Bech32 | null, requiredSignersJson?: string | null, scriptParamsJson?: string | null, inlineDatumJson?: string | null, lockOnScript?: boolean | null, forceInputsJson?: string | null, protectInputsJson?: string | null, extraOutputsJson?: string | null, mintActionsJson?: string | null, mintingPolicyScript?: string | null, mintRedeemerJson?: string | null, referenceInputsJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
491
491
  kind: 'action'
492
492
  }
493
493
 
494
494
  export declare const BuildPlutusTransaction: {
495
495
  // positional
496
- (senderAddress: _.Bech32 | null, changeAddress: _.Bech32 | null, scriptInputsJson: string | null, outputsJson: string | null, referenceInputsJson: string | null, forceInputsJson: string | null, requiredSignersJson: string | null, mintActionsJson: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
496
+ (senderAddress: _.Bech32 | null, changeAddress: _.Bech32 | null, scriptInputsJson: string | null, outputsJson: string | null, referenceInputsJson: string | null, forceInputsJson: string | null, protectInputsJson: string | null, withdrawalsJson: string | null, certificatesJson: string | null, requiredSignersJson: string | null, mintActionsJson: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
497
497
  // named
498
- ({senderAddress, changeAddress, scriptInputsJson, outputsJson, referenceInputsJson, forceInputsJson, requiredSignersJson, mintActionsJson, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, changeAddress?: _.Bech32 | null, scriptInputsJson?: string | null, outputsJson?: string | null, referenceInputsJson?: string | null, forceInputsJson?: string | null, requiredSignersJson?: string | null, mintActionsJson?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
498
+ ({senderAddress, changeAddress, scriptInputsJson, outputsJson, referenceInputsJson, forceInputsJson, protectInputsJson, withdrawalsJson, certificatesJson, requiredSignersJson, mintActionsJson, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, changeAddress?: _.Bech32 | null, scriptInputsJson?: string | null, outputsJson?: string | null, referenceInputsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, withdrawalsJson?: string | null, certificatesJson?: string | null, requiredSignersJson?: string | null, mintActionsJson?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
499
499
  // metadata (do not use)
500
- __parameters: {senderAddress?: _.Bech32 | null, changeAddress?: _.Bech32 | null, scriptInputsJson?: string | null, outputsJson?: string | null, referenceInputsJson?: string | null, forceInputsJson?: string | null, requiredSignersJson?: string | null, mintActionsJson?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
500
+ __parameters: {senderAddress?: _.Bech32 | null, changeAddress?: _.Bech32 | null, scriptInputsJson?: string | null, outputsJson?: string | null, referenceInputsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, withdrawalsJson?: string | null, certificatesJson?: string | null, requiredSignersJson?: string | null, mintActionsJson?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
501
501
  kind: 'action'
502
502
  }
503
503
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.26",
3
+ "version": "2.0.0-rc.27",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -37,6 +37,11 @@ export declare class CardanoTransactionBuilder {
37
37
  * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
38
38
  */
39
39
  buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
40
+ /**
41
+ * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
42
+ * build fails here with the account named. A provider failure is passed on as it is.
43
+ */
44
+ private _assertRewardAccountsRegistered;
40
45
  /**
41
46
  * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
42
47
  * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
@@ -186,9 +186,16 @@ class CardanoTransactionBuilder {
186
186
  const allUtxos = mergeUtxosUnique(senderUtxos, scriptUtxos);
187
187
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
188
188
  // Reference-script UTxOs always from the ledger: a known sender UTxO may carry only the script hash
189
- const refScriptUtxos = await this._resolveInputRefs(req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])), [], 'referenceScript');
189
+ const refScriptUtxos = await this._resolveInputRefs([
190
+ ...req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])),
191
+ ...(req.withdrawals ?? []).flatMap(w => (w.referenceScript ? [w.referenceScript] : [])),
192
+ ...(req.certificates ?? []).flatMap(c => (c.referenceScript ? [c.referenceScript] : [])),
193
+ ], [], 'referenceScript');
190
194
  const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
191
195
  const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
196
+ // A credential this transaction registers is withdrawable in the same transaction
197
+ const registeredHere = new Set((req.certificates ?? []).filter(c => c.type === 'registerStake').map(c => c.stakeAddress.toLowerCase()));
198
+ await this._assertRewardAccountsRegistered(req.withdrawals ?? [], registeredHere);
192
199
  const txContext = {
193
200
  utxos: mergeUtxosUnique(allUtxos, forcedUtxos),
194
201
  protocolParameters,
@@ -200,6 +207,28 @@ class CardanoTransactionBuilder {
200
207
  logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
201
208
  return builder.buildUnsignedPlutusTransaction(req, txContext);
202
209
  }
210
+ /**
211
+ * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
212
+ * build fails here with the account named. A provider failure is passed on as it is.
213
+ */
214
+ async _assertRewardAccountsRegistered(withdrawals, registeredHere = new Set()) {
215
+ for (const [i, w] of withdrawals.entries()) {
216
+ if (registeredHere.has(w.rewardAddress.toLowerCase()))
217
+ continue;
218
+ let active;
219
+ try {
220
+ active = (await this.client.getAccount(w.rewardAddress)).active;
221
+ }
222
+ catch (err) {
223
+ if (!(err instanceof errors_1.NotFoundError))
224
+ throw err;
225
+ active = false;
226
+ }
227
+ if (!active) {
228
+ throw new errors_1.TransactionValidationError(`withdrawals[${i}] reward account ${w.rewardAddress} is not registered on chain; register the stake credential first`);
229
+ }
230
+ }
231
+ }
203
232
  /**
204
233
  * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
205
234
  * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
@@ -96,6 +96,17 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
96
96
  * refs absent from utxos are ignored (existence is validated upstream).
97
97
  */
98
98
  private _partitionForcedInputs;
99
+ /**
100
+ * Staking script of a withdrawal or certificate: inline (swapped for a reference input that already
101
+ * carries the same hash), by reference, or none (key witness).
102
+ */
103
+ private _resolveStakingScript;
104
+ /**
105
+ * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
106
+ * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
107
+ * Script addresses are refused; those UTxOs are script inputs.
108
+ */
109
+ private _checkForeignForcedInputs;
99
110
  /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
100
111
  private _referencedKeys;
101
112
  /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
@@ -192,7 +192,7 @@ class BuildooorTxBuilder {
192
192
  const refScript = this._parseReferenceScript(req.referenceScript);
193
193
  const outputs = [this._buildTxOut(recipientAddress, outputValue, req.outputDatum, refScript)];
194
194
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
195
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs));
195
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
196
196
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
197
197
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
198
198
  // Coin selection on candidates only; forced inputs are prepended unconditionally
@@ -232,7 +232,7 @@ class BuildooorTxBuilder {
232
232
  }
233
233
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
234
234
  // collateral and coin selection operate on the remainder only.
235
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs));
235
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
236
236
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
237
237
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
238
238
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
@@ -325,7 +325,7 @@ class BuildooorTxBuilder {
325
325
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
326
326
  // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
327
327
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
328
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs));
328
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
329
329
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
330
330
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
331
331
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
@@ -467,15 +467,52 @@ class BuildooorTxBuilder {
467
467
  }
468
468
  return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
469
469
  });
470
+ // Withdrawals: the staking script inline, by reference, or the one a reference input carries
471
+ const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
472
+ w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
473
+ ...this._resolveStakingScript(w, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
474
+ }));
475
+ // Certificates: the credential from the stake address; a script runs under the Certifying purpose
476
+ const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
477
+ const certEntries = (req.certificates ?? []).map((c, i) => {
478
+ const at = `certificates[${i}]`;
479
+ const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
480
+ const credentialHash = stake.credentials.toString().toLowerCase();
481
+ const witness = this._resolveStakingScript(c, at, referencedByHash, refUtxoByKey);
482
+ const scripted = Boolean(witness.script || witness.refLedgerUtxo);
483
+ const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
484
+ if (stake.type === 'script') {
485
+ if (scripted && witnessHash !== credentialHash) {
486
+ throw new errors_1.TransactionValidationError(`${at} staking script hash ${witnessHash} is not the credential of ${c.stakeAddress} (${credentialHash})`);
487
+ }
488
+ if (!scripted && c.type === 'deregisterStake') {
489
+ throw new errors_1.TransactionValidationError(`${at} deregisters the script credential ${c.stakeAddress}; its staking script and redeemer are needed`);
490
+ }
491
+ }
492
+ else if (scripted) {
493
+ throw new errors_1.TransactionValidationError(`${at} ${c.stakeAddress} is a key credential; it takes no staking script`);
494
+ }
495
+ const stakeCredential = stake.type === 'script' ? cardano_ledger_ts_1.Credential.script(stake.credentials) : cardano_ledger_ts_1.Credential.keyHash(stake.credentials);
496
+ const deposit = c.deposit ? BigInt(c.deposit) : stakeDeposit;
497
+ // Without a script the witness-free legacy registration; the deposit forms need the witness
498
+ const cert = c.type === 'registerStake'
499
+ ? (scripted ? new cardano_ledger_ts_1.CertRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeRegistration({ stakeCredential }))
500
+ : (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
501
+ return { c, cert, deposit, ...witness };
502
+ });
470
503
  const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
471
504
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
472
- 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] : []))));
505
+ const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
506
+ if (scriptKeyClash)
507
+ throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
508
+ 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);
509
+ this._checkForeignForcedInputs(forced, req);
473
510
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
474
511
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
475
512
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
476
513
  const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
477
- // Funding covers only what the outputs need beyond the script inputs, forced inputs and mints
478
- // (keepRelevant adds its own lovelace margin for fee and change).
514
+ // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
515
+ // withdrawals (keepRelevant adds its own lovelace margin for fee and change).
479
516
  const need = new Map();
480
517
  const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
481
518
  for (const o of req.outputs) {
@@ -489,6 +526,11 @@ class BuildooorTxBuilder {
489
526
  }
490
527
  for (const m of req.mintActions ?? [])
491
528
  add(m.assetUnit, -BigInt(m.quantity));
529
+ for (const { w } of withdrawalEntries)
530
+ add('lovelace', -BigInt(w.lovelace));
531
+ // a registration locks the deposit, a deregistration refunds it
532
+ for (const { c, deposit } of certEntries)
533
+ add('lovelace', c.type === 'registerStake' ? deposit : -deposit);
492
534
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
493
535
  for (const [unit, qty] of need) {
494
536
  if (qty <= 0n)
@@ -518,8 +560,23 @@ class BuildooorTxBuilder {
518
560
  const mints = req.mintActions && req.mintActions.length > 0
519
561
  ? this._buildMintEntries(req.mintActions, this._parsePlutusV3Script(req.mintActions[0].mintingPolicyScript, 'mintActions[0].mintingPolicyScript'), undefined, resolveCtx)
520
562
  : undefined;
563
+ // Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
564
+ const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
565
+ const withdrawal = { rewardAccount, amount: BigInt(w.lovelace) };
566
+ if (!script && !refLedgerUtxo)
567
+ return { withdrawal };
568
+ 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));
569
+ return { withdrawal, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
570
+ });
571
+ // Certificates in the given order; a scripted one carries its redeemer under the Cert purpose
572
+ const certificates = certEntries.map(({ c, cert, script, refLedgerUtxo }) => {
573
+ if (!script && !refLedgerUtxo)
574
+ return { cert };
575
+ 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));
576
+ return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
577
+ });
521
578
  // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
522
- const refScriptKeys = new Set(scriptEntries.filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
579
+ const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
523
580
  const readonlyRefInputs = this._mapReferenceInputs((ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u))));
524
581
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
525
582
  const buildParams = {
@@ -528,7 +585,9 @@ class BuildooorTxBuilder {
528
585
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
529
586
  invalidBefore, invalidAfter,
530
587
  ...(collateralReturn && { collateralReturn }),
531
- ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
588
+ ...(readonlyRefInputs.length > 0 && { readonlyRefInputs }),
589
+ ...(withdrawals.length > 0 && { withdrawals }),
590
+ ...(certificates.length > 0 && { certificates })
532
591
  };
533
592
  const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
534
593
  const details = this._extractTxDetails(tx);
@@ -826,28 +885,103 @@ class BuildooorTxBuilder {
826
885
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
827
886
  * refs absent from utxos are ignored (existence is validated upstream).
828
887
  */
829
- _partitionForcedInputs(utxos, forceInputs, referenced = new Set()) {
888
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs) {
830
889
  const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
831
- if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && !utxos.some(hasRefScript))
832
- return { forced: [], rest: utxos };
833
890
  const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
891
+ const protectedKeys = new Set((protectInputs ?? []).map(key));
892
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(hasRefScript)) {
893
+ return { forced: [], rest: utxos };
894
+ }
834
895
  const forcedKeys = new Set((forceInputs ?? []).map(key));
835
896
  // a UTxO cannot be spent and referenced in one transaction
836
897
  const clash = [...forcedKeys].find(k => referenced.has(k));
837
898
  if (clash)
838
899
  throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input — a UTxO cannot be spent and referenced in one transaction`);
900
+ const protectedClash = [...forcedKeys].find(k => protectedKeys.has(k));
901
+ if (protectedClash)
902
+ throw new errors_1.TransactionValidationError(`forceInputs ${protectedClash} is also in protectInputs`);
839
903
  const forced = [];
840
904
  const rest = [];
841
905
  for (const u of utxos) {
842
906
  if (forcedKeys.has(key(u)))
843
907
  forced.push(u);
844
- // reference inputs and UTxOs carrying a reference script stay out of coin selection and
845
- // collateral; a deployed script is spent only when forced
846
- else if (!referenced.has(key(u)) && !hasRefScript(u))
908
+ // reference inputs, protected UTxOs and UTxOs carrying a reference script stay out of coin
909
+ // selection and collateral; a deployed script is spent only when forced
910
+ else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !hasRefScript(u))
847
911
  rest.push(u);
848
912
  }
849
913
  return { forced, rest };
850
914
  }
915
+ /**
916
+ * Staking script of a withdrawal or certificate: inline (swapped for a reference input that already
917
+ * carries the same hash), by reference, or none (key witness).
918
+ */
919
+ _resolveStakingScript(w, at, referencedByHash, refUtxoByKey) {
920
+ if (w.stakingScript) {
921
+ const script = this._parsePlutusV3Script(w.stakingScript, `${at}.stakingScript`);
922
+ const referenced = referencedByHash.get(script.hash.toString());
923
+ return referenced ? { refLedgerUtxo: referenced } : { script };
924
+ }
925
+ if (!w.referenceScript)
926
+ return {};
927
+ const refKey = `${w.referenceScript.txHash.toLowerCase()}#${w.referenceScript.outputIndex}`;
928
+ const refUtxo = refUtxoByKey.get(refKey);
929
+ if (!refUtxo)
930
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} not found on-chain or already spent`);
931
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
932
+ if (!refLedgerUtxo.resolved.refScript) {
933
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
934
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
935
+ }
936
+ return { refLedgerUtxo };
937
+ }
938
+ /**
939
+ * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
940
+ * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
941
+ * Script addresses are refused; those UTxOs are script inputs.
942
+ */
943
+ _checkForeignForcedInputs(forced, req) {
944
+ const sender = req.senderAddress.toLowerCase();
945
+ const foreign = forced.filter(u => u.address.toLowerCase() !== sender);
946
+ if (foreign.length === 0)
947
+ return;
948
+ const signers = new Set((req.requiredSigners ?? []).map(s => s.toLowerCase()));
949
+ const keyOf = (u) => `${u.txHash}#${u.outputIndex}`;
950
+ const byAddress = new Map();
951
+ for (const u of foreign)
952
+ byAddress.set(u.address, [...(byAddress.get(u.address) ?? []), u]);
953
+ for (const [address, utxos] of byAddress) {
954
+ const creds = cardano_ledger_ts_1.Address.fromString(address).paymentCreds;
955
+ const refs = utxos.map(keyOf).join(', ');
956
+ if (creds.type !== cardano_ledger_ts_1.CredentialType.KeyHash) {
957
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} are at the script address ${address}; spend script UTxOs via scriptInputs`);
958
+ }
959
+ const keyHash = creds.hash.toString().toLowerCase();
960
+ if (!signers.has(keyHash)) {
961
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} belong to ${address}; its payment key hash ${keyHash} must be in requiredSigners (the owner co-signs)`);
962
+ }
963
+ }
964
+ const brought = new Map();
965
+ for (const u of foreign) {
966
+ for (const a of u.amount) {
967
+ const unit = a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit;
968
+ brought.set(unit, (brought.get(unit) ?? 0n) + BigInt(a.quantity));
969
+ }
970
+ }
971
+ const spent = new Map();
972
+ for (const o of req.outputs) {
973
+ spent.set('lovelace', (spent.get('lovelace') ?? 0n) + BigInt(o.lovelaceAmount));
974
+ for (const a of o.assets ?? [])
975
+ spent.set(a.unit, (spent.get(a.unit) ?? 0n) + BigInt(a.quantity));
976
+ }
977
+ for (const [unit, qty] of brought) {
978
+ const out = spent.get(unit) ?? 0n;
979
+ if (qty > out) {
980
+ throw new errors_1.TransactionValidationError(`forceInputs of other addresses bring ${qty} ${unit} but the outputs spend only ${out}; ` +
981
+ `the difference would go to the sender's change, return it to its owner in outputs`);
982
+ }
983
+ }
984
+ }
851
985
  /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
852
986
  _referencedKeys(ctx, ...refs) {
853
987
  const keys = new Set();
@@ -114,6 +114,8 @@ function prepareSimpleAda(raw, network) {
114
114
  const clean = { ...raw };
115
115
  clean.forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
116
116
  delete clean.forceInputsJson;
117
+ clean.protectInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.protectInputsJson, 'protectInputsJson'));
118
+ delete clean.protectInputsJson;
117
119
  const outputDatum = parseJsonField(raw, 'outputDatumJson');
118
120
  if (outputDatum !== undefined)
119
121
  clean.outputDatum = outputDatum;
@@ -170,6 +172,7 @@ function prepareMint(raw, network) {
170
172
  const inlineDatum = parseJsonField(raw, 'inlineDatumJson');
171
173
  const mintRedeemer = parseJsonField(raw, 'mintRedeemerJson');
172
174
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
175
+ const protectInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.protectInputsJson, 'protectInputsJson'));
173
176
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
174
177
  const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
175
178
  if (raw.lockOnScript && (!scriptParams || scriptParams.length === 0)) {
@@ -190,6 +193,7 @@ function prepareMint(raw, network) {
190
193
  delete clean.mintRedeemerJson;
191
194
  delete clean.lockOnScript;
192
195
  delete clean.forceInputsJson;
196
+ delete clean.protectInputsJson;
193
197
  delete clean.referenceInputsJson;
194
198
  delete clean.extraOutputsJson;
195
199
  if (parsedMetadata)
@@ -237,6 +241,7 @@ function prepareMint(raw, network) {
237
241
  inlineDatum,
238
242
  mintRedeemer,
239
243
  forceInputs,
244
+ protectInputs,
240
245
  referenceInputs,
241
246
  extraOutputs,
242
247
  };
@@ -255,6 +260,7 @@ function preparePlutusSpend(raw, network) {
255
260
  fail('lockOnScript requires scriptParamsJson to derive script address');
256
261
  }
257
262
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
263
+ const protectInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.protectInputsJson, 'protectInputsJson'));
258
264
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
259
265
  const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
260
266
  // Optional combined spend+mint.
@@ -317,6 +323,7 @@ function preparePlutusSpend(raw, network) {
317
323
  requiredSigners,
318
324
  inlineDatum,
319
325
  forceInputs,
326
+ protectInputs,
320
327
  referenceInputs,
321
328
  extraOutputs,
322
329
  mintActions,
@@ -329,6 +336,7 @@ function preparePlutusSpend(raw, network) {
329
336
  delete clean.scriptParamsJson;
330
337
  delete clean.inlineDatumJson;
331
338
  delete clean.forceInputsJson;
339
+ delete clean.protectInputsJson;
332
340
  delete clean.referenceInputsJson;
333
341
  delete clean.extraOutputsJson;
334
342
  delete clean.mintActionsJson;
@@ -109,6 +109,9 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
109
109
  @title: 'Force Inputs JSON'
110
110
  @description: 'Optional JSON array of {txHash, outputIndex} UTxOs that MUST be consumed as inputs. Added before coin selection. Use for one-shot minting seeds, token-carrying UTxOs, or deterministic input control.'
111
111
  forceInputsJson: String,
112
+ @title: 'Protect Inputs JSON'
113
+ @description: 'Optional JSON array of {txHash, outputIndex} UTxOs of the sender that must never be spent: left out of coin selection and collateral.'
114
+ protectInputsJson: String,
112
115
  @title: 'Validator Script'
113
116
  @description: 'Optional Plutus validator CBOR hex. Required when lockOnScript=true. Used only to derive the target script address — the script itself is not attached to the transaction.'
114
117
  validatorScript: String,
@@ -217,6 +220,9 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
217
220
  @title: 'Force Inputs JSON'
218
221
  @description: 'Optional JSON array of {txHash, outputIndex} UTxOs that MUST be consumed as inputs. Added before coin selection. Use for one-shot minting seeds, token-carrying UTxOs, or deterministic input control.'
219
222
  forceInputsJson: String,
223
+ @title: 'Protect Inputs JSON'
224
+ @description: 'Optional JSON array of {txHash, outputIndex} UTxOs of the sender that must never be spent: left out of coin selection and collateral.'
225
+ protectInputsJson: String,
220
226
  @title: 'Reference Inputs JSON'
221
227
  @description: 'Optional JSON array of {txHash, outputIndex} UTxOs to include as CIP-31 reference inputs (read-only, not consumed). Use for oracle feeds, shared config UTxOs, or script reference UTxOs. Buildooor builder only.'
222
228
  referenceInputsJson: String,
@@ -308,6 +314,9 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
308
314
  @title: 'Force Inputs JSON'
309
315
  @description: 'Optional JSON array of {txHash, outputIndex} UTxOs that MUST be consumed as inputs. Added before coin selection. Use for one-shot minting seeds, token-carrying UTxOs, or deterministic input control.'
310
316
  forceInputsJson: String,
317
+ @title: 'Protect Inputs JSON'
318
+ @description: 'Optional JSON array of {txHash, outputIndex} UTxOs of the sender that must never be spent: left out of coin selection and collateral.'
319
+ protectInputsJson: String,
311
320
  @title: 'Extra Outputs JSON'
312
321
  @description: 'Optional JSON array of additional outputs appended after the primary recipient output, before change. Each entry: {address, lovelaceAmount, assets?: [{unit, quantity}], inlineDatumJson?, referenceScriptHex?}. Use for multi-output state-machine transitions (counter updates + batch NFT outputs) or per-output CIP-33 ref-script deploy. Each extra output is independently min-ADA checked.'
313
322
  extraOutputsJson: String,
@@ -352,8 +361,17 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
352
361
  @description: 'Optional JSON array of {txHash, outputIndex} read-only reference inputs; reference-script UTxOs of scriptInputsJson are added automatically.'
353
362
  referenceInputsJson: String,
354
363
  @title: 'Force Inputs JSON'
355
- @description: 'Optional JSON array of {txHash, outputIndex} UTxOs of the sender that must be consumed.'
364
+ @description: 'Optional JSON array of {txHash, outputIndex} UTxOs that must be consumed. A UTxO of another key address needs that address''s payment key hash in requiredSignersJson, and every unit it brings must be spent by outputsJson (nothing of it goes to the change); it is never collateral.'
356
365
  forceInputsJson: String,
366
+ @title: 'Protect Inputs JSON'
367
+ @description: 'Optional JSON array of {txHash, outputIndex} UTxOs of the sender that must never be spent: left out of coin selection and collateral.'
368
+ protectInputsJson: String,
369
+ @title: 'Withdrawals JSON'
370
+ @description: 'Optional JSON array, 1..16 entries: {rewardAddress, lovelace (0 allowed), stakingScript (CBOR hex) | referenceScript: {txHash, outputIndex}, scriptParamsJson?, redeemerJson | redeemerCbor}. With a script the withdrawal runs it under the Reward purpose (withdraw-zero pattern), without one the stake key signs. The reward account must be registered on chain.'
371
+ withdrawalsJson: String,
372
+ @title: 'Certificates JSON'
373
+ @description: 'Optional JSON array, 1..16 entries: {type: registerStake | deregisterStake, stakeAddress, deposit?, stakingScript (CBOR hex) | referenceScript: {txHash, outputIndex}, scriptParamsJson?, redeemerJson | redeemerCbor}. A registration without a script needs no witness (key or script credential); with a script it is the Conway deposit form and the script runs under the Certifying purpose. A deregistration of a script credential needs the script; of a key credential the key''s witness. The deposit is balanced by the builder.'
374
+ certificatesJson: String,
357
375
  @title: 'Required Signers JSON'
358
376
  @description: 'Optional JSON array of Ed25519 key hashes (hex, 28 bytes each) that must sign the transaction.'
359
377
  requiredSignersJson: String,
@@ -35,6 +35,11 @@ module.exports = (srv) => {
35
35
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', forceInputsResult.error, 'forceInputsJson');
36
36
  cleanData.forceInputs = forceInputsResult.parsed;
37
37
  delete cleanData.forceInputsJson;
38
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
39
+ if (protectInputsResult.error)
40
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', protectInputsResult.error, 'protectInputsJson');
41
+ cleanData.protectInputs = protectInputsResult.parsed;
42
+ delete cleanData.protectInputsJson;
38
43
  if (outputDatumJson) {
39
44
  const jsonResult = (0, validators_1.validatePlutusJson)(outputDatumJson, 'outputDatumJson');
40
45
  if (!jsonResult.valid)
@@ -261,6 +266,10 @@ module.exports = (srv) => {
261
266
  if (forceInputsResult.error)
262
267
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', forceInputsResult.error, 'forceInputsJson');
263
268
  const forceInputs = forceInputsResult.parsed;
269
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
270
+ if (protectInputsResult.error)
271
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', protectInputsResult.error, 'protectInputsJson');
272
+ const protectInputs = protectInputsResult.parsed;
264
273
  // CIP-31 reference inputs
265
274
  const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
266
275
  if (refInputsResult.error)
@@ -289,6 +298,7 @@ module.exports = (srv) => {
289
298
  delete cleanData.mintRedeemerJson;
290
299
  delete cleanData.lockOnScript;
291
300
  delete cleanData.forceInputsJson;
301
+ delete cleanData.protectInputsJson;
292
302
  delete cleanData.referenceInputsJson;
293
303
  delete cleanData.extraOutputsJson;
294
304
  if (parsedMetadata) {
@@ -350,6 +360,7 @@ module.exports = (srv) => {
350
360
  inlineDatum,
351
361
  mintRedeemer,
352
362
  forceInputs,
363
+ protectInputs,
353
364
  referenceInputs,
354
365
  extraOutputs
355
366
  });
@@ -421,6 +432,10 @@ module.exports = (srv) => {
421
432
  if (forceInputsResult.error)
422
433
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', forceInputsResult.error, 'forceInputsJson');
423
434
  const forceInputs = forceInputsResult.parsed;
435
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
436
+ if (protectInputsResult.error)
437
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', protectInputsResult.error, 'protectInputsJson');
438
+ const protectInputs = protectInputsResult.parsed;
424
439
  // CIP-31 reference inputs
425
440
  const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
426
441
  if (refInputsResult.error)
@@ -571,6 +586,7 @@ module.exports = (srv) => {
571
586
  requiredSigners,
572
587
  inlineDatum,
573
588
  forceInputs,
589
+ protectInputs,
574
590
  referenceInputs,
575
591
  extraOutputs,
576
592
  mintActions: parsedMintActions,
@@ -585,6 +601,7 @@ module.exports = (srv) => {
585
601
  delete cleanData.inlineDatumJson;
586
602
  delete cleanData.lockOnScript;
587
603
  delete cleanData.forceInputsJson;
604
+ delete cleanData.protectInputsJson;
588
605
  delete cleanData.referenceInputsJson;
589
606
  delete cleanData.extraOutputsJson;
590
607
  delete cleanData.mintActionsJson;
@@ -617,7 +634,7 @@ module.exports = (srv) => {
617
634
  });
618
635
  // BuildPlutusTransaction — several script UTxOs in one transaction, each with its own redeemer.
619
636
  srv.on('BuildPlutusTransaction', async (req) => {
620
- const { senderAddress, changeAddress, scriptInputsJson, outputsJson, referenceInputsJson, forceInputsJson, requiredSignersJson, mintActionsJson, validityStartMs, validityEndMs } = req.data;
637
+ const { senderAddress, changeAddress, scriptInputsJson, outputsJson, referenceInputsJson, forceInputsJson, protectInputsJson, withdrawalsJson, certificatesJson, requiredSignersJson, mintActionsJson, validityStartMs, validityEndMs } = req.data;
621
638
  const action = 'BuildPlutusTransaction';
622
639
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, validityStartMs, validityEndMs }, ['senderAddress']);
623
640
  (0, errors_1.throwIfValidationErrors)(req, action, errors);
@@ -640,6 +657,15 @@ module.exports = (srv) => {
640
657
  const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
641
658
  if (forceInputsResult.error)
642
659
  return (0, errors_1.rejectInvalid)(req, action, forceInputsResult.error, 'forceInputsJson');
660
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(protectInputsJson, 'protectInputsJson');
661
+ if (protectInputsResult.error)
662
+ return (0, errors_1.rejectInvalid)(req, action, protectInputsResult.error, 'protectInputsJson');
663
+ const withdrawalsResult = (0, tx_request_parsers_1.parseWithdrawals)(withdrawalsJson);
664
+ if (withdrawalsResult.error)
665
+ return (0, errors_1.rejectInvalid)(req, action, withdrawalsResult.error, 'withdrawalsJson');
666
+ const certificatesResult = (0, tx_request_parsers_1.parseCertificates)(certificatesJson);
667
+ if (certificatesResult.error)
668
+ return (0, errors_1.rejectInvalid)(req, action, certificatesResult.error, 'certificatesJson');
643
669
  const signersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
644
670
  if (signersResult.error)
645
671
  return (0, errors_1.rejectInvalid)(req, action, signersResult.error, 'requiredSignersJson');
@@ -669,6 +695,41 @@ module.exports = (srv) => {
669
695
  ...(si.datumCbor ? { datumCbor: si.datumCbor } : {}),
670
696
  });
671
697
  }
698
+ // Same for the staking scripts of withdrawals and certificates
699
+ const stakingWitness = (w, at, field) => {
700
+ let stakingScript = w.stakingScript;
701
+ if (stakingScript && w.scriptParams) {
702
+ try {
703
+ stakingScript = (0, tx_build_helper_1.applyScriptParameters)(stakingScript, w.scriptParams);
704
+ }
705
+ catch (err) {
706
+ const errMsg = err instanceof Error ? err.message : String(err);
707
+ return { error: (0, errors_1.rejectInvalid)(req, action, `${at}: failed to apply script parameters: ${errMsg}`, field) };
708
+ }
709
+ }
710
+ return {
711
+ parsed: {
712
+ ...(stakingScript ? { stakingScript } : {}),
713
+ ...(w.referenceScript ? { referenceScript: w.referenceScript } : {}),
714
+ ...(w.redeemer !== undefined ? { redeemer: w.redeemer } : {}),
715
+ ...(w.redeemerCbor ? { redeemerCbor: w.redeemerCbor } : {}),
716
+ },
717
+ };
718
+ };
719
+ const withdrawals = [];
720
+ for (const [i, w] of (withdrawalsResult.parsed ?? []).entries()) {
721
+ const witness = stakingWitness(w, `withdrawals[${i}]`, 'withdrawalsJson');
722
+ if ('error' in witness)
723
+ return witness.error;
724
+ withdrawals.push({ rewardAddress: w.rewardAddress, lovelace: w.lovelace, ...witness.parsed });
725
+ }
726
+ const certificates = [];
727
+ for (const [i, c] of (certificatesResult.parsed ?? []).entries()) {
728
+ const witness = stakingWitness(c, `certificates[${i}]`, 'certificatesJson');
729
+ if ('error' in witness)
730
+ return witness.error;
731
+ certificates.push({ type: c.type, stakeAddress: c.stakeAddress, ...(c.deposit ? { deposit: c.deposit } : {}), ...witness.parsed });
732
+ }
672
733
  const buildReq = {
673
734
  network: (0, server_1.getCardanoClient)().network,
674
735
  senderAddress,
@@ -677,6 +738,9 @@ module.exports = (srv) => {
677
738
  outputs: outputsResult.parsed,
678
739
  referenceInputs: refInputsResult.parsed,
679
740
  forceInputs: forceInputsResult.parsed,
741
+ protectInputs: protectInputsResult.parsed,
742
+ ...(withdrawals.length > 0 ? { withdrawals } : {}),
743
+ ...(certificates.length > 0 ? { certificates } : {}),
680
744
  requiredSigners: signersResult.parsed,
681
745
  mintActions: mintResult.parsed,
682
746
  validityStartMs,
@@ -104,10 +104,13 @@ export declare const ED25519_KEY_HASH_HEX_LENGTH = 56;
104
104
  export declare const ED25519_KEY_HASH_REGEX: RegExp;
105
105
  /** Minimum lovelace for a change output carrying native assets (2 ADA) */
106
106
  export declare const MIN_CHANGE_LOVELACE = 2000000;
107
- /** Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`). */
107
+ /**
108
+ * Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`)
109
+ * and `slotToPosixSeconds()`. `systemStartPosixMs` is the first Shelley slot's wall-clock time.
110
+ */
108
111
  export declare const GENESIS_INFOS_BY_NETWORK: {
109
112
  readonly mainnet: {
110
- readonly systemStartPosixMs: 1596491091000;
113
+ readonly systemStartPosixMs: 1596059091000;
111
114
  readonly slotLengthMs: 1000;
112
115
  readonly startSlotNo: 4492800;
113
116
  };
@@ -83,9 +83,12 @@ exports.ED25519_KEY_HASH_HEX_LENGTH = 56;
83
83
  exports.ED25519_KEY_HASH_REGEX = /^[a-f0-9]{56}$/i;
84
84
  /** Minimum lovelace for a change output carrying native assets (2 ADA) */
85
85
  exports.MIN_CHANGE_LOVELACE = 2_000_000;
86
- /** Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`). */
86
+ /**
87
+ * Shelley genesis parameters per network for Buildooor's GenesisInfos (`TxBuilder.posixToSlot()`)
88
+ * and `slotToPosixSeconds()`. `systemStartPosixMs` is the first Shelley slot's wall-clock time.
89
+ */
87
90
  exports.GENESIS_INFOS_BY_NETWORK = {
88
- mainnet: { systemStartPosixMs: 1596491091000, slotLengthMs: 1000, startSlotNo: 4492800 },
91
+ mainnet: { systemStartPosixMs: 1596059091000, slotLengthMs: 1000, startSlotNo: 4492800 }, // 2020-07-29T21:44:51Z
89
92
  preprod: { systemStartPosixMs: 1655683200000, slotLengthMs: 1000, startSlotNo: 0 },
90
93
  preview: { systemStartPosixMs: 1666656000000, slotLengthMs: 1000, startSlotNo: 0 },
91
94
  };
@@ -1,5 +1,5 @@
1
1
  import type { JSONValue, MintAction } from './types';
2
- export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson'): {
2
+ export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson' | 'protectInputsJson'): {
3
3
  parsed?: Array<{
4
4
  txHash: string;
5
5
  outputIndex: number;
@@ -81,6 +81,47 @@ export declare function parseScriptInputs(json: string | undefined): {
81
81
  parsed?: ParsedScriptInput[];
82
82
  error?: string;
83
83
  };
84
+ /** Upper bound on withdrawals per BuildPlutusTransaction. */
85
+ export declare const MAX_WITHDRAWALS = 16;
86
+ /** One withdrawal of a BuildPlutusTransaction, validated; `stakingScript` still without params applied. */
87
+ export interface ParsedWithdrawal {
88
+ rewardAddress: string;
89
+ lovelace: string;
90
+ stakingScript?: string;
91
+ scriptParams?: JSONValue[];
92
+ referenceScript?: {
93
+ txHash: string;
94
+ outputIndex: number;
95
+ };
96
+ redeemer?: JSONValue;
97
+ redeemerCbor?: string;
98
+ }
99
+ /**
100
+ * Parse and validate withdrawalsJson: distinct reward accounts, lovelace >= 0, optionally a staking
101
+ * script (inline or by reference) with exactly one redeemer form; without a script no redeemer.
102
+ */
103
+ export declare function parseWithdrawals(json: string | undefined): {
104
+ parsed?: ParsedWithdrawal[];
105
+ error?: string;
106
+ };
107
+ /** Optional staking script (inline with params, or by reference) plus its redeemer, shared by withdrawals and certificates. */
108
+ type ParsedStakingScriptWitness = Pick<ParsedWithdrawal, 'stakingScript' | 'scriptParams' | 'referenceScript' | 'redeemer' | 'redeemerCbor'>;
109
+ /** Upper bound on certificates per BuildPlutusTransaction. */
110
+ export declare const MAX_CERTIFICATES = 16;
111
+ /** One certificate of a BuildPlutusTransaction, validated; `stakingScript` still without params applied. */
112
+ export interface ParsedCertificate extends ParsedStakingScriptWitness {
113
+ type: 'registerStake' | 'deregisterStake';
114
+ stakeAddress: string;
115
+ deposit?: string;
116
+ }
117
+ /**
118
+ * Parse and validate certificatesJson: stake registrations and deregistrations, each with an
119
+ * optional staking script (inline or by reference) and exactly one redeemer form when scripted.
120
+ */
121
+ export declare function parseCertificates(json: string | undefined): {
122
+ parsed?: ParsedCertificate[];
123
+ error?: string;
124
+ };
84
125
  /**
85
126
  * Parse mintActionsJson for BuildPlutusTransaction: every action carries its own `mintingPolicyScript`
86
127
  * (no request-level default) and optional `redeemerJson`; `assetUnit` is policyId+assetName, or a bare
@@ -90,4 +131,5 @@ export declare function parsePolicyMintActions(json: string | undefined): {
90
131
  parsed?: MintAction[];
91
132
  error?: string;
92
133
  };
134
+ export {};
93
135
  //# sourceMappingURL=tx-request-parsers.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_SCRIPT_INPUTS = exports.MAX_EXTRA_OUTPUTS = void 0;
3
+ exports.MAX_CERTIFICATES = exports.MAX_WITHDRAWALS = exports.MAX_SCRIPT_INPUTS = exports.MAX_EXTRA_OUTPUTS = void 0;
4
4
  exports.parseUtxoRefArray = parseUtxoRefArray;
5
5
  exports.parseRequiredSigners = parseRequiredSigners;
6
6
  exports.parseAssetsArray = parseAssetsArray;
@@ -8,6 +8,8 @@ exports.parseExtraOutputs = parseExtraOutputs;
8
8
  exports.parseOutputList = parseOutputList;
9
9
  exports.parseMintActionPolicyFields = parseMintActionPolicyFields;
10
10
  exports.parseScriptInputs = parseScriptInputs;
11
+ exports.parseWithdrawals = parseWithdrawals;
12
+ exports.parseCertificates = parseCertificates;
11
13
  exports.parsePolicyMintActions = parsePolicyMintActions;
12
14
  const validators_1 = require("./validators");
13
15
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
@@ -334,6 +336,161 @@ function parseScriptInputs(json) {
334
336
  }
335
337
  return { parsed: out };
336
338
  }
339
+ /** Upper bound on withdrawals per BuildPlutusTransaction. */
340
+ exports.MAX_WITHDRAWALS = 16;
341
+ /**
342
+ * Parse and validate withdrawalsJson: distinct reward accounts, lovelace >= 0, optionally a staking
343
+ * script (inline or by reference) with exactly one redeemer form; without a script no redeemer.
344
+ */
345
+ function parseWithdrawals(json) {
346
+ if (!json)
347
+ return { parsed: undefined };
348
+ const jsonResult = (0, validators_1.validateJsonWithLimits)(json, 'withdrawalsJson');
349
+ if (!jsonResult.valid)
350
+ return { error: jsonResult.error };
351
+ if (!Array.isArray(jsonResult.parsed))
352
+ return { error: 'withdrawalsJson must be a JSON array' };
353
+ if (jsonResult.parsed.length === 0)
354
+ return { parsed: undefined };
355
+ if (jsonResult.parsed.length > exports.MAX_WITHDRAWALS) {
356
+ return { error: `withdrawalsJson exceeds maximum of ${exports.MAX_WITHDRAWALS} entries` };
357
+ }
358
+ const out = [];
359
+ const seen = new Set();
360
+ for (let i = 0; i < jsonResult.parsed.length; i++) {
361
+ const entry = jsonResult.parsed[i];
362
+ const at = `withdrawals[${i}]`;
363
+ if (!entry || typeof entry !== 'object')
364
+ return { error: `${at} must be an object` };
365
+ if (typeof entry.rewardAddress !== 'string' || !(0, validators_1.isValidBech32StakeAddress)(entry.rewardAddress)) {
366
+ return { error: `${at}.rewardAddress must be a Bech32 stake address` };
367
+ }
368
+ const rewardAddress = entry.rewardAddress.toLowerCase();
369
+ if (seen.has(rewardAddress))
370
+ return { error: `${at} withdraws from ${rewardAddress} a second time` };
371
+ seen.add(rewardAddress);
372
+ const lovelace = typeof entry.lovelace === 'number' && Number.isInteger(entry.lovelace) && entry.lovelace >= 0
373
+ ? String(entry.lovelace)
374
+ : typeof entry.lovelace === 'string' && /^\d+$/.test(entry.lovelace) ? entry.lovelace : undefined;
375
+ if (lovelace === undefined)
376
+ return { error: `${at}.lovelace must be a non-negative integer (0 for withdraw-zero)` };
377
+ const witness = parseStakingScriptWitness(entry, at, 'withdrawal');
378
+ if (witness.error)
379
+ return { error: witness.error };
380
+ out.push({ rewardAddress, lovelace, ...witness.parsed });
381
+ }
382
+ return { parsed: out };
383
+ }
384
+ function parseStakingScriptWitness(entry, at, kind) {
385
+ const present = (v) => v !== undefined && v !== null;
386
+ const parseJsonField = (value, field) => {
387
+ if (typeof value !== 'string')
388
+ return { error: `${field} must be a JSON string` };
389
+ const r = (0, validators_1.validatePlutusJson)(value, field);
390
+ return r.valid ? { parsed: r.parsed } : { error: r.error };
391
+ };
392
+ const w = {};
393
+ const hasInline = present(entry.stakingScript);
394
+ const hasRef = present(entry.referenceScript);
395
+ if (hasInline && hasRef)
396
+ return { error: `${at} takes stakingScript or referenceScript, not both` };
397
+ if (hasInline) {
398
+ if (typeof entry.stakingScript !== 'string' || !(0, validators_1.isValidCbor)(entry.stakingScript)) {
399
+ return { error: `${at}.stakingScript must be even-length CBOR hex` };
400
+ }
401
+ w.stakingScript = entry.stakingScript;
402
+ if (present(entry.scriptParamsJson)) {
403
+ const params = parseJsonField(entry.scriptParamsJson, `${at}.scriptParamsJson`);
404
+ if (params.error)
405
+ return { error: params.error };
406
+ if (!Array.isArray(params.parsed))
407
+ return { error: `${at}.scriptParamsJson must be a JSON array` };
408
+ if (params.parsed.length > 0)
409
+ w.scriptParams = params.parsed;
410
+ }
411
+ }
412
+ else if (hasRef) {
413
+ const ref = entry.referenceScript;
414
+ if (!ref || typeof ref !== 'object' || typeof ref.txHash !== 'string' || !(0, validators_1.isTxHash)(ref.txHash)
415
+ || typeof ref.outputIndex !== 'number' || !Number.isInteger(ref.outputIndex) || ref.outputIndex < 0) {
416
+ return { error: `${at}.referenceScript must be {txHash, outputIndex} of the UTxO carrying the script` };
417
+ }
418
+ if (present(entry.scriptParamsJson))
419
+ return { error: `${at}.scriptParamsJson applies to an inline stakingScript only` };
420
+ w.referenceScript = { txHash: ref.txHash.toLowerCase(), outputIndex: ref.outputIndex };
421
+ }
422
+ else if (present(entry.scriptParamsJson)) {
423
+ return { error: `${at}.scriptParamsJson applies to an inline stakingScript only` };
424
+ }
425
+ const hasRedeemerJson = present(entry.redeemerJson);
426
+ const hasRedeemerCbor = present(entry.redeemerCbor);
427
+ if (hasInline || hasRef) {
428
+ if (hasRedeemerJson === hasRedeemerCbor)
429
+ return { error: `${at} needs exactly one of redeemerJson or redeemerCbor` };
430
+ if (hasRedeemerCbor) {
431
+ const cbor = parsePlutusCbor(entry.redeemerCbor, `${at}.redeemerCbor`);
432
+ if (cbor.error)
433
+ return { error: cbor.error };
434
+ w.redeemerCbor = cbor.hex;
435
+ }
436
+ else {
437
+ const redeemer = parseJsonField(entry.redeemerJson, `${at}.redeemerJson`);
438
+ if (redeemer.error)
439
+ return { error: redeemer.error };
440
+ w.redeemer = redeemer.parsed;
441
+ }
442
+ }
443
+ else if (hasRedeemerJson || hasRedeemerCbor) {
444
+ return { error: `${at} has a redeemer but no staking script; a key-witnessed ${kind} takes none` };
445
+ }
446
+ return { parsed: w };
447
+ }
448
+ /** Upper bound on certificates per BuildPlutusTransaction. */
449
+ exports.MAX_CERTIFICATES = 16;
450
+ /**
451
+ * Parse and validate certificatesJson: stake registrations and deregistrations, each with an
452
+ * optional staking script (inline or by reference) and exactly one redeemer form when scripted.
453
+ */
454
+ function parseCertificates(json) {
455
+ if (!json)
456
+ return { parsed: undefined };
457
+ const jsonResult = (0, validators_1.validateJsonWithLimits)(json, 'certificatesJson');
458
+ if (!jsonResult.valid)
459
+ return { error: jsonResult.error };
460
+ if (!Array.isArray(jsonResult.parsed))
461
+ return { error: 'certificatesJson must be a JSON array' };
462
+ if (jsonResult.parsed.length === 0)
463
+ return { parsed: undefined };
464
+ if (jsonResult.parsed.length > exports.MAX_CERTIFICATES) {
465
+ return { error: `certificatesJson exceeds maximum of ${exports.MAX_CERTIFICATES} entries` };
466
+ }
467
+ const out = [];
468
+ for (let i = 0; i < jsonResult.parsed.length; i++) {
469
+ const entry = jsonResult.parsed[i];
470
+ const at = `certificates[${i}]`;
471
+ if (!entry || typeof entry !== 'object')
472
+ return { error: `${at} must be an object` };
473
+ if (entry.type !== 'registerStake' && entry.type !== 'deregisterStake') {
474
+ return { error: `${at}.type must be registerStake or deregisterStake` };
475
+ }
476
+ if (typeof entry.stakeAddress !== 'string' || !(0, validators_1.isValidBech32StakeAddress)(entry.stakeAddress)) {
477
+ return { error: `${at}.stakeAddress must be a Bech32 stake address` };
478
+ }
479
+ let deposit;
480
+ if (entry.deposit !== undefined && entry.deposit !== null) {
481
+ deposit = typeof entry.deposit === 'number' && Number.isInteger(entry.deposit) && entry.deposit > 0
482
+ ? String(entry.deposit)
483
+ : typeof entry.deposit === 'string' && /^\d+$/.test(entry.deposit) && entry.deposit !== '0' ? entry.deposit : undefined;
484
+ if (deposit === undefined)
485
+ return { error: `${at}.deposit must be a positive integer (lovelace)` };
486
+ }
487
+ const witness = parseStakingScriptWitness(entry, at, 'certificate');
488
+ if (witness.error)
489
+ return { error: witness.error };
490
+ out.push({ type: entry.type, stakeAddress: entry.stakeAddress.toLowerCase(), ...(deposit ? { deposit } : {}), ...witness.parsed });
491
+ }
492
+ return { parsed: out };
493
+ }
337
494
  /**
338
495
  * Parse mintActionsJson for BuildPlutusTransaction: every action carries its own `mintingPolicyScript`
339
496
  * (no request-level default) and optional `redeemerJson`; `assetUnit` is policyId+assetName, or a bare
@@ -378,6 +378,11 @@ export type TxBuildRequest = {
378
378
  txHash: string;
379
379
  outputIndex: number;
380
380
  }>;
381
+ /** UTxOs the build must never spend: left out of coin selection and collateral. */
382
+ protectInputs?: Array<{
383
+ txHash: string;
384
+ outputIndex: number;
385
+ }>;
381
386
  /** CIP-31 reference inputs (read-only, not consumed), passed as readonlyRefInputs to Buildooor. */
382
387
  referenceInputs?: Array<{
383
388
  txHash: string;
@@ -437,10 +442,54 @@ export type PlutusTxOutput = NonNullable<TxBuildRequest['extraOutputs']>[number]
437
442
  /** Inline datum as PlutusData CBOR hex, taken byte for byte; exclusive with inlineDatum. */
438
443
  inlineDatumCbor?: string;
439
444
  };
445
+ /**
446
+ * Reward-account withdrawal of a BuildPlutusTransaction. A staking script (inline or by reference)
447
+ * runs with the redeemer under the Reward purpose; without a script the stake key signs.
448
+ */
449
+ export type WithdrawalInput = {
450
+ /** Bech32 reward account (stake address). */
451
+ rewardAddress: string;
452
+ /** Withdrawn lovelace; 0 for the withdraw-zero pattern. */
453
+ lovelace: string;
454
+ /** Staking script CBOR hex (script params already applied); exclusive with referenceScript. */
455
+ stakingScript?: string;
456
+ /** UTxO that carries the staking script as reference script; added as reference input. */
457
+ referenceScript?: {
458
+ txHash: string;
459
+ outputIndex: number;
460
+ };
461
+ /** Redeemer (PlutusData JSON); `__INPUT_IDX__` placeholders resolve against the final inputs. */
462
+ redeemer?: JSONValue;
463
+ /** Redeemer as PlutusData CBOR hex; wins over `redeemer`, no placeholders. */
464
+ redeemerCbor?: string;
465
+ };
466
+ /**
467
+ * Stake-credential certificate of a BuildPlutusTransaction. A registration without a script is the
468
+ * witness-free legacy form (key or script credential); with a script the Conway deposit form, run
469
+ * under the Certifying purpose. A deregistration needs the key's witness or the script.
470
+ */
471
+ export type CertificateInput = {
472
+ type: 'registerStake' | 'deregisterStake';
473
+ /** Bech32 stake address of the credential. */
474
+ stakeAddress: string;
475
+ /** Explicit deposit (lovelace) for the Conway forms; defaults to the protocol's stake deposit. */
476
+ deposit?: string;
477
+ stakingScript?: string;
478
+ referenceScript?: {
479
+ txHash: string;
480
+ outputIndex: number;
481
+ };
482
+ redeemer?: JSONValue;
483
+ redeemerCbor?: string;
484
+ };
440
485
  /** BuildPlutusTransaction: several script inputs, the outputs as given, change after them. */
441
- export type TxBuildPlutusRequest = Pick<TxBuildRequest, 'network' | 'senderAddress' | 'changeAddress' | 'requiredSigners' | 'forceInputs' | 'referenceInputs' | 'mintActions' | 'validityStartMs' | 'validityEndMs'> & {
486
+ export type TxBuildPlutusRequest = Pick<TxBuildRequest, 'network' | 'senderAddress' | 'changeAddress' | 'requiredSigners' | 'forceInputs' | 'protectInputs' | 'referenceInputs' | 'mintActions' | 'validityStartMs' | 'validityEndMs'> & {
442
487
  scriptInputs: ScriptInput[];
443
488
  outputs: PlutusTxOutput[];
489
+ /** Reward-account withdrawals, with or without a staking script. */
490
+ withdrawals?: WithdrawalInput[];
491
+ /** Stake-credential registrations and deregistrations. */
492
+ certificates?: CertificateInput[];
444
493
  };
445
494
  /** Execution budget for Plutus scripts */
446
495
  export type ExecutionBudget = {