{-# LANGUAGE NoImplicitPrelude #-}

module Plutus.Script.Utils.Value
  ( module Export
  , noAdaValue
  , adaOnlyValue
  , isAdaOnlyValue
  , currencyValueOf
  ) where

import Plutus.Script.Utils.Ada qualified as Ada
import Plutus.V1.Ledger.Value as Export (AssetClass (AssetClass, unAssetClass),
                                         CurrencySymbol (CurrencySymbol, unCurrencySymbol),
                                         TokenName (TokenName, unTokenName), Value (Value, getValue), adaSymbol,
                                         adaToken, assetClass, assetClassValue, assetClassValueOf, currencyMPSHash,
                                         currencySymbol, flattenValue, geq, gt, isZero, leq, lt, mpsSymbol, scale,
                                         singleton, split, symbols, toString, tokenName, unionWith, valueOf)
import PlutusTx.AssocMap qualified as Map
import PlutusTx.Prelude (Bool, Eq ((==)), Maybe (Just, Nothing), mempty, (-))

{-# INLINABLE noAdaValue #-}
-- | Value without any Ada.
noAdaValue :: Value -> Value
noAdaValue :: Value -> Value
noAdaValue Value
v = Value
v Value -> Value -> Value
forall a. AdditiveGroup a => a -> a -> a
- Value -> Value
adaOnlyValue Value
v

{-# INLINABLE adaOnlyValue #-}
-- | Value without any non-Ada.
adaOnlyValue :: Value -> Value
adaOnlyValue :: Value -> Value
adaOnlyValue Value
v = Ada -> Value
Ada.toValue (Value -> Ada
Ada.fromValue Value
v)

{-# INLINABLE isAdaOnlyValue #-}
isAdaOnlyValue :: Value -> Bool
isAdaOnlyValue :: Value -> Bool
isAdaOnlyValue Value
v = Value -> Value
adaOnlyValue Value
v Value -> Value -> Bool
forall a. Eq a => a -> a -> Bool
== Value
v

{-# INLINABLE currencyValueOf #-}
-- | Get the quantities of just the given 'CurrencySymbol' in the 'Value'. This
-- is useful when implementing minting policies as they are responsible for
-- checking all minted/burnt tokens of their own 'CurrencySymbol'.
currencyValueOf :: Value -> CurrencySymbol -> Value
currencyValueOf :: Value -> CurrencySymbol -> Value
currencyValueOf (Value Map CurrencySymbol (Map TokenName Integer)
m) CurrencySymbol
c = case CurrencySymbol
-> Map CurrencySymbol (Map TokenName Integer)
-> Maybe (Map TokenName Integer)
forall k v. Eq k => k -> Map k v -> Maybe v
Map.lookup CurrencySymbol
c Map CurrencySymbol (Map TokenName Integer)
m of
    Maybe (Map TokenName Integer)
Nothing -> Value
forall a. Monoid a => a
mempty
    Just Map TokenName Integer
t  -> Map CurrencySymbol (Map TokenName Integer) -> Value
Value (CurrencySymbol
-> Map TokenName Integer
-> Map CurrencySymbol (Map TokenName Integer)
forall k v. k -> v -> Map k v
Map.singleton CurrencySymbol
c Map TokenName Integer
t)