Safe Haskell | None |
---|---|
Language | Haskell2010 |
Cardano.Api.Internal.Fees
Contents
Description
Calculating fees.
Synopsis
- evaluateTransactionFee :: ShelleyBasedEra era -> PParams (ShelleyLedgerEra era) -> TxBody era -> Word -> Word -> Int -> Coin
- calculateMinTxFee :: ShelleyBasedEra era -> PParams (ShelleyLedgerEra era) -> UTxO era -> TxBody era -> Word -> Coin
- estimateTransactionKeyWitnessCount :: TxBodyContent BuildTx era -> Word
- evaluateTransactionExecutionUnits :: CardanoEra era -> SystemStart -> LedgerEpochInfo -> LedgerProtocolParameters era -> UTxO era -> TxBody era -> Either (TransactionValidityError era) (Map ScriptWitnessIndex (Either ScriptExecutionError (EvalTxExecutionUnitsLog, ExecutionUnits)))
- evaluateTransactionExecutionUnitsShelley :: ShelleyBasedEra era -> SystemStart -> LedgerEpochInfo -> LedgerProtocolParameters era -> UTxO era -> Tx (ShelleyLedgerEra era) -> Either (TransactionValidityError era) (Map ScriptWitnessIndex (Either ScriptExecutionError (EvalTxExecutionUnitsLog, ExecutionUnits)))
- data ScriptExecutionError
- = ScriptErrorMissingTxIn TxIn
- | ScriptErrorTxInWithoutDatum TxIn
- | ScriptErrorWrongDatum (Hash ScriptData)
- | ScriptErrorEvaluationFailed DebugPlutusFailure
- | ScriptErrorExecutionUnitsOverflow
- | ScriptErrorNotPlutusWitnessedTxIn ScriptWitnessIndex ScriptHash
- | ScriptErrorRedeemerPointsToUnknownScriptHash ScriptWitnessIndex
- | ScriptErrorMissingScript ScriptWitnessIndex ResolvablePointers
- | ScriptErrorMissingCostModel Language
- | (EraPlutusContext (ShelleyLedgerEra era), Show (ContextError (ShelleyLedgerEra era))) => ScriptErrorTranslationError (ContextError (ShelleyLedgerEra era))
- data TransactionValidityError era where
- TransactionValidityIntervalError :: forall era. PastHorizonException -> TransactionValidityError era
- TransactionValidityCostModelError :: forall era. Map AnyPlutusScriptVersion CostModel -> String -> TransactionValidityError era
- evaluateTransactionBalance :: ShelleyBasedEra era -> PParams (ShelleyLedgerEra era) -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> UTxO era -> TxBody era -> TxOutValue era
- estimateBalancedTxBody :: HasCallStack => MaryEraOnwards era -> TxBodyContent BuildTx era -> PParams (ShelleyLedgerEra era) -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> Map ScriptWitnessIndex ExecutionUnits -> Coin -> Int -> Int -> Int -> AddressInEra era -> Value -> Either (TxFeeEstimationError era) (BalancedTxBody era)
- estimateOrCalculateBalancedTxBody :: ShelleyBasedEra era -> FeeEstimationMode era -> PParams (ShelleyLedgerEra era) -> TxBodyContent BuildTx era -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> AddressInEra era -> Either (AutoBalanceError era) (BalancedTxBody era)
- makeTransactionBodyAutoBalance :: HasCallStack => ShelleyBasedEra era -> SystemStart -> LedgerEpochInfo -> LedgerProtocolParameters era -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> UTxO era -> TxBodyContent BuildTx era -> AddressInEra era -> Maybe Word -> Either (TxBodyErrorAutoBalance era) (BalancedTxBody era)
- calcReturnAndTotalCollateral :: AlonzoEraPParams (ShelleyLedgerEra era) => BabbageEraOnwards era -> Coin -> PParams (ShelleyLedgerEra era) -> TxInsCollateral era -> TxReturnCollateral CtxTx era -> TxTotalCollateral era -> AddressInEra era -> Value (ShelleyLedgerEra era) -> (TxReturnCollateral CtxTx era, TxTotalCollateral era)
- data AutoBalanceError era
- data BalancedTxBody era = BalancedTxBody (TxBodyContent BuildTx era) (TxBody era) (TxOut CtxTx era) Coin
- data FeeEstimationMode era
- newtype RequiredShelleyKeyWitnesses = RequiredShelleyKeyWitnesses {}
- newtype RequiredByronKeyWitnesses = RequiredByronKeyWitnesses {}
- newtype TotalReferenceScriptsSize = TotalReferenceScriptsSize {}
- data TxBodyErrorAutoBalance era
- = TxBodyError TxBodyError
- | TxBodyScriptExecutionError [(ScriptWitnessIndex, ScriptExecutionError)]
- | TxBodyScriptBadScriptValidity
- | TxBodyErrorAdaBalanceNegative Coin
- | TxBodyErrorAdaBalanceTooSmall TxOutInAnyEra Coin Coin
- | TxBodyErrorByronEraNotSupported
- | TxBodyErrorMissingParamMinUTxO
- | TxBodyErrorValidityInterval (TransactionValidityError era)
- | TxBodyErrorMinUTxONotMet TxOutInAnyEra Coin
- | TxBodyErrorNonAdaAssetsUnbalanced Value
- | TxBodyErrorScriptWitnessIndexMissingFromExecUnitsMap ScriptWitnessIndex (Map ScriptWitnessIndex ExecutionUnits)
- data TxFeeEstimationError era
- = TxFeeEstimationTransactionTranslationError (TransactionValidityError era)
- | TxFeeEstimationScriptExecutionError (TxBodyErrorAutoBalance era)
- | TxFeeEstimationBalanceError (TxBodyErrorAutoBalance era)
- | TxFeeEstimationxBodyError TxBodyError
- | TxFeeEstimationFinalConstructionError TxBodyError
- | TxFeeEstimationOnlyMaryOnwardsSupportedError
- calculateMinimumUTxO :: HasCallStack => ShelleyBasedEra era -> TxOut CtxTx era -> PParams (ShelleyLedgerEra era) -> Coin
- data ResolvablePointers where
- ResolvablePointers :: forall era. (Era (ShelleyLedgerEra era), Show (PlutusPurpose AsIx (ShelleyLedgerEra era)), Show (PlutusPurpose AsItem (ShelleyLedgerEra era)), Show (PlutusScript (ShelleyLedgerEra era))) => ShelleyBasedEra era -> !(Map (PlutusPurpose AsIx (ShelleyLedgerEra era)) (PlutusPurpose AsItem (ShelleyLedgerEra era), Maybe (PlutusScriptBytes, Language), ScriptHash StandardCrypto)) -> ResolvablePointers
Introduction
The Cardano.Api.Internal.Tx.Body documentation demonstrates how to create a TxBodyContent
for a
transaction that takes 12 ada and sends 10 ada to an address, and spends 2 ada for fees. If a
UTXO with exactly 12 ada is available, this would be a valid transaction, because it is balanced, and has
sufficient fees, as 2 ada is more than enough to cover the fees for such a simple transaction on mainnet
at the time of writing.
A simple transaction that spends UTXOs is considered balanced if the value consumed equals the value produced. Simply put, a transaction that spends only lovelace must account for the total lovelace at the inputs, output(s), and transaction fee.
In other words:
inputs = outputs + fee
In this equation, the inputs would include the minted tokens, and the outputs would include the burned tokens.
However, we don't always want to spend all the ada from a UTXO. Balancing a transaction ensures that we send the desired amount, pay only the necessary fees, and calculate any extra currency to be sent back to a change address.
Since changes to the transaction body can affect the required, finding this balance can be challenging. Fortunately, there are functions available to help achieve this.
This module offers several methods for calculating transaction fees or fully balancing a draft transaction. Each method requires varying amounts of information and provides different levels of accuracy and automation.
Next, this module explores three examples of fee calculation methods. Other methods exist but they have similar requirements.
Examples below use the following qualified modules:
import qualified Cardano.Api as Api -- the general `cardano-api` exports
Example 1: Simple fee calculation and manual balancing
This method requires minimal information and some manual work.
It calculates the transaction fees, but we need to balance the transaction manually.
We need to know:
- The Shelley-based era witness for the current era, which can be obtained by using
shelleyBasedEra
.
let sbe :: Api.ShelleyBasedEra Api.ConwayEra = Api.shelleyBasedEra
- The protocol parameters for the current era, which can be obtained using the
QueryProtocolParameters
query defined in Cardano.Api.Internal.Query. Let's assume they are stored in theexampleProtocolParams
variable. - The draft transaction body, which can be created using
createTransactionBody
defined in Cardano.Api.Internal.Tx.Body:
let (Right txBody) = Api.createTransactionBody sbe txBodyContent
- The number of Byron and Shelley key witnesses, which corresponds to the number of keys required
to sign the transaction. We can estimate this by using
estimateTransactionKeyWitnessCount
. For a simple transaction with a single UTXO locked by a single modern Shelley key, there would be0
Byron witnesses and1
Shelley witness. - The size of any reference scripts in bytes (if any). For simple transactions,
this would be
0
.
With this in mind, it is possible to estimate the fees required by the transaction by calling
evaluateTransactionFee
as follows:
let fees = Api.evaluateTransactionFee sbe exampleProtocolParams txBody 0 1 0
Once we know the required fees, we can balance the transaction by subtracting fees from the total value of the UTXO being spent.
For example, if we have a UTXO with 12 ada, the fees are 0.2 ada, and we want to send 10 ada to an address, the transaction could look like this:
- 1 input of 12 ada (from the UTXO)
- 1 output of 10 ada (to the recipient address)
- 1 output of 1.8 ada (to the change address)
- 0.2 ada in fees (calculated fees, in this case, an overestimation).
We would then have to update the TxBodyContent
accordingly and continue building
the transaction as demonstrated in Cardano.Api.Internal.Experimental.Tx.
Example 2: Automated balancing without chain information (no UTXO, no ledger state)
This method requires more information, but better automates the process, reducing
the need for estimation. It also works with a TxBodyContent
, rather than a
full TxBody
.
The following information is required:
- The MaryEraOnwards witness for the current era. In this case, we use the
one for the
Conway
era:
let meo = Api.MaryEraOnwardsConway
- The draft
TxBodyContent
for the transaction we want to balance. See how to create one in Cardano.Api.Internal.Tx.Body. It is assumed to be stored in thetxBodyContent
variable. - The protocol parameters for the current era, which can be obtained using the
QueryProtocolParameters
query defined in Cardano.Api.Internal.Query. Let's assume they are stored in theexampleProtocolParams
variable. For stake pool and governance actions, we will also need:
- The set of registered stake pools being unregistered in this transaction
- The map of all deposits for stake credentials being unregistered in this transaction
- The map of all deposits for DRep credentials that are unregistered in this transaction
- Plutus script execution units for all script witnesses used in the transaction.
This example assumes we are only spending key-locked UTXOs. Therefore, we can ignore the above
and use mempty
.
The following amounts:
- Collateral amount: required only for transactions involving Plutus scripts. Since
this transaction does not include any, the collateral is
0
. - Amount of Shelley key witnesses to be added: estimated using
estimateTransactionKeyWitnessCount
. For a simple transaction spending a single UTXO locked by a modern Shelley key, there is1
Shelley witness. - Amount of Byron key witnesses to be added: assumed to be
0
for this transaction. - Size of all reference scripts (in bytes): since no reference scripts are used, this value is
0
.
- Collateral amount: required only for transactions involving Plutus scripts. Since
this transaction does not include any, the collateral is
- The address for sending the change. We can deserialize it from its bech32 representation
using the
deserialiseAddress
function defined in Cardano.Api.Internal.Address:
let Just exampleChangeAddress = Api.deserialiseAddress (Api.AsAddressInEra eraAsType) "addr_test1vzpfxhjyjdlgk5c0xt8xw26avqxs52rtf69993j4tajehpcue4v2v"
Alternatively, we can get it from our signing key:
let exampleChangeAddress = Api.shelleyAddressInEra sbe $ Api.makeShelleyAddress (Api.Testnet $ Api.NetworkMagic 2) -- The magic for the network we are using (Api.PaymentCredentialByKey $ Api.verificationKeyHash $ Api.getVerificationKey signingKey) Api.NoStakeAddress -- Potentially, the stake credential if we want to use one
- Finally, we need the total amount of ada (and other tokens) in the UTXOs being spent. In this example, the transaction spends 12 ada:
let totalUTxOValue = Api.lovelaceToValue 12_000_000
With all this information, a balanced transaction can be obtained by calling estimateBalancedTxBody
as follows:
let (Right (Api.BalancedTxBody updatedTxBodyContent updatedTxBody changeOutput fees)) = Api.estimateBalancedTxBody meo txBodyContent exampleProtocolParams mempty mempty mempty mempty 0 1 0 0 exampleChangeAddress
This will produce a balanced transaction body with calculated fees and a change output, but it still needs to be signed and submitted.
Example 3: Fully automated balancing with chain information (requires UTXO and ledger state data)
The previous example required manually providing various details, which was feasible for a simple transaction. However, for more complex transactions involving scripts or advanced functionalities such as governance actions, a more automated approach is available. This method performs most calculations in exchange for general ledger information.
The following details are required:
- Shelley-based era witness for the current era, retrievable using
shelleyBasedEra
.
let sbe :: Api.ShelleyBasedEra Api.ConwayEra = Api.shelleyBasedEra
- Network start time, obtainable using the
QuerySystemStart
query defined in Cardano.Api.Internal.Query. Assume we have it in theexampleSystemStart
variable. - Ledger epoch information, derivable by applying
toLedgerEpochInfo
to theEraHistory
, which can be retrieved using theQueryEraHistory
query defined in Cardano.Api.Internal.Query. Assume this is stored in theexampleLedgerEpochInfo
variable. - Protocol parameters for the current era, accessible through the
QueryProtocolParameters
query defined in Cardano.Api.Internal.Query. Assume this is stored in theexampleProtocolParams
variable. For stake pool and gov actions, additional data is requried:
- The set of registered stake pools being unregistered in this transaction
- The map of all deposits associated with stake credentials being unregistered in this transaction
- The map of all deposits associated with DRep credentials being unregistered in this transaction.
For this example, no stake pool deregistration or governance actions are considered, so mempty
is used
for the corresponding parameters.
- UTXO set being spent -- the full UTXO set can be obtained using the
QueryUTxO
query from Cardano.Api.Internal.Query. Assume this is stored in theutxoToUse
variable. - Draft transaction body content -- the
TxBodyContent
for the transaction that requires balancing. The process for creating this structure is demonstrated in Cardano.Api.Internal.Tx.Body. - Change address -- the address where any remaining balance should be returned. This can be
deserialized from its Bech32 representation using the
deserialiseAddress
function from Cardano.Api.Internal.Address:
let (Just exampleChangeAddress) = Api.deserialiseAddress (Api.AsAddressInEra eraAsType) "addr_test1vzpfxhjyjdlgk5c0xt8xw26avqxs52rtf69993j4tajehpcue4v2v"
Alternatively, it is possible to get it from the signing key:
let exampleChangeAddress = Api.shelleyAddressInEra sbe $ Api.makeShelleyAddress (Api.Testnet $ Api.NetworkMagic 2) -- The magic for the network we are using (Api.PaymentCredentialByKey $ Api.verificationKeyHash $ Api.getVerificationKey signingKey) Api.NoStakeAddress -- Potentially, the stake credential if we want to use one
- Finally, the number of key witnesses required for the transaction can be manually specified.
However, if set to
Nothing
, the function will automatically estimate the required number.
With all the necessary information available, a balanced transaction can be obtained
by calling makeTransactionBodyAutoBalance
as follows:
let Right (Api.BalancedTxBody updatedTxBodyContent updatedTxBody changeOutput fees) = Api.makeTransactionBodyAutoBalance sbe exampleSystemStart exampleLedgerEpochInfo (Api.LedgerProtocolParameters exampleProtocolParams) mempty mempty mempty utxoToUse txBodyContent exampleChangeAddress Nothing
This will give us a balanced transaction with the fees calculated and the change output included. The transaction can now be signed and submitted.
Contents
Transaction fees
evaluateTransactionFee Source #
Arguments
:: ShelleyBasedEra era | |
-> PParams (ShelleyLedgerEra era) | |
-> TxBody era | |
-> Word | The number of Shelley key witnesses |
-> Word | The number of Byron key witnesses |
-> Int | Reference script size in bytes |
-> Coin |
Transaction fees can be computed for a proposed transaction based on the expected number of key witnesses (i.e. signatures).
When possible, use calculateMinTxFee
, as it provides a more accurate
estimate:
Arguments
:: ShelleyBasedEra era | |
-> PParams (ShelleyLedgerEra era) | |
-> UTxO era | |
-> TxBody era | |
-> Word | The number of Shelley key witnesses |
-> Coin |
Estimate the minimum transaction fee by analyzing the transaction structure and determining the required number and type of key witnesses.
It requires access to the relevant portion of the UTXO set to look up any transaction inputs (txins) included in the transaction. However, it cannot reliably determine the number of witnesses required for native scripts.
Therefore, the number of witnesses needed for native scripts must be provided as an additional argument.
estimateTransactionKeyWitnessCount :: TxBodyContent BuildTx era -> Word Source #
Provide and approximate count of the key witnesses (i.e. signatures) required for a transaction.
This estimate is not exact and may overestimate the required number of witnesses. The function makes conservative assumptions, including:
- Treating all inputs as originating from distinct addresses. In reality, multiple inputs may share the same address, requiring only one witness per address.
- Assuming regular and collateral inputs are distinct, even though they may overlap.
TODO: Consider implementing a more precise calculation that leverages the UTXO set to determine which inputs correspond to distinct addresses. Additionally, the estimate can be refined by distinguishing between Shelley and Byron-style witnesses.
Script execution units
evaluateTransactionExecutionUnits :: CardanoEra era -> SystemStart -> LedgerEpochInfo -> LedgerProtocolParameters era -> UTxO era -> TxBody era -> Either (TransactionValidityError era) (Map ScriptWitnessIndex (Either ScriptExecutionError (EvalTxExecutionUnitsLog, ExecutionUnits))) Source #
Compute the ExecutionUnits
required for each script in the transaction.
This process involves executing all scripts and counting the actual execution units consumed.
evaluateTransactionExecutionUnitsShelley :: ShelleyBasedEra era -> SystemStart -> LedgerEpochInfo -> LedgerProtocolParameters era -> UTxO era -> Tx (ShelleyLedgerEra era) -> Either (TransactionValidityError era) (Map ScriptWitnessIndex (Either ScriptExecutionError (EvalTxExecutionUnitsLog, ExecutionUnits))) Source #
data ScriptExecutionError Source #
This data type represents the possible reasons for a script’s execution
failure, as reported by the evaluateTransactionExecutionUnits
function.
The first three errors relate to issues before executing the script, while the last two arise during script execution.
TODO: Consider replacing ScriptWitnessIndex
with the ledger’s PlutusPurpose
AsIx ledgerera
. This change would require parameterizing the
ScriptExecutionError
.
Constructors
ScriptErrorMissingTxIn TxIn | The script depends on a |
ScriptErrorTxInWithoutDatum TxIn | The |
ScriptErrorWrongDatum (Hash ScriptData) | The |
ScriptErrorEvaluationFailed DebugPlutusFailure | The script evaluation failed. This usually means it evaluated to an
error value. This is not a case of running out of execution units
(which is not possible for |
ScriptErrorExecutionUnitsOverflow | The execution units overflowed a 64bit word. Congratulations if you encounter this error. With the current style of cost model this would need a script to run for over 7 months, which is somewhat more than the expected maximum of a few milliseconds. |
ScriptErrorNotPlutusWitnessedTxIn ScriptWitnessIndex ScriptHash | An attempt was made to spend a key witnessed tx input with a script witness. |
ScriptErrorRedeemerPointsToUnknownScriptHash ScriptWitnessIndex | The redeemer pointer points to a script hash that does not exist in the transaction nor in the UTxO as a reference script" |
ScriptErrorMissingScript ScriptWitnessIndex ResolvablePointers | A redeemer pointer points to a script that does not exist. |
ScriptErrorMissingCostModel Language | A cost model was missing for a language which was used. |
(EraPlutusContext (ShelleyLedgerEra era), Show (ContextError (ShelleyLedgerEra era))) => ScriptErrorTranslationError (ContextError (ShelleyLedgerEra era)) |
Instances
Show ScriptExecutionError Source # | |
Defined in Cardano.Api.Internal.Fees | |
Error ScriptExecutionError Source # | |
Defined in Cardano.Api.Internal.Fees Methods prettyError :: ScriptExecutionError -> Doc ann Source # |
data TransactionValidityError era where Source #
Constructors
TransactionValidityIntervalError :: forall era. PastHorizonException -> TransactionValidityError era | The transaction validity interval is too far into the future. Transactions containing Plutus scripts must have a validity interval that is not excessively far in the future. This ensures that the UTC corresponding to the validity interval expressed in slot numbers, can be reliably determined. Plutus scripts are given the transaction validity interval in UTC to prevent sensitivity to variations in slot lengths. If either end of the validity interval exceeds the "time horizon", the consensus algorithm cannot reliably establish the relationship between slots and time. This error occurs when thevalidity interval exceeds the time horizon. For the Cardano mainnet, the time horizon is set to 36 hours beyond the current time. This effectively restricts the submission and validation of transactions that include Plutus scripts if the end of their validity interval extends more than 36 hours into the future. |
TransactionValidityCostModelError :: forall era. Map AnyPlutusScriptVersion CostModel -> String -> TransactionValidityError era |
Instances
Show (TransactionValidityError era) Source # | |
Defined in Cardano.Api.Internal.Fees | |
Error (TransactionValidityError era) Source # | |
Defined in Cardano.Api.Internal.Fees Methods prettyError :: TransactionValidityError era -> Doc ann Source # |
Transaction balance
evaluateTransactionBalance :: ShelleyBasedEra era -> PParams (ShelleyLedgerEra era) -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> UTxO era -> TxBody era -> TxOutValue era Source #
Compute the total balance of the proposed transaction. Ultimately, a valid transaction must be fully balanced, which means that it has a total value of zero.
Finding the (non-zero) balance of a partially constructed transaction is useful for adjusting a transaction to be fully balanced.
Automated transaction building
estimateBalancedTxBody Source #
Arguments
:: HasCallStack | |
=> MaryEraOnwards era | |
-> TxBodyContent BuildTx era | |
-> PParams (ShelleyLedgerEra era) | |
-> Set PoolId | The set of registered stake pools, being unregistered in this transaction. |
-> Map StakeCredential Coin | A map of all deposits for stake credentials that are being unregistered in this transaction. |
-> Map (Credential 'DRepRole StandardCrypto) Coin | A map of all deposits for DRep credentials that are being unregistered in this transaction. |
-> Map ScriptWitnessIndex ExecutionUnits | Plutus script execution units. |
-> Coin | Total potential collateral amount. |
-> Int | The number of key witnesses to be added to the transaction. |
-> Int | The number of Byron key witnesses to be added to the transaction. |
-> Int | The size of all reference scripts in bytes. |
-> AddressInEra era | Change address. |
-> Value | Total value of UTXOs being spent. |
-> Either (TxFeeEstimationError era) (BalancedTxBody era) |
Use when you do not have access to the UTxOs you intend to spend
estimateOrCalculateBalancedTxBody :: ShelleyBasedEra era -> FeeEstimationMode era -> PParams (ShelleyLedgerEra era) -> TxBodyContent BuildTx era -> Set PoolId -> Map StakeCredential Coin -> Map (Credential 'DRepRole StandardCrypto) Coin -> AddressInEra era -> Either (AutoBalanceError era) (BalancedTxBody era) Source #
makeTransactionBodyAutoBalance Source #
Arguments
:: HasCallStack | |
=> ShelleyBasedEra era | |
-> SystemStart | |
-> LedgerEpochInfo | |
-> LedgerProtocolParameters era | |
-> Set PoolId | The set of registered stake pools, being unregistered in this transaction. |
-> Map StakeCredential Coin | The map of all deposits for stake credentials that are being unregistered in this transaction |
-> Map (Credential 'DRepRole StandardCrypto) Coin | The map of all deposits for DRep credentials that are being unregistered in this transaction |
-> UTxO era | The transaction inputs (including reference and collateral ones), not the entire |
-> TxBodyContent BuildTx era | |
-> AddressInEra era | Change address |
-> Maybe Word | Override key witnesses |
-> Either (TxBodyErrorAutoBalance era) (BalancedTxBody era) |
This is similar to makeTransactionBody
but with greater automation to
calculate suitable values for several things.
In particular:
- It calculates the correct script
ExecutionUnits
(ignoring the provided values, which can thus be zero). - It calculates the transaction fees based on the script
ExecutionUnits
, the currentProtocolParameters
, and an estimate of the number of key witnesses (i.e. signatures). There is an override for the number of key witnesses. - It accepts a change address, calculates the balance of the transaction and puts the excess change into the change output.
- It also checks that the balance is positive and the change is above the minimum threshold.
To do this, it requires more information than makeTransactionBody
, all of
which can be queried from a local node.
calcReturnAndTotalCollateral Source #
Arguments
:: AlonzoEraPParams (ShelleyLedgerEra era) | |
=> BabbageEraOnwards era | |
-> Coin | Fee |
-> PParams (ShelleyLedgerEra era) | |
-> TxInsCollateral era | From the initial TxBodyContent |
-> TxReturnCollateral CtxTx era | From the initial TxBodyContent |
-> TxTotalCollateral era | From the initial TxBodyContent |
-> AddressInEra era | Change address |
-> Value (ShelleyLedgerEra era) | Total available collateral (can include non-ada) |
-> (TxReturnCollateral CtxTx era, TxTotalCollateral era) |
data AutoBalanceError era Source #
Constructors
AutoBalanceEstimationError (TxFeeEstimationError era) | |
AutoBalanceCalculationError (TxBodyErrorAutoBalance era) |
Instances
Show (AutoBalanceError era) Source # | |
Defined in Cardano.Api.Internal.Fees | |
Error (AutoBalanceError era) Source # | |
Defined in Cardano.Api.Internal.Fees Methods prettyError :: AutoBalanceError era -> Doc ann Source # |
data BalancedTxBody era Source #
Constructors
BalancedTxBody | |
Instances
IsShelleyBasedEra era => Show (BalancedTxBody era) Source # | |
Defined in Cardano.Api.Internal.Fees |
data FeeEstimationMode era Source #
Constructors
CalculateWithSpendableUTxO | Accurate fee calculation. |
Fields
| |
EstimateWithoutSpendableUTxO | Less accurate fee estimation. |
Fields
|
newtype RequiredShelleyKeyWitnesses Source #
Constructors
RequiredShelleyKeyWitnesses | |
Fields |
Instances
newtype RequiredByronKeyWitnesses Source #
Constructors
RequiredByronKeyWitnesses | |
Fields |
Instances
newtype TotalReferenceScriptsSize Source #
Constructors
TotalReferenceScriptsSize | |
Fields |
Instances
data TxBodyErrorAutoBalance era Source #
The possible errors that can arise from makeTransactionBodyAutoBalance
.
Constructors
TxBodyError TxBodyError | The same errors that can arise from |
TxBodyScriptExecutionError [(ScriptWitnessIndex, ScriptExecutionError)] | One or more scripts failed to execute correctly. |
TxBodyScriptBadScriptValidity | One or more scripts were expected to fail validation, but none did. |
TxBodyErrorAdaBalanceNegative Coin | There is not enough ada to cover both the outputs and the fees. The transaction should be changed to provide more input ada, or otherwise adjusted to need less (e.g. outputs, script etc). |
TxBodyErrorAdaBalanceTooSmall | There is enough ada to cover both the outputs and the fees, but the resulting change is too small: it is under the minimum value for new UTXO entries. The transaction should be changed to provide more input ada. |
Fields
| |
TxBodyErrorByronEraNotSupported |
|
TxBodyErrorMissingParamMinUTxO | The |
TxBodyErrorValidityInterval (TransactionValidityError era) | The transaction validity interval is too far into the future.
See |
TxBodyErrorMinUTxONotMet | The minimum spendable UTxO threshold has not been met. |
Fields
| |
TxBodyErrorNonAdaAssetsUnbalanced Value | |
TxBodyErrorScriptWitnessIndexMissingFromExecUnitsMap ScriptWitnessIndex (Map ScriptWitnessIndex ExecutionUnits) |
Instances
Show (TxBodyErrorAutoBalance era) Source # | |
Defined in Cardano.Api.Internal.Fees | |
Error (TxBodyErrorAutoBalance era) Source # | |
Defined in Cardano.Api.Internal.Fees Methods prettyError :: TxBodyErrorAutoBalance era -> Doc ann Source # |
data TxFeeEstimationError era Source #
Constructors
Instances
Show (TxFeeEstimationError era) Source # | |
Defined in Cardano.Api.Internal.Fees | |
Error (TxFeeEstimationError era) Source # | |
Defined in Cardano.Api.Internal.Fees Methods prettyError :: TxFeeEstimationError era -> Doc ann Source # |
Minimum UTxO calculation
calculateMinimumUTxO :: HasCallStack => ShelleyBasedEra era -> TxOut CtxTx era -> PParams (ShelleyLedgerEra era) -> Coin Source #
Internal helpers
data ResolvablePointers where Source #
Constructors
ResolvablePointers :: forall era. (Era (ShelleyLedgerEra era), Show (PlutusPurpose AsIx (ShelleyLedgerEra era)), Show (PlutusPurpose AsItem (ShelleyLedgerEra era)), Show (PlutusScript (ShelleyLedgerEra era))) => ShelleyBasedEra era -> !(Map (PlutusPurpose AsIx (ShelleyLedgerEra era)) (PlutusPurpose AsItem (ShelleyLedgerEra era), Maybe (PlutusScriptBytes, Language), ScriptHash StandardCrypto)) -> ResolvablePointers |
Instances
Show ResolvablePointers Source # | |
Defined in Cardano.Api.Internal.Fees |