TxBuilder

scalus.cardano.txbuilder.TxBuilder
See theTxBuilder companion object
case class TxBuilder(env: CardanoInfo, context: Context, evaluator: PlutusScriptEvaluator, steps: Seq[TransactionBuilderStep] = ..., attachedData: Map[DataHash, Data] = ..., validators: Seq[Validator] = ...)

A high-level, fluent API for building Cardano transactions.

TxBuilder provides a convenient way to construct transactions by chaining method calls. It handles input selection, output creation, script attachment, minting, and transaction finalization including fee calculation and change handling.

TxBuilder is purely functional; each method returns a new instance with the updated state. The complete method is the only one that performs effects (querying UTXOs from a provider).

==Platform Support==

TxBuilder supports both JVM and JavaScript platforms:

  • complete(provider, sponsor): Returns Future[TxBuilder]. Available on all platforms.
  • complete(provider, sponsor, timeout): JVM-only blocking version with timeout parameter.

On JVM, you can also use the await extension method on Future:

import scalus.cardano.txbuilder.await
builder.complete(provider, sponsor).await()

==Usage==

// Cross-platform - async (returns Future)
val txFuture = TxBuilder(env)
 .payTo(recipientAddress, Value.ada(10))
 .complete(provider, sponsorAddress)
 .map(_.sign(signer).transaction)

// JVM-only - blocking with timeout
import scala.concurrent.duration.*
val tx = TxBuilder(env)
 .payTo(recipientAddress, Value.ada(10))
 .complete(provider, sponsorAddress, 30.seconds)
 .sign(signer)
 .transaction

Value parameters

attachedData

datum values to be included in the transaction witness set

context

the current transaction builder context

env

the environment containing protocol parameters, network info, and slot configuration

evaluator

the Plutus script evaluator used for script validation

steps

accumulated transaction building steps

validators

ledger rules to run against the built transaction for additional validations

Attributes

Companion
object
Graph
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Members list

Value members

Concrete methods

Appends transaction building steps to this builder.

Appends transaction building steps to this builder.

This is the low-level method for adding steps. Prefer using the high-level methods like spend, payTo, mint, etc. unless you need direct step control.

Value parameters

s

the steps to append

Attributes

def attach(datum: Data): TxBuilder

Attaches a datum to the transaction witness set.

Attaches a datum to the transaction witness set.

Use this method when spending UTXOs that have datum hashes instead of inline datums. The datum hash is computed automatically and the datum is stored for inclusion in the witness set.

Value parameters

datum

the datum data to attach

Attributes

def build(diffHandler: DiffHandler): TxBuilder

Builds and finalizes the transaction.

Builds and finalizes the transaction.

This method assembles the transaction from all the accumulated steps, calculates fees, handles change, validates and runs all Plutus scripts, and produces a ready-to-sign transaction.

Value parameters

diffHandler

the handler for managing transaction balance differences (change)

Attributes

Returns

a new TxBuilder with the finalized transaction

Throws
RuntimeException

if script execution fails or if the transaction cannot be balanced

def build(changeTo: Address): TxBuilder

Builds and finalizes the transaction, sending any remaining value to the specified change address.

Builds and finalizes the transaction, sending any remaining value to the specified change address.

This is a convenience method that uses the default change handling strategy. Any difference between inputs and outputs (minus fees) will be sent to the provided address.

Value parameters

changeTo

the address to receive any remaining value (change)

Attributes

Returns

a new TxBuilder with the finalized transaction

Throws
RuntimeException

if script execution fails or if the transaction cannot be balanced

def collaterals(utxo: Utxo, rest: Utxo*): TxBuilder

Adds the specified utxos to the list of collateral inputs.

Adds the specified utxos to the list of collateral inputs.

Collateral inputs are used to cover transaction fees if script execution fails. They are only consumed if a script fails validation.

Attributes

def collaterals(utxos: Utxos): TxBuilder

Adds the specified utxos to the list of collateral inputs.

Adds the specified utxos to the list of collateral inputs.

Collateral inputs are used to cover transaction fees if script execution fails. They are only consumed if a script fails validation.

