Skip to content

Commit

Permalink
Apply suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
klntsky committed Apr 29, 2024
1 parent caf238b commit adf54bf
Show file tree
Hide file tree
Showing 18 changed files with 108 additions and 134 deletions.
1 change: 0 additions & 1 deletion src/Contract/Time.purs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ import Ctl.Internal.Types.Interval
, after
, always
, before
, beginningOfTime
, contains
, findSlotEraSummary
, findTimeEraSummary
Expand Down
13 changes: 6 additions & 7 deletions src/Internal/BalanceTx/BalanceTx.purs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ import Ctl.Internal.Contract.Wallet
, getWalletCollateral
, getWalletUtxos
) as Wallet
import Ctl.Internal.Helpers (liftEither, pprintTagSet, (??))
import Ctl.Internal.Helpers (liftEither, pprintTagSet, unsafeFromJust, (??))
import Ctl.Internal.Lens
( _amount
, _body
Expand Down Expand Up @@ -158,7 +158,7 @@ import Data.Map
, toUnfoldable
, union
) as Map
import Data.Maybe (Maybe(Just, Nothing), fromJust, isJust, maybe)
import Data.Maybe (Maybe(Just, Nothing), isJust, maybe)
import Data.Newtype (unwrap, wrap)
import Data.Set (Set)
import Data.Set as Set
Expand All @@ -177,7 +177,7 @@ balanceTxWithConstraints
-> Map TransactionInput TransactionOutput
-> BalanceTxConstraintsBuilder
-> Contract (Either BalanceTxError Transaction)
balanceTxWithConstraints transaction_ extraUtxos constraintsBuilder = do
balanceTxWithConstraints transaction extraUtxos constraintsBuilder = do

pparams <- getProtocolParameters

Expand Down Expand Up @@ -263,8 +263,6 @@ balanceTxWithConstraints transaction_ extraUtxos constraintsBuilder = do
getChangeAddress = maybe (liftContract Wallet.getChangeAddress) pure
=<< asksConstraints Constraints._changeAddress

transaction = transaction_ -- # _redeemers .~ [] # _transaction <<< _body <<< _mint .~ Nothing

transactionWithNetworkId :: BalanceTxM Transaction
transactionWithNetworkId = do
networkId <- maybe askNetworkId pure
Expand Down Expand Up @@ -756,8 +754,9 @@ assignCoinsToChangeValues
-> NonEmptyArray (Value /\ BigInt)
-> BalanceTxM (Array Value)
assignCoinsToChangeValues changeAddress adaAvailable pairsAtStart =
unsafePartial $ changeValuesAtStart <#> \changeValues ->
fromJust <<< Val.toValue <$> worker (adaRequiredAtStart changeValues)
changeValuesAtStart <#> \changeValues ->
unsafeFromJust "assignCoinsToChangeValues" <<< Val.toValue <$> worker
(adaRequiredAtStart changeValues)
changeValues
where
worker :: BigInt -> NonEmptyArray ChangeValue -> Array Val
Expand Down
17 changes: 6 additions & 11 deletions src/Internal/BalanceTx/CoinSelection.purs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,12 @@ import Cardano.Types.AssetClass (AssetClass(AssetClass))
import Cardano.Types.AssetName (unAssetName)
import Cardano.Types.TransactionInput (TransactionInput)
import Cardano.Types.UtxoMap (UtxoMap)
import Cardano.Types.Value as Value
import Control.Monad.Error.Class (class MonadThrow, throwError)
import Ctl.Internal.BalanceTx.Error
( Actual(Actual)
, BalanceTxError
( BalanceInsufficientError
, InsufficientUtxoBalanceToCoverAsset
( BalanceTxError
( InsufficientUtxoBalanceToCoverAsset
, BalanceInsufficientError
)
, Expected(Expected)
)
import Ctl.Internal.CoinSelection.UtxoIndex
( SelectionFilter(SelectSingleton, SelectPairWith, SelectAnyWith)
Expand Down Expand Up @@ -122,16 +119,14 @@ performMultiAssetSelection
-> m SelectionState
performMultiAssetSelection strategy utxoIndex requiredValue = do
case requiredValue `Val.leq` availableValue of
true -> do
true ->
runRoundRobinM (mkSelectionState utxoIndex) selectors
false -> do
false ->
throwError balanceInsufficientError
where
balanceInsufficientError :: BalanceTxError
balanceInsufficientError =
BalanceInsufficientError
(Expected Value.empty) -- $ unsafePartial $ fromJust $ Val.toValue requiredValue)
(Actual Value.empty) -- $ unsafePartial $ fromJust $ Val.toValue availableValue)
BalanceInsufficientError requiredValue availableValue

availableValue :: Val
availableValue = balance (utxoIndexUniverse utxoIndex)
Expand Down
18 changes: 3 additions & 15 deletions src/Internal/BalanceTx/Collateral/Select.purs
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,19 @@ import Cardano.Types.UtxoMap (UtxoMap)
import Cardano.Types.Value as Value
import Ctl.Internal.BalanceTx.FakeOutput (fakeOutputWithMultiAssets)
import Ctl.Internal.BalanceTx.UtxoMinAda (utxoMinAdaValue)
import Ctl.Internal.Helpers (bugTrackerLink)
import Ctl.Internal.Helpers (unsafeFromJust)
import Data.Array as Array
import Data.Foldable (foldl)
import Data.Function (on)
import Data.List (List(Nil, Cons))
import Data.List as List
import Data.Map (toUnfoldable) as Map
import Data.Maybe (Maybe(Just, Nothing))
import Data.Maybe (Maybe)
import Data.Newtype (class Newtype, unwrap, wrap)
import Data.Ordering (invert) as Ordering
import Data.Tuple (Tuple(Tuple))
import Data.Tuple (fst, snd) as Tuple
import Data.Tuple.Nested (type (/\), (/\))
import Effect.Exception (throw)
import Effect.Unsafe (unsafePerformEffect)

minRequiredCollateral :: Coin
minRequiredCollateral = wrap $ BigNum.fromInt 5_000_000
Expand Down Expand Up @@ -164,19 +162,9 @@ adaValue =
Value.getCoin <<< _.amount <<< unwrap <<< _.output <<< unwrap

consumeUtxoAdaValue :: Coin -> TransactionUnspentOutput -> Coin
consumeUtxoAdaValue acc = unsafeFromMaybe "consumeUtxoAdaValue" <<< Coin.add acc
consumeUtxoAdaValue acc = unsafeFromJust "consumeUtxoAdaValue" <<< Coin.add acc
<<< adaValue

unsafeFromMaybe :: forall a. String -> Maybe a -> a
unsafeFromMaybe e a = case a of
Nothing ->
unsafePerformEffect $ throw $ "unsafeFromMaybe: impossible happened: "
<> e
<> " (please report as bug at "
<> bugTrackerLink
<> " )"
Just v -> v

nonAdaAsset :: TransactionUnspentOutput -> MultiAsset
nonAdaAsset =
Value.getMultiAsset <<< _.amount <<< unwrap <<< _.output <<< unwrap
Expand Down
22 changes: 11 additions & 11 deletions src/Internal/BalanceTx/Error.purs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import Cardano.Types.BigNum as BigNum
import Cardano.Types.TransactionInput (TransactionInput)
import Cardano.Types.TransactionOutput (TransactionOutput)
import Cardano.Types.UtxoMap (UtxoMap, pprintUtxoMap)
import Cardano.Types.Value (Value, pprintValue)
import Cardano.Types.Value (Value)
import Ctl.Internal.BalanceTx.RedeemerIndex (UnindexedRedeemer)
import Ctl.Internal.Helpers (bugTrackerLink, pprintTagSet)
import Ctl.Internal.Lens (_redeemers, _witnessSet)
Expand All @@ -49,18 +49,18 @@ import Ctl.Internal.QueryM.Ogmios
)
, TxEvaluationFailure(UnparsedError, AdditionalUtxoOverlap, ScriptFailures)
) as Ogmios
import Ctl.Internal.Types.Val (Val)
import Ctl.Internal.Types.Val (Val, pprintVal)
import Data.Array (catMaybes, filter, uncons) as Array
import Data.Bifunctor (bimap)
import Data.Either (Either(Left, Right), either, isLeft)
import Data.Foldable (find, foldMap, foldl, length)
import Data.Foldable (find, fold, foldMap, foldl, length)
import Data.FoldableWithIndex (foldMapWithIndex)
import Data.Function (applyN)
import Data.Generic.Rep (class Generic)
import Data.Int (ceil, decimal, toNumber, toStringAs)
import Data.Lens ((^.))
import Data.Maybe (Maybe(Just, Nothing))
import Data.Newtype (class Newtype, unwrap)
import Data.Newtype (class Newtype)
import Data.Show.Generic (genericShow)
import Data.String (Pattern(Pattern))
import Data.String.CodePoints (length) as String
Expand All @@ -71,7 +71,7 @@ import JS.BigInt as BigInt

-- | Errors conditions that may possibly arise during transaction balancing
data BalanceTxError
= BalanceInsufficientError Expected Actual
= BalanceInsufficientError Val Val
| CouldNotConvertScriptOutputToTxInput
| CouldNotGetCollateral
| InsufficientCollateralUtxos UtxoMap
Expand All @@ -93,9 +93,9 @@ instance Show BalanceTxError where
explainBalanceTxError :: BalanceTxError -> String
explainBalanceTxError = case _ of
BalanceInsufficientError expected actual ->
"Insufficient balance. " <> prettyValue "Expected" (unwrap expected)
"Insufficient balance. " <> prettyVal "Expected" expected
<> ", "
<> prettyValue "actual" (unwrap actual)
<> prettyVal "Actual" actual
InsufficientCollateralUtxos utxos ->
"Could not cover collateral requirements. " <>
pprintTagSet "UTxOs for collateral selection:" (pprintUtxoMap utxos)
Expand Down Expand Up @@ -138,11 +138,11 @@ explainBalanceTxError = case _ of
UtxoMinAdaValueCalculationFailed ->
"Could not calculate min ADA for UTxO"
NumericOverflowError mbVal ->
"Could not compute output value due to numeric overflow. Decrease the quantity of assets. Value: "
<> show mbVal
"Could not compute output value due to numeric overflow. Decrease the quantity of assets. "
<> fold (prettyVal "Value:" <$> mbVal)
where
prettyValue :: String -> Value -> String
prettyValue str = pprintValue >>> pprintTagSet str
prettyVal :: String -> Val -> String
prettyVal str = pprintVal >>> pprintTagSet str

newtype Actual = Actual Value

Expand Down
12 changes: 12 additions & 0 deletions src/Internal/Helpers.purs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ module Ctl.Internal.Helpers
, compareViaCslBytes
, decodeMap
, decodeTaggedNewtype
, unsafeFromJust
) where

import Prelude
Expand Down Expand Up @@ -88,6 +89,7 @@ import Effect (Effect)
import Effect.Class (class MonadEffect)
import Effect.Class.Console (log)
import Effect.Exception (throw)
import Effect.Unsafe (unsafePerformEffect)
import Foreign.Object (Object)
import Foreign.Object as Obj
import JS.BigInt (BigInt)
Expand Down Expand Up @@ -372,3 +374,13 @@ showFromCbor typeName a = "(" <> typeName
<> " $ unsafePartial $ fromJust $ decodeCbor $ CborBytes $ "
<> show (toBytes a)
<> ")"

unsafeFromJust :: forall a. String -> Maybe a -> a
unsafeFromJust e a = case a of
Nothing ->
unsafePerformEffect $ throw $ "unsafeFromJust: impossible happened: "
<> e
<> " (please report as bug at "
<> bugTrackerLink
<> " )"
Just v -> v
31 changes: 16 additions & 15 deletions src/Internal/Partition.purs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Cardano.Types.MultiAsset (MultiAsset)
import Cardano.Types.MultiAsset as MultiAsset
import Cardano.Types.ScriptHash (ScriptHash)
import Cardano.Types.Value (Value(Value))
import Ctl.Internal.Helpers (unsafeFromJust)
import Data.Array (replicate)
import Data.Array.NonEmpty (NonEmptyArray)
import Data.Array.NonEmpty
Expand All @@ -30,7 +31,7 @@ import Data.Array.NonEmpty
) as NEArray
import Data.Foldable (any, foldl, length, sum)
import Data.Function (on)
import Data.Maybe (Maybe(Just, Nothing), fromJust)
import Data.Maybe (Maybe(Just, Nothing))
import Data.Newtype (class Newtype, unwrap, wrap)
import Data.Ordering (invert) as Ordering
import Data.Tuple (fst, snd)
Expand All @@ -46,7 +47,8 @@ class Partition (a :: Type) where
instance Partition BigNum where
partition bigNum = unsafePartial $ map BigNum.toBigInt
>>> partition (BigNum.toBigInt bigNum)
>>> map (map $ fromJust <<< BigNum.fromBigInt)
>>> map
(map $ unsafeFromJust "instance Partition BigNum" <<< BigNum.fromBigInt)

-- | Partitions a `BigInt` into a number of parts, where the size of each part
-- | is proportional to the size of its corresponding element in the given
Expand Down Expand Up @@ -91,13 +93,14 @@ instance Partition BigInt where
round portions =
NEArray.zipWith (+)
(map (fst <<< unwrap) <$> portions)
( fromArrayUnsafe $
( unsafeFromJust "instance Partition BigInt" <<< NEArray.fromArray $
replicate shortfall one
<> replicate (length portions - shortfall) zero
)

shortfall :: Int
shortfall = toIntUnsafe $ target - sum (map fst portionsUnrounded)
shortfall = unsafeFromJust "instance Partition BigInt" <<< BigInt.toInt
$ target - sum (map fst portionsUnrounded)

portionsUnrounded :: NonEmptyArray (BigInt /\ BigInt)
portionsUnrounded = weights <#> \w -> (target * w) `quotRem` sumWeights
Expand All @@ -120,22 +123,25 @@ instance Equipartition BigInt where
NEArray.singleton bi
| otherwise =
let
quot /\ rem = toIntUnsafe <$> (bi `quotRem` BigInt.fromInt numParts)
quot /\ rem =
unsafeFromJust "instance Equipartition BigInt" <<< BigInt.toInt <$>
(bi `quotRem` BigInt.fromInt numParts)
in
NEArray.replicate (numParts - rem) quot
`NEArray.appendArray` replicate rem (quot + one)

instance Equipartition BigNum where
equipartition bn = unsafePartial
$ map (fromJust <<< BigNum.fromBigInt)
$ map (unsafeFromJust "instance Equipartition BigNum" <<< BigNum.fromBigInt)
<<< equipartition (BigNum.toBigInt bn)

instance Equipartition MultiAsset where
equipartition nonAdaAssets numParts =
foldl accumulate (NEArray.replicate numParts MultiAsset.empty)
(MultiAsset.flatten nonAdaAssets)
where
append' a b = unsafePartial $ fromJust $ MultiAsset.add a b
append' a b = unsafeFromJust "instance Equipartition MultiAsset" $
MultiAsset.add a b

accumulate
:: NonEmptyArray MultiAsset
Expand All @@ -146,12 +152,6 @@ instance Equipartition MultiAsset where
map (MultiAsset.singleton cs tn)
(equipartition tokenQuantity numParts)

toIntUnsafe :: BigInt -> Int
toIntUnsafe = unsafePartial fromJust <<< BigInt.toInt

fromArrayUnsafe :: forall (a :: Type). Array a -> NonEmptyArray a
fromArrayUnsafe = unsafePartial fromJust <<< NEArray.fromArray

quotRem :: forall (a :: Type). EuclideanRing a => a -> a -> (a /\ a)
quotRem a b = (a `div` b) /\ (a `mod` b)

Expand Down Expand Up @@ -202,8 +202,9 @@ equipartitionAssetsWithTokenQuantityUpperBound nonAdaAssets maxTokenQuantity =
equipartition nonAdaAssets numParts /\ numParts
where
numParts :: Int
numParts = unsafePartial $ fromJust $ BigInt.toInt $
divCeil (BigNum.toBigInt currentMaxTokenQuantity) maxTokenQuantity
numParts = unsafeFromJust "equipartitionAssetsWithTokenQuantityUpperBound"
$ BigInt.toInt
$ divCeil (BigNum.toBigInt currentMaxTokenQuantity) maxTokenQuantity

tokenQuantity :: (ScriptHash /\ AssetName /\ BigNum) -> BigNum
tokenQuantity (_ /\ _ /\ quantity) = quantity
Expand Down
7 changes: 4 additions & 3 deletions src/Internal/Plutip/Types.purs
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@ import Cardano.Types.PrivateKey (PrivateKey(PrivateKey))
import Cardano.Types.PrivateKey as PrivateKey
import Cardano.Types.RawBytes (RawBytes(RawBytes))
import Ctl.Internal.Contract.Hooks (Hooks)
import Ctl.Internal.Helpers (unsafeFromJust)
import Ctl.Internal.ServerConfig (ServerConfig)
import Ctl.Internal.Test.UtxoDistribution (InitialUTxODistribution)
import Data.ByteArray (hexToByteArray)
import Data.Either (Either(Left), note)
import Data.Generic.Rep (class Generic)
import Data.Log.Level (LogLevel)
import Data.Log.Message (Message)
import Data.Maybe (Maybe, fromJust)
import Data.Maybe (Maybe)
import Data.Newtype (class Newtype)
import Data.Show.Generic (genericShow)
import Data.Time.Duration (Seconds(Seconds))
import Data.UInt (UInt)
import Effect.Aff (Aff)
import Partial.Unsafe (unsafePartial)

-- | A config that is used to run tests on Plutip clusters.
-- | Note that the test suite starts the services on the specified ports.
Expand Down Expand Up @@ -94,7 +94,8 @@ instance EncodeAeson ClusterStartupRequest where
) = encodeAeson
{ keysToGenerate
, epochSize
, slotLength: unsafePartial $ fromJust $ finiteNumber slotLength
, slotLength: unsafeFromJust "instance EncodeAeson ClusterStartupRequest" $
finiteNumber slotLength
, maxTxSize
, raiseExUnitsToMax
}
Expand Down

0 comments on commit adf54bf

Please sign in to comment.