imports
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
{-# LANGUAGE StandaloneDeriving, FlexibleInstances, UndecidableInstances #-}
module Plutarch.Docs.DerivingForNewtype (PPubKeyHash'(..), PPubKeyHash(..)) where
import Plutarch.Prelude
import GHC.Generics (Generic)
import Generics.SOP qualified as SOP
Deriving typeclasses for newtypes
If you're defining a newtype to an existing Plutarch type, like so:
newtype PPubKeyHash' (s :: S) = PPubKeyHash' (Term s (PDataNewtype PByteString))
You ideally want to just have this newtype be represented as a PByteString under the hood. Therefore, all the typeclass instances of PByteString make sense for
PPubKeyHash as well. In this case, you can simply derive all those typeclasses for your PPubKeyHash type as well:
newtype PPubKeyHash (s :: S) = PPubKeyHash (Term s (PDataNewtype PByteString))
deriving stock (Generic)
deriving anyclass (SOP.Generic, PIsData, PEq, POrd, PShow)
deriving (PlutusType) via (DeriveNewtypePlutusType PPubKeyHash)
Note: It's important to note that the content of a
newtypethat aims to be a Plutarch type (i.e. can be represented as a Plutarch term), must also be a Plutarch term. The typePByteString ssimply doesn't exist in the Plutus Core world after compilation. It's all justTerms. So, when you sayTerm s PPubKeyHash, you're really just describing aTerm s PByteStringunder the hood - since that's what it is during runtime.
Aside: You can access the inner type using
pto(assuming it's aPlutusTypeinstance). For example,pto x, wherex :: Term s PPubKeyHash, would give youTerm s PByteString.ptoconverts aPlutusTypeterm to its inner type. This is very useful, for example, when you need to use a function that operates on bytestring terms, but all you have is aTerm s PPubKeyHash. You know it's literally a bytestring under the hood anyway - but how do you obtain that? Usingpto!
Currently, DerivePNewtype lets you derive the following typeclasses for your Plutarch types:
PEqPIntegralPIsDataPNumPOrdPShowPlutusType
Note: You cannot derive instances for
Terms anymore because of coherence issues with the previous solutions. All derivations have to be done for the PlutusType (e.g. you cannot newtype deriveSemigroupforPPubKeyHashanymore)