Attributes

def complete(provider: Provider, sponsor: Address)(using ExecutionContext): Future[TxBuilder]

Completes the transaction by selecting UTXOs, adding collateral, and balancing.

Completes the transaction by selecting UTXOs, adding collateral, and balancing.

This method queries the provider for available UTXOs at the sponsor address, selects inputs to cover all outputs and fees, selects collateral if needed (for script transactions), and sets up change handling to the sponsor address.

This is the primary cross-platform method available on both JVM and JavaScript platforms.

On JVM, you can use the blocking overload with a timeout parameter, or use the await extension method:

import scalus.cardano.txbuilder.await
builder.complete(provider, sponsor).await(30.seconds)

Value parameters

provider

the async provider to query for UTXOs

sponsor

the address to use for input selection, collateral, and change

Attributes

Returns

a Future containing a new TxBuilder with the transaction completed

def complete(availableUtxos: Utxos, sponsor: Address): TxBuilder

Completes the transaction using pre-fetched UTXOs.

Completes the transaction using pre-fetched UTXOs.

This synchronous variant is useful when UTXOs are already available in memory, avoiding the need for async provider queries. Otherwise identical to the provider-based variant.

Value parameters

availableUtxos

the UTXOs available at the sponsor address for input/collateral selection

sponsor

the address to use for input selection, collateral, and change

Attributes

Returns

a new TxBuilder with the transaction completed

def delegateTo(stakeAddress: StakeAddress, poolId: PoolKeyHash): TxBuilder

Delegates a stake key to the specified stake pool.

Delegates a stake key to the specified stake pool.

Attributes

def delegateToPoolAndDRep(stakeAddress: StakeAddress, poolId: PoolKeyHash, drep: DRep): TxBuilder

Delegates to both a stake pool and a DRep.

Delegates to both a stake pool and a DRep.

Attributes

def delegateVoteToDRep(stakeAddress: StakeAddress, drep: DRep): TxBuilder

Delegates voting power to a DRep.

Delegates voting power to a DRep.

Attributes

def deregisterStake(stakeAddress: StakeAddress): TxBuilder

Deregisters a stake key from the network.

Deregisters a stake key from the network.

The refund amount is taken from protocol parameters (stakeAddressDeposit).

Attributes

def deregisterStake(stakeAddress: StakeAddress, refund: Coin): TxBuilder

Deregisters a stake key with an explicit refund amount.

Deregisters a stake key with an explicit refund amount.

Value parameters

refund

the amount originally deposited during registration (must match ledger state)

Attributes

def metadata(auxiliaryData: AuxiliaryData): TxBuilder

Adds transaction metadata (auxiliary data).

Adds transaction metadata (auxiliary data).

Metadata is optional data attached to a transaction that does not affect validation but can be used for off-chain purposes.

Value parameters

auxiliaryData

the auxiliary data to attach

Attributes

def minFee(minFee: Coin): TxBuilder

Sets a minimum fee for the transaction.

Sets a minimum fee for the transaction.

This overrides the automatically calculated fee. Use with caution; the actual fee may need to be higher to cover script execution costs.

Value parameters

minFee

the minimum fee in lovelace

Attributes

def mint[T : ToData](policyId: PolicyId, assets: Map[AssetName, Long], redeemer: T): TxBuilder

Mints or burns native tokens under a minting policy (reference script).

Mints or burns native tokens under a minting policy (reference script).

Use positive amounts to mint tokens and negative amounts to burn tokens. The minting policy script must be present as a reference input (via references) for this to work.

Type parameters

T

type of the redeemer (must have a ToData instance)

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

policyId

the policy ID (script hash) of the minting policy

redeemer

redeemer to pass to the minting policy script

Attributes

def mint[T : ToData](policyId: PolicyId, assets: Map[AssetName, Long], redeemer: T, requiredSigners: Set[AddrKeyHash]): TxBuilder

Mints or burns native tokens under a minting policy with required signers (reference script).

Mints or burns native tokens under a minting policy with required signers (reference script).

