{-# LANGUAGE NamedFieldPuns #-}
-- | Dealing with tokens
module Ledger.Tokens(
  -- $tokens
  token
  , outputsWith
  , paidTo
  ) where

import Plutus.V1.Ledger.Contexts
import Plutus.V1.Ledger.Value (AssetClass, Value, leq)
import Plutus.V1.Ledger.Value qualified as Value

-- $tokens
-- The extended UTXO ledger with scripts that Plutus runs on supports
-- native user-defined currencies. Tokens are user-defined currencies
-- with an issuance of exactly one unit. Every token is identified by
-- a 'Currency'.

{-# INLINABLE token #-}
-- | A value that contains exactly the token.
token :: AssetClass -> Value
token :: AssetClass -> Value
token AssetClass
cur = AssetClass -> Integer -> Value
Value.assetClassValue AssetClass
cur Integer
1

{-# INLINABLE outputsWith #-}
-- | The outputs of the 'ValidatorCtx' that carry a non-zero amount of the
--   currency.
outputsWith :: TxInfo -> AssetClass -> [TxOut]
outputsWith :: TxInfo -> AssetClass -> [TxOut]
outputsWith TxInfo{[TxOut]
txInfoOutputs :: TxInfo -> [TxOut]
txInfoOutputs :: [TxOut]
txInfoOutputs} AssetClass
currency =
    (TxOut -> Bool) -> [TxOut] -> [TxOut]
forall a. (a -> Bool) -> [a] -> [a]
filter (\TxOut
output -> AssetClass -> Value
token AssetClass
currency  Value -> Value -> Bool
`leq` TxOut -> Value
txOutValue TxOut
output) [TxOut]
txInfoOutputs

{-# INLINABLE paidTo #-}
-- | The total 'Value' paid by the pending transaction to outputs
--   whose value also includes a non-zero amount of the currency.
paidTo :: TxInfo -> AssetClass -> Value
paidTo :: TxInfo -> AssetClass -> Value
paidTo TxInfo
ptx AssetClass
currency =
    (TxOut -> Value) -> [TxOut] -> Value
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap TxOut -> Value
txOutValue (TxInfo -> AssetClass -> [TxOut]
outputsWith TxInfo
ptx AssetClass
currency)