sdk/builders/TxBuilderImpl.ts
TxBuilderImpl overview
// Effect-TS imports
Table of contents
assembly
assembleTransaction
Assemble a Transaction from inputs, outputs, and calculated fee. Creates TransactionBody with all required fields.
Uses Core TransactionOutput directly.
This is minimal assembly with accurate fee:
- Build witness set with redeemers and signatures (Step 4 - future)
- Run script evaluation to fill ExUnits (Step 5 - future)
- Add change output (Step 6 - future)
Signature
export declare const assembleTransaction: (
inputs: ReadonlyArray<TransactionInput.TransactionInput>,
outputs: ReadonlyArray<TxOut.TransactionOutput>,
fee: bigint
) => Effect.Effect<Transaction.Transaction, TransactionBuilderError, TxContext | TxBuilderConfigTag | BuildOptionsTag>Added in v2.0.0
buildTransactionInputs
Convert an array of UTxOs to an array of TransactionInputs. Inputs are sorted by txHash then outputIndex for deterministic ordering. Uses Core UTxO types directly.
Signature
export declare const buildTransactionInputs: (
utxos: ReadonlyArray<CoreUTxO.UTxO>
) => Effect.Effect<ReadonlyArray<TransactionInput.TransactionInput>, never>Added in v2.0.0
change
calculateMinimumUtxoLovelace
Calculate minimum ADA required for a UTxO based on its actual CBOR size. Uses the Babbage/Conway-era formula: coinsPerUtxoByte * (160 + serializedOutputSize).
The 160-byte constant accounts for the UTxO entry overhead in the ledger state (transaction hash + index). A lovelace placeholder is used during CBOR encoding to ensure the coin field width matches the final result.
This function creates a temporary TransactionOutput, encodes it to CBOR, and calculates the exact size to determine the minimum lovelace required.
Signature
export declare const calculateMinimumUtxoLovelace: (params: {
address: CoreAddress.Address
assets: CoreAssets.Assets
datum?: DatumOption.DatumOption
scriptRef?: CoreScript.Script
coinsPerUtxoByte: bigint
}) => Effect.Effect<bigint, TransactionBuilderError>Added in v2.0.0
createChangeOutput
Create change output(s) for leftover assets.
When unfracking is disabled (default):
- Check if leftover assets exist
- Calculate minimum ADA required for change output
- If leftover lovelace < minimum, cannot create change (warning)
- Create single output with all leftover assets to change address
When unfracking is enabled:
- Apply Unfrack.It optimization strategies
- Bundle tokens into optimally-sized UTxOs
- Isolate fungible tokens if configured
- Group NFTs by policy if configured
- Roll up or subdivide ADA-only UTxOs
- Return multiple change outputs for optimal wallet structure
Signature
export declare const createChangeOutput: (params: {
leftoverAssets: CoreAssets.Assets
changeAddress: CoreAddress.Address
coinsPerUtxoByte: bigint
unfrackOptions?: UnfrackOptions
}) => Effect.Effect<ReadonlyArray<TxOut.TransactionOutput>, TransactionBuilderError>Added in v2.0.0
fee-calculation
buildFakeWitnessSet
Build a fake witness set for fee estimation from transaction inputs. Extracts unique payment key hashes from input addresses and creates fake witnesses to accurately estimate witness set size in CBOR. Includes any attached scripts from builder state for accurate size estimation.
Signature
export declare const buildFakeWitnessSet: (
inputUtxos: ReadonlyArray<CoreUTxO.UTxO>
) => Effect.Effect<TransactionWitnessSet.TransactionWitnessSet, TransactionBuilderError, TxContext>Added in v2.0.0
calculateFeeIteratively
Calculate transaction fee iteratively until stable.
Algorithm:
- Build fake witness set from input UTxOs for accurate size estimation
- Build transaction with fee = 0
- Calculate size and fee
- Rebuild transaction with calculated fee
- If size changed, recalculate (usually converges in 1-2 iterations)
Signature
export declare const calculateFeeIteratively: (
inputUtxos: ReadonlyArray<CoreUTxO.UTxO>,
inputs: ReadonlyArray<TransactionInput.TransactionInput>,
outputs: ReadonlyArray<TxOut.TransactionOutput>,
redeemers: Map<
string,
{
readonly tag: "spend" | "mint" | "cert" | "reward" | "vote"
readonly data: PlutusData.Data
readonly exUnits?: { readonly mem: bigint; readonly steps: bigint }
}
>,
protocolParams: { minFeeCoefficient: bigint; minFeeConstant: bigint; priceMem?: number; priceStep?: number }
) => Effect.Effect<bigint, TransactionBuilderError, TxContext | BuildOptionsTag>Added in v2.0.0
calculateMinimumFee
Calculate minimum transaction fee based on protocol parameters.
Formula: minFee = txSizeInBytes × minFeeCoefficient + minFeeConstant
Signature
export declare const calculateMinimumFee: (
transactionSizeBytes: number,
protocolParams: { minFeeCoefficient: bigint; minFeeConstant: bigint }
) => bigintAdded in v2.0.0
calculateTransactionSize
Calculate the size of a transaction in bytes for fee estimation. Uses CBOR serialization to get accurate size.
Signature
export declare const calculateTransactionSize: (
transaction: Transaction.Transaction
) => Effect.Effect<number, TransactionBuilderError>Added in v2.0.0
verifyTransactionBalance
Verify if selected UTxOs can cover outputs + fee for ALL assets. Used by the re-selection loop to determine if more UTxOs are needed.
Checks both lovelace AND native assets (tokens/NFTs) to ensure complete balance.
Signature
export declare const verifyTransactionBalance: (
selectedUtxos: ReadonlyArray<CoreUTxO.UTxO>,
outputs: ReadonlyArray<TxOut.TransactionOutput>,
fee: bigint
) => { sufficient: boolean; shortfall: bigint; change: bigint }Added in v2.0.0
helpers
calculateReferenceScriptFee
Calculate reference script fees using tiered pricing.
Matches the Cardano node's tierRefScriptFee from Conway ledger:
- Stride: 25,600 bytes (hardcoded, becomes a protocol param post-Conway)
- Multiplier: 1.2× per tier (hardcoded, becomes a protocol param post-Conway)
- Base cost:
minFeeRefScriptCostPerByteprotocol parameter
For each 25,600-byte chunk the price per byte increases by 1.2×.
The final (partial) chunk is charged proportionally. Result is floor(total).
The Cardano node sums scriptRef sizes from both spent inputs and reference
inputs (txNonDistinctRefScriptsSize), so callers must pass both.
Signature
export declare const calculateReferenceScriptFee: (
utxos: ReadonlyArray<CoreUTxO.UTxO>,
costPerByte: number
) => Effect.Effect<bigint, TransactionBuilderError>Added in v2.0.0
calculateTotalAssets
Calculate total assets from a set of UTxOs.
Signature
export declare const calculateTotalAssets: (
utxos: ReadonlyArray<CoreUTxO.UTxO> | Set<CoreUTxO.UTxO>
) => CoreAssets.AssetsAdded in v2.0.0
filterScriptUtxos
Filter UTxOs to find those locked by scripts (script-locked UTxOs).
Signature
export declare const filterScriptUtxos: (
utxos: ReadonlyArray<CoreUTxO.UTxO>
) => Effect.Effect<ReadonlyArray<CoreUTxO.UTxO>, TransactionBuilderError>Added in v2.0.0
isScriptAddress
Check if an address string is a script address (payment credential is ScriptHash). Parses the address to extract its structure and checks the payment credential type.
Signature
export declare const isScriptAddress: (address: string) => Effect.Effect<boolean, TransactionBuilderError>Added in v2.0.0
isScriptAddressCore
Check if an address is a script address (payment credential is ScriptHash). Works with Core Address type.
Signature
export declare const isScriptAddressCore: (address: CoreAddress.Address) => booleanAdded in v2.0.0
makeTxOutput
Create a TransactionOutput from user-friendly parameters. Uses Core types directly.
TransactionOutput represents an output being created in a transaction.
Signature
export declare const makeTxOutput: (params: {
address: CoreAddress.Address
assets: CoreAssets.Assets
datum?: DatumOption.DatumOption
scriptRef?: CoreScript.Script
}) => Effect.Effect<TxOut.TransactionOutput, never>Added in v2.0.0
mergeAssetsIntoOutput
Merge additional assets into an existing TransactionOutput. Creates a new output with combined assets from the original output and leftover assets.
Use case: Draining wallet by merging leftover into an existing payment output.
Signature
export declare const mergeAssetsIntoOutput: (
output: TxOut.TransactionOutput,
additionalAssets: CoreAssets.Assets
) => Effect.Effect<TxOut.TransactionOutput, never>Added in v2.0.0
mergeAssetsIntoUTxO
Merge additional assets into an existing UTxO. Creates a new UTxO with combined assets from the original UTxO and additional assets.
Use case: Draining wallet by merging leftover into an existing payment output.
Signature
export declare const mergeAssetsIntoUTxO: (
utxo: CoreUTxO.UTxO,
additionalAssets: CoreAssets.Assets
) => Effect.Effect<CoreUTxO.UTxO, never>Added in v2.0.0
tierRefScriptFee
Calculate reference script fees using tiered pricing.
Direct port of the Cardano ledger's tierRefScriptFee function.
Each sizeIncrement-byte chunk is priced at curTierPrice per byte,
then curTierPrice *= multiplier for the next chunk. Final result: floor(total).
Signature
export declare const tierRefScriptFee: (
multiplier: number,
sizeIncrement: number,
baseFee: number,
totalSize: number
) => bigintAdded in v2.0.0
validation
calculateLeftoverAssets
Calculate leftover assets (will become excess fee in minimal build).
Signature
export declare const calculateLeftoverAssets: (params: {
totalInputAssets: CoreAssets.Assets
totalOutputAssets: CoreAssets.Assets
fee: bigint
}) => CoreAssets.AssetsAdded in v2.0.0
validateTransactionBalance
Validate that inputs cover outputs plus fee. This is the ONLY validation for minimal build - no coin selection.
Signature
export declare const validateTransactionBalance: (params: {
totalInputAssets: CoreAssets.Assets
totalOutputAssets: CoreAssets.Assets
fee: bigint
}) => Effect.Effect<void, TransactionBuilderError>Added in v2.0.0