Use positive amounts to mint tokens and negative amounts to burn tokens. The minting policy script must be present as a reference input (via references) for this to work.

Type parameters

T

type of the redeemer (must have a ToData instance)

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

policyId

the policy ID (script hash) of the minting policy

redeemer

redeemer to pass to the minting policy script

requiredSigners

set of public key hashes that must sign the transaction

Attributes

def mint[T : ToData](script: PlutusScript, assets: Map[AssetName, Long], redeemer: T): TxBuilder

Mints or burns native tokens with the script provided inline.

Mints or burns native tokens with the script provided inline.

Use positive amounts to mint tokens and negative amounts to burn tokens.

Type parameters

T

type of the redeemer (must have a ToData instance)

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

redeemer

redeemer to pass to the minting policy script

script

the minting policy script

Attributes

def mint[T : ToData](script: PlutusScript, assets: Map[AssetName, Long], redeemer: T, requiredSigners: Set[AddrKeyHash]): TxBuilder

Mints or burns native tokens with the script provided inline and required signers.

Mints or burns native tokens with the script provided inline and required signers.

Use positive amounts to mint tokens and negative amounts to burn tokens.

Type parameters

T

type of the redeemer (must have a ToData instance)

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

redeemer

redeemer to pass to the minting policy script

requiredSigners

set of public key hashes that must sign the transaction

script

the minting policy script

Attributes

def mint(script: PlutusScript, assets: Map[AssetName, Long], redeemerBuilder: Transaction => Data): TxBuilder

Mints or burns native tokens with a delayed redeemer and attached script.

Mints or burns native tokens with a delayed redeemer and attached script.

Use this method when the redeemer depends on the final transaction structure (e.g., for self-referential scripts). The redeemer is computed after the transaction is assembled but before script evaluation.

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

redeemerBuilder

function that computes the redeemer from the assembled transaction

script

the minting policy script

Attributes

def mint(policyId: PolicyId, assets: Map[AssetName, Long], redeemerBuilder: Transaction => Data): TxBuilder

Mints or burns native tokens with a delayed redeemer computed from the built transaction.

Mints or burns native tokens with a delayed redeemer computed from the built transaction.

Use this method when the redeemer depends on the final transaction structure (e.g., for self-referential scripts). The redeemer is computed after the transaction is assembled but before script evaluation.

The minting policy script must be present as a reference input (via references).

Value parameters

assets

map of asset names to amounts (positive for minting, negative for burning)

policyId

the policy ID (script hash) of the minting policy

redeemerBuilder

function that computes the redeemer from the assembled transaction

Attributes

Adds the specified output to the list of transaction outputs.

Adds the specified output to the list of transaction outputs.

Use this method for fine-grained control over output construction. For simpler cases, use payTo.

Value parameters

output

the transaction output to add

Attributes

def payTo(address: Address, value: Value): TxBuilder

Sends the specified value to the given address without a datum.

Sends the specified value to the given address without a datum.

Value parameters

address

recipient address

value

amount to send

Attributes

def payTo[T : ToData](address: Address, value: Value, datum: T): TxBuilder

Sends the specified value to the given address with an inline datum.

Sends the specified value to the given address with an inline datum.

Value parameters

address

recipient address

datum

inline datum to attach to the output

value

amount to send

Attributes

def payTo(address: Address, value: Value, datumHash: DataHash): TxBuilder

Sends the specified value to the given address with a datum hash.

Sends the specified value to the given address with a datum hash.

Make sure to call attach with the corresponding datum data before calling build.

Value parameters

address

recipient address

datumHash

hash of the datum (the actual datum must be attached via attach)

value

amount to send

Attributes

def references(utxo: Utxo, rest: Utxo*): TxBuilder

Adds the specified utxos to the list of reference inputs.

Adds the specified utxos to the list of reference inputs.

Reference inputs allow scripts to read UTXOs without consuming them.

Attributes

Registers stake address and delegates to both stake pool and DRep in one transaction.

Registers stake address and delegates to both stake pool and DRep in one transaction.

The deposit amount is taken from protocol parameters (stakeAddressDeposit).

Attributes

Registers stake address and delegates voting power to a DRep in one transaction.

Registers stake address and delegates voting power to a DRep in one transaction.

The deposit amount is taken from protocol parameters (stakeAddressDeposit).

Attributes

def registerDRep(drepCredential: Credential, anchor: Option[Anchor]): TxBuilder

Registers as a DRep.

Registers as a DRep.

The deposit amount is taken from protocol parameters (dRepDeposit).

Attributes

def registerStake(stakeAddress: StakeAddress): TxBuilder

Registers a stake key with the network.

Registers a stake key with the network.

The deposit amount is taken from protocol parameters (stakeAddressDeposit).

Attributes

Signs the transaction with the provided signer.

Signs the transaction with the provided signer.

This method should be called after build to add signatures to the transaction. Multiple signers can be applied by chaining sign calls.

Value parameters

signer

the transaction signer

Attributes

Returns

a new TxBuilder with the signed transaction

def spend(utxo: Utxo, witness: SpendWitness): TxBuilder

Spends a UTXO with an explicit witness.

Spends a UTXO with an explicit witness.

This is the most flexible spend method, allowing full control over the witness configuration. Use this when you need custom witness settings not covered by the convenience overloads.

Value parameters

utxo

the UTXO to spend

witness

the witness specifying how to authorize the spend (PubKeyWitness, NativeScriptWitness, or ThreeArgumentPlutusScriptWitness)

Attributes

def spend(utxo: Utxo): TxBuilder

Adds the specified pubkey utxo to the list of inputs, thus spending it.

Adds the specified pubkey utxo to the list of inputs, thus spending it.

If the sum of outputs exceeds the sum of spent inputs, the change is going to be handled according to the changeTo or diffHandler parameter of build.

Value parameters

utxo

utxo to spend

Attributes

Note

use spend with utxo and redeemer to spend script-protected utxos. Otherwise, build throws.

def spend(utxos: Utxos): TxBuilder

Adds the specified pubkey utxos to the list of inputs, thus spending them.

Adds the specified pubkey utxos to the list of inputs, thus spending them.

If the sum of outputs exceeds the sum of spent inputs, the change is going to be handled according to the changeTo or diffHandler parameter of build.

Value parameters

utxos

utxos to spend

Attributes

Note

use spend with utxo and redeemer to spend script-protected utxos. Otherwise, build throws.

def spend[T : ToData](utxo: Utxo, redeemer: T, requiredSigners: Set[AddrKeyHash] = ...): TxBuilder

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set.

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set.

The script must be present as a reference input (via references) for this to work. If the script that protects the utxo fails with the specified redeemer, build is going to throw.

If the sum of outputs exceeds the sum of spent inputs, the change is going to be handled according to the changeTo or diffHandler parameter of build.

Value parameters

redeemer

redeemer to pass to the script to unlock the inputs

requiredSigners

set of public key hashes that must sign the transaction

utxo

utxo to spend

Attributes

def spend(utxo: Utxo, redeemerBuilder: Transaction => Data): TxBuilder

Adds the specified script-protected utxo with a delayed redeemer that is computed from the built transaction.

Adds the specified script-protected utxo with a delayed redeemer that is computed from the built transaction.

Use this method when the redeemer depends on the final transaction structure (e.g., for self-referential scripts). The redeemer is computed after the transaction is assembled but before script evaluation.

The script must be present as a reference input (via references) for this to work.

Value parameters

redeemerBuilder

function that computes the redeemer from the assembled transaction

utxo

utxo to spend

Attributes

def spend(utxo: Utxo, redeemerBuilder: Transaction => Data, script: PlutusScript): TxBuilder

Spends a script-protected UTXO with a delayed redeemer computed from the built transaction.

Spends a script-protected UTXO with a delayed redeemer computed from the built transaction.

Use this method when the redeemer depends on the final transaction structure (e.g., for self-referential scripts that need to know input/output indices). The redeemer is computed after the transaction is assembled but before script evaluation.

Value parameters

redeemerBuilder

function that computes the redeemer from the assembled transaction

script

the Plutus script that protects the UTXO

utxo

the UTXO to spend

Attributes

def spend[T : ToData](utxo: Utxo, redeemer: T, script: PlutusScript): TxBuilder

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set.

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set.

If the specified script fails with the specified redeemer, build is going to throw.

If the sum of outputs exceeds the sum of spent inputs, the change is going to be handled according to the changeTo or diffHandler parameter of build.

Value parameters

redeemer

redeemer to pass to the script to unlock the inputs

script

script that protects the utxo

utxo

utxo to spend

Attributes

def spend[T : ToData](utxo: Utxo, redeemer: T, script: PlutusScript, requiredSigners: Set[AddrKeyHash]): TxBuilder

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set, with additional required signers.

Adds the specified script-protected utxo to the list of inputs and the specified redeemer to the witness set, with additional required signers.

Use this method when the validator script requires specific signatures beyond the spender. The public key hashes in additionalSigners will be added to the transaction's required signers field.

If the specified script fails with the specified redeemer, build is going to throw.

If the sum of outputs exceeds the sum of spent inputs, the change is going to be handled according to the changeTo or diffHandler parameter of build.

Value parameters

redeemer

redeemer to pass to the script to unlock the inputs

requiredSigners

set of public key hashes that must sign the transaction

script

script that protects the utxo

utxo

utxo to spend

Attributes

def stakeAndDelegate(stakeAddress: StakeAddress, poolId: PoolKeyHash): TxBuilder

Registers a stake key and delegates to a stake pool in a single transaction.

Registers a stake key and delegates to a stake pool in a single transaction.

The deposit amount is taken from protocol parameters (stakeAddressDeposit).

Attributes

Returns the current transaction.

Returns the current transaction.

Call this after build and optionally sign to get the final transaction ready for submission.

Attributes

def unregisterDRep(drepCredential: Credential, refund: Coin): TxBuilder

Unregisters as a DRep.

Unregisters as a DRep.

Value parameters

refund

the amount originally deposited during registration (must match ledger state)

Attributes

def updateDRep(drepCredential: Credential, anchor: Option[Anchor]): TxBuilder

Updates DRep metadata anchor.

Updates DRep metadata anchor.

Attributes

Sets the transaction validity interval using slot numbers.

Sets the transaction validity interval using slot numbers.

The transaction is only valid for inclusion in a block within the specified slot range. This is important for time-sensitive contracts.

Value parameters

interval

the validity interval specifying the valid slot range

Attributes

def validFrom(from: Instant): TxBuilder

Sets the earliest time from which the transaction is valid.

Sets the earliest time from which the transaction is valid.

The timestamp is converted to a slot number using the environment's slot configuration.

Value parameters

from

the earliest valid time for the transaction

Attributes

def validTo(to: Instant): TxBuilder

Sets the latest time until which the transaction is valid.

Sets the latest time until which the transaction is valid.

The timestamp is converted to a slot number using the environment's slot configuration. The transaction becomes invalid after this time.

Value parameters

to

the latest valid time for the transaction (exclusive)

Attributes

def withdrawRewards(stakeAddress: StakeAddress, amount: Coin): TxBuilder

Withdraws staking rewards.

Withdraws staking rewards.

Attributes

Deprecated methods

def mintAndAttach[T : ToData](redeemer: T, assets: Map[AssetName, Long], script: PlutusScript): TxBuilder

Attributes

Deprecated
[Since version 0.13.0] Use mint(script, assets, redeemer) instead

Use mint(script, assets, redeemer) instead

def mintAndAttach[T : ToData](redeemer: T, assets: Map[AssetName, Long], script: PlutusScript, requiredSigners: Set[AddrKeyHash]): TxBuilder

Attributes

Deprecated
[Since version 0.13.0] Use mint(script, assets, redeemer, requiredSigners) instead

Use mint(script, assets, redeemer, requiredSigners) instead

Inherited methods

def productElementNames: Iterator[String]

Attributes

Inherited from:
Product
def productIterator: Iterator[Any]

Attributes

Inherited from:
Product