Skip to content

Commit

Permalink
Move to PParams
Browse files Browse the repository at this point in the history
  • Loading branch information
berewt committed Nov 29, 2022
1 parent 59b7ef3 commit 280bf33
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 34 deletions.
Expand Up @@ -307,7 +307,7 @@ handleAdjustUnbalancedTx =
RequestHandler $ \utx ->
surroundDebug @Text "handleAdjustUnbalancedTx" $ do
params <- Wallet.Effects.getClientParams
forM (adjustUnbalancedTx params utx) $ \(missingAdaCosts, adjusted) -> do
forM (adjustUnbalancedTx (emulatorPParams params) utx) $ \(missingAdaCosts, adjusted) -> do
logDebug $ AdjustingUnbalancedTx missingAdaCosts
pure adjusted

Expand Down
3 changes: 2 additions & 1 deletion plutus-contract/src/Wallet/API.hs
Expand Up @@ -132,7 +132,8 @@ payToAddress params range v addr = do
utx <- either (throwError . PaymentMkTxError)
pure
(Constraints.mkTxWithParams @Void params mempty constraints)
(missingAdaCosts, adjustedUtx) <- either (throwError . ToCardanoError) pure (adjustUnbalancedTx params utx)
(missingAdaCosts, adjustedUtx) <- either (throwError . ToCardanoError) pure
(adjustUnbalancedTx (emulatorPParams params) utx)
logDebug $ AdjustingUnbalancedTx missingAdaCosts
unless (utx == adjustedUtx) $
logWarn @Text $ "Wallet.API.payToPublicKeyHash: "
Expand Down
2 changes: 1 addition & 1 deletion plutus-contract/src/Wallet/Emulator/MultiAgent.hs
Expand Up @@ -312,7 +312,7 @@ emulatorStateInitialDist params mp = do
mMinAdaTxOut = do
let k = fst $ head $ Map.toList mp
emptyTxOut <- toCardanoTxOut (pNetworkId params) $ mkOutput k mempty
pure $ minAdaTxOut params (TxOut emptyTxOut)
pure $ minAdaTxOut (emulatorPParams params) (TxOut emptyTxOut)
-- See [Creating wallets with multiple outputs]
mkOutputs minAda (key, vl) = mkOutput key <$> splitInto10 vl minAda
splitInto10 vl minAda = if count <= 1
Expand Down
2 changes: 1 addition & 1 deletion plutus-contract/src/Wallet/Emulator/Wallet.hs
Expand Up @@ -507,7 +507,7 @@ calculateTxChanges addr utxos (neg, pos) = do
$ toCardanoTxOut (pNetworkId params) $ PV2.TxOut addr pos PV2.NoOutputDatum Nothing
(missing, extraTxOut) <-
either (throwError . WAPI.ToCardanoError) pure
$ U.adjustTxOut params txOut
$ U.adjustTxOut (emulatorPParams params) txOut
let missingValue = Ada.toValue (fold missing)
-- Add the missing ada to both sides to keep the balance.
pure (neg <> missingValue, pos <> missingValue, Just extraTxOut)
Expand Down
9 changes: 4 additions & 5 deletions plutus-ledger-constraints/src/Ledger/Constraints/OffChain.hs
Expand Up @@ -123,15 +123,14 @@ import Ledger.Constraints.TxConstraints (ScriptInputConstraint (ScriptInputConst
import Ledger.Crypto (pubKeyHash)
import Ledger.Index (minAdaTxOut)
import Ledger.Orphans ()
import Ledger.Params (Params (pNetworkId, pSlotConfig))
import Ledger.Params (PParams, Params (pNetworkId, pSlotConfig))
import Ledger.TimeSlot (posixTimeRangeToContainedSlotRange)
import Ledger.Tx (DecoratedTxOut, Language (PlutusV1, PlutusV2), ReferenceScript, TxOut (TxOut), TxOutRef,
Versioned (Versioned), txOutValue)
import Ledger.Tx qualified as Tx
import Ledger.Tx.CardanoAPI qualified as C
import Ledger.Typed.Scripts (Any, ConnectionError (UnknownRef), TypedValidator (tvValidator, tvValidatorHash),
ValidatorTypes (DatumType, RedeemerType), validatorAddress)
import Ledger.Validation (evaluateMinLovelaceOutput, fromPlutusTxOut)
import Plutus.Script.Utils.Scripts qualified as P
import Plutus.Script.Utils.V2.Typed.Scripts qualified as Typed
import Plutus.V1.Ledger.Api (Datum (Datum), DatumHash, StakingCredential, Validator (getValidator), Value,
Expand Down Expand Up @@ -561,17 +560,17 @@ mkTxWithParams params lookups txc = mkSomeTx params [SomeLookupsAndConstraints l

-- | Each transaction output should contain a minimum amount of Ada (this is a
-- restriction on the real Cardano network).
adjustUnbalancedTx :: Params -> UnbalancedTx -> Either Tx.ToCardanoError ([Ada.Ada], UnbalancedTx)
adjustUnbalancedTx :: PParams -> UnbalancedTx -> Either Tx.ToCardanoError ([Ada.Ada], UnbalancedTx)
adjustUnbalancedTx params = alaf Compose (tx . Tx.outputs . traverse) (adjustTxOut params)

-- | Adjust a single transaction output so it contains at least the minimum amount of Ada
-- and return the adjustment (if any) and the updated TxOut.
adjustTxOut :: Params -> TxOut -> Either Tx.ToCardanoError ([Ada.Ada], TxOut)
adjustTxOut :: PParams -> TxOut -> Either Tx.ToCardanoError ([Ada.Ada], TxOut)
adjustTxOut params txOut = do
-- Increasing the ada amount can also increase the size in bytes, so start with a rough estimated amount of ada
withMinAdaValue <- C.toCardanoTxOutValue $ txOutValue txOut \/ Ada.toValue (minAdaTxOut params txOut)
let txOutEstimate = txOut & outValue .~ withMinAdaValue
minAdaTxOutEstimated' = evaluateMinLovelaceOutput params (fromPlutusTxOut txOutEstimate)
minAdaTxOutEstimated' = minAdaTxOut params txOutEstimate
missingLovelace = minAdaTxOutEstimated' - Ada.fromValue (txOutValue txOut)
if missingLovelace > 0
then do
Expand Down
Expand Up @@ -12,7 +12,7 @@ Uncomment the section that is right (remove the HTML comment wrapper).
-->
### Added

- `minAdaTxOut`, computes the minimum amount of Ada requires for a `TxOut` more
- `minAdaTxOut`, computes the minimum amount of Ada required for a `TxOut` more
precisely, by taking the params and the `TxOut`.

### Changed
Expand Down
31 changes: 17 additions & 14 deletions plutus-ledger/src/Ledger/Index.hs
Expand Up @@ -49,7 +49,7 @@ import Ledger.Ada qualified as Ada
import Ledger.Blockchain
import Ledger.Index.Internal
import Ledger.Orphans ()
import Ledger.Params (Params (emulatorPParams))
import Ledger.Params (PParams)
import Ledger.Tx (CardanoTx (..), Tx, TxIn (TxIn, txInType), TxInType (ConsumePublicKeyAddress, ScriptAddress),
TxOut (getTxOut), TxOutRef, outValue, txOutValue, updateUtxoCollateral)
import Ledger.Tx.CardanoAPI (toCardanoTxOutValue)
Expand Down Expand Up @@ -97,12 +97,14 @@ the blockchain.
-}

-- | Exact computation of the mimimum Ada required for a given TxOut.
minAdaTxOut :: Params -> TxOut -> Ada
-- TODO: Should be moved to cardano-api-extended once created
minAdaTxOut :: PParams -> TxOut -> Ada

minAdaTxOut params txOut = let
toAda = lovelaceOf . C.Ledger.unCoin
initialValue = txOutValue txOut
fromPlutusTxOut = C.Api.toShelleyTxOut C.Api.ShelleyBasedEraBabbage . C.Api.toCtxUTxOTxOut . getTxOut
firstEstimate = toAda . C.Ledger.evaluateMinLovelaceOutput (emulatorPParams params) $ fromPlutusTxOut txOut
firstEstimate = toAda . C.Ledger.evaluateMinLovelaceOutput params $ fromPlutusTxOut txOut
in -- if the estimate is above the initialValue, we run minAdaAgain, just to be sure that the
-- new amount didn't change the TxOut size and requires more ada.
if firstEstimate > fromValue initialValue
Expand All @@ -115,17 +117,18 @@ minAdaTxOut params txOut = let
-- minAdaTxOutParams

{-# INLINABLE minAdaTxOutEstimated #-}
-- | Provide a reasonable estimate of the mimimum of Ada required for a TxOut.
--
-- An exact estimate of the the mimimum of Ada in a TxOut is determined by two things:
-- - the `PParams`, more precisely its 'coinPerUTxOWord' parameter.
-- - the size of the 'TxOut'.
-- In many situations though, we need to determine a plausible value for the minimum of Ada needed for a TxOut
-- without knowing much of the 'TxOut'.
-- This function provides a value big enough to balance UTxOs without
-- a large inlined data (larger than a hash) nor a complex val with a lot of minted values.
-- It's superior to the lowest minimum needed for an UTxO, as the lowest value require no datum.
-- An estimate of the minimum required Ada for each tx output.
{- | Provide a reasonable estimate of the mimimum of Ada required for a TxOut.
An exact estimate of the the mimimum of Ada in a TxOut is determined by two things:
- the `PParams`, more precisely its 'coinPerUTxOWord' parameter.
- the size of the 'TxOut'.
In many situations though, we need to determine a plausible value for the minimum of Ada needed for a TxOut
without knowing much of the 'TxOut'.
This function provides a value big enough to balance UTxOs without
a large inlined data (larger than a hash) nor a complex val with a lot of minted values.
It's superior to the lowest minimum needed for an UTxO, as the lowest value require no datum.
An estimate of the minimum required Ada for each tx output.
-}
minAdaTxOutEstimated :: Ada
minAdaTxOutEstimated = Ada.lovelaceOf minTxOut

Expand Down
8 changes: 0 additions & 8 deletions plutus-ledger/src/Ledger/Validation.hs
Expand Up @@ -16,7 +16,6 @@ module Ledger.Validation(
EmulatorEra,
CardanoLedgerError,
initialState,
evaluateMinLovelaceOutput,
getRequiredSigners,
hasValidationErrors,
makeTransactionBody,
Expand Down Expand Up @@ -84,7 +83,6 @@ import Data.Sequence.Strict (StrictSeq)
import Data.Set (Set)
import Data.Text qualified as Text
import GHC.Records (HasField (..))
import Ledger.Ada qualified as P
import Ledger.Address qualified as P
import Ledger.Crypto qualified as Crypto
import Ledger.Index.Internal qualified as P
Expand Down Expand Up @@ -308,12 +306,6 @@ makeTransactionBody params utxo txBodyContent = do
first Right $ P.makeTransactionBody (Just $ emulatorPParams params) exUnits txBodyContent


evaluateMinLovelaceOutput :: P.Params -> TxOut EmulatorEra -> P.Ada
evaluateMinLovelaceOutput params = toPlutusValue . C.Ledger.evaluateMinLovelaceOutput (emulatorPParams params)
where
toPlutusValue :: Coin -> P.Ada
toPlutusValue (Coin c) = P.lovelaceOf c

fromPlutusTxSigned'
:: P.Params
-> UTxO EmulatorEra
Expand Down
5 changes: 3 additions & 2 deletions plutus-pab-executables/tx-inject/Main.hs
Expand Up @@ -18,6 +18,7 @@ import Control.Lens hiding (ix)
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO)
import Control.RateLimit (rateLimitExecution)
import Data.Default (Default (def))
import Data.Map qualified as Map
import Data.Text (Text)
import Data.Text qualified as T
Expand All @@ -35,7 +36,7 @@ import Text.Pretty.Simple (pPrint)
import Cardano.Node.Types (PABServerConfig (..))
import Cardano.Protocol.Socket.Mock.Client (TxSendHandle (..), queueTx, runTxSender)
import Data.Either (fromRight)
import Ledger (testnet)
import Ledger (Params (pNetworkId), testnet)
import Ledger.Ada qualified as Ada
import Ledger.Blockchain (OnChainTx (..))
import Ledger.Index (UtxoIndex (..), insertBlock)
Expand Down Expand Up @@ -76,7 +77,7 @@ initialUtxoIndex config =
(repeat (Ada.adaValueOf 1000_000_000))
initialTxs =
view (chainState . txPool) $ fromRight (error "cannot initialize chain state") $
emulatorStateInitialDist testnet $
emulatorStateInitialDist (def {pNetworkId = testnet}) $
Map.mapKeys mockWalletPaymentPubKeyHash dist
in insertBlock (map Valid initialTxs) (UtxoIndex Map.empty)

Expand Down

0 comments on commit 280bf33

Please sign in to comment.