{-# OPTIONS_GHC -Wno-orphans #-}

module Hydra.Cardano.Api.PolicyId where

import Hydra.Cardano.Api.Prelude

import Cardano.Ledger.Alonzo.Plutus.TxInfo qualified as Ledger
import Cardano.Ledger.Mary.Value qualified as Ledger
import Hydra.Cardano.Api.ScriptHash ()
import PlutusLedgerApi.V3 (CurrencySymbol, fromBuiltin, unCurrencySymbol)
import Test.Gen.Cardano.Api.Typed (genPolicyId)
import Test.QuickCheck.Hedgehog (hedgehog)

-- * Orphans

instance Arbitrary PolicyId where
  arbitrary :: Gen PolicyId
arbitrary = Gen PolicyId -> Gen PolicyId
forall a. Gen a -> Gen a
hedgehog Gen PolicyId
genPolicyId

-- * Type conversions

-- | Convert Cardano api 'PolicyId' to Cardano ledger `PolicyID`.
toLedgerPolicyID :: PolicyId -> Ledger.PolicyID StandardCrypto
toLedgerPolicyID :: PolicyId -> PolicyID StandardCrypto
toLedgerPolicyID (PolicyId ScriptHash
sh) = ScriptHash StandardCrypto -> PolicyID StandardCrypto
forall c. ScriptHash c -> PolicyID c
Ledger.PolicyID (ScriptHash -> ScriptHash StandardCrypto
toShelleyScriptHash ScriptHash
sh)

-- | Convert Cardano api 'PolicyId' to Plutus `CurrencySymbol`.
toPlutusCurrencySymbol :: PolicyId -> CurrencySymbol
toPlutusCurrencySymbol :: PolicyId -> CurrencySymbol
toPlutusCurrencySymbol = PolicyID StandardCrypto -> CurrencySymbol
forall c. PolicyID c -> CurrencySymbol
Ledger.transPolicyID (PolicyID StandardCrypto -> CurrencySymbol)
-> (PolicyId -> PolicyID StandardCrypto)
-> PolicyId
-> CurrencySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PolicyId -> PolicyID StandardCrypto
toLedgerPolicyID

-- | Convert a plutus 'CurrencySymbol' into a cardano-api 'PolicyId'.
fromPlutusCurrencySymbol :: MonadFail m => CurrencySymbol -> m PolicyId
fromPlutusCurrencySymbol :: forall (m :: * -> *). MonadFail m => CurrencySymbol -> m PolicyId
fromPlutusCurrencySymbol CurrencySymbol
cs =
  case AsType PolicyId
-> ByteString -> Either SerialiseAsRawBytesError PolicyId
forall a.
SerialiseAsRawBytes a =>
AsType a -> ByteString -> Either SerialiseAsRawBytesError a
deserialiseFromRawBytes AsType PolicyId
AsPolicyId ByteString
FromBuiltin BuiltinByteString
bytes of
    Left SerialiseAsRawBytesError
err -> String -> m PolicyId
forall a. String -> m a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (SerialiseAsRawBytesError -> String
forall a. Show a => a -> String
show SerialiseAsRawBytesError
err)
    Right PolicyId
pid -> PolicyId -> m PolicyId
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure PolicyId
pid
 where
  bytes :: FromBuiltin BuiltinByteString
bytes = BuiltinByteString -> FromBuiltin BuiltinByteString
forall arep. HasFromBuiltin arep => arep -> FromBuiltin arep
fromBuiltin (BuiltinByteString -> FromBuiltin BuiltinByteString)
-> BuiltinByteString -> FromBuiltin BuiltinByteString
forall a b. (a -> b) -> a -> b
$ CurrencySymbol -> BuiltinByteString
unCurrencySymbol CurrencySymbol
cs