### Module header and imports for PAsData examples Source: https://plutarch-plutus.org/Types/PAsData.html Declares the module and imports Plutarch.Prelude for the examples that follow. ```haskell module Plutarch.Docs.PAsData (fooData, fooConcrete) where import Plutarch.Prelude ``` -------------------------------- ### Module imports for PEq and POrd examples Source: https://plutarch-plutus.org/Typeclasses/PEqAndPOrd.html Required imports and language pragma for the examples on this page. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.PEqAndPOrd (PMaybe'(..)) where import GHC.Generics (Generic) import Plutarch.Prelude ``` -------------------------------- ### Module imports and options for PListLike examples Source: https://plutarch-plutus.org/Typeclasses/PListLike.html Sets up the module for the PListLike examples, disabling redundant constraint warnings and importing Plutarch.Prelude. ```haskell {-# OPTIONS_GHC -Wno-redundant-constraints #-} module Plutarch.Docs.PListLike (pfoo, pfoo', x, x') where import Plutarch.Prelude ``` -------------------------------- ### Module imports for PDataSum and PDataRecord examples Source: https://plutarch-plutus.org/Types/PDataSumAndPDataRecord.html Required imports and language pragma for the examples on this page. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.PDataSumAndRecord (Foo (..), test) where import Plutarch.Prelude ``` -------------------------------- ### Imports for Plutarch pattern matching examples Source: https://plutarch-plutus.org/Tricks/PreferMatchingOnPmatchResultImmediately.html Imports required for the examples: Plutarch.Prelude and Plutarch.LedgerApi.V3 with the PScriptPurpose constructors. ```haskell module Plutarch.Docs.PreferMatchingOnResult (this, this') where import Plutarch.Prelude import Plutarch.LedgerApi.V3 ( PScriptPurpose ( PSpending, PMinting, PRewarding, PCertifying, PVoting, PProposing ) ) ``` -------------------------------- ### Module imports for PBuiltinList examples Source: https://plutarch-plutus.org/Types/PBuiltinList.html Module header for the Plutarch PBuiltinList documentation examples. It enables the -Wno-redundant-constraints GHC option and imports Plutarch.Prelude. ```haskell {-# OPTIONS_GHC -Wno-redundant-constraints #-} module Plutarch.Docs.PBuiltinList (validBuiltinList, listOfBs, matchOnList, matchOnList') where import Plutarch.Prelude ``` -------------------------------- ### Scott encoding example with just, nothing, and foo Source: https://plutarch-plutus.org/Concepts/DataAndScottEncoding.html Complete Scott encoding example with type alias, constructors, and a deconstruction function. ```haskell type Maybe a = forall b. (a -> b) -> b -> b just :: a -> Maybe a just x = \f _ -> f x nothing :: Maybe a nothing = \_ n -> n foo :: Maybe Integer -> Integer foo mb = mb (\x -> x + 42) 0 ``` -------------------------------- ### Imports for PByteString examples Source: https://plutarch-plutus.org/Types/PByteString.html Imports required for the PByteString examples: Plutarch.Prelude for Plutarch types and Data.ByteString for ByteString operations. ```haskell module Plutarch.Docs.PByteString (notQuiteTheAnswer, aChar) where import Plutarch.Prelude import qualified Data.ByteString as BS ``` -------------------------------- ### Imports for TermCont examples Source: https://plutarch-plutus.org/Usage/DoSyntaxWithTermCont.html Imports required for the TermCont examples: Plutarch.LedgerApi.V3 for PScriptPurpose and Plutarch.Prelude, hiding pmatchC and ptraceC to avoid conflicts. ```haskell module Plutarch.Docs.TermCont (test, testC, foo) where import Plutarch.LedgerApi.V3 (PScriptPurpose (PSpending)) import Plutarch.Prelude hiding (pmatchC, ptraceC) ``` -------------------------------- ### Module imports for Plutarch.Docs.PBool Source: https://plutarch-plutus.org/Types/PBool.html Imports required for the PBool example, including Plutarch.Prelude. ```haskell module Plutarch.Docs.PBool (pTheAnswer) where import Plutarch.Prelude ``` -------------------------------- ### Factorial implementation with pfix Source: https://plutarch-plutus.org/Usage/Recursion.html An example of implementing a factorial function using pfix, showing the difference in plam usage compared to pfixHoisted. ```haskell pfac' :: Term s (PInteger :--> PInteger) pfac' = pfix f where f :: Term s (PInteger :--> PInteger) -> Term s (PInteger :--> PInteger) f self = plam $ \n -> pif (n #== 1) n $ n * (self #$ n - 1) ``` -------------------------------- ### Factorial implementation with pfixHoisted Source: https://plutarch-plutus.org/Usage/Recursion.html An example of implementing a factorial function using pfixHoisted. ```haskell pfac :: Term s (PInteger :--> PInteger) pfac = pfixHoisted #$ plam f where f :: Term s (PInteger :--> PInteger) -> Term s PInteger -> Term s PInteger f self n = pif (n #== 1) n $ n * (self #$ n - 1) -- (ignore the existence of non positives :D) ``` -------------------------------- ### Testing PLiftable Laws with checkPLiftableLaws Source: https://plutarch-plutus.org/Typeclasses/PLiftable.html Example of using checkPLiftableLaws to verify instances for PInteger and PScriptContext using QuickCheck. ```haskell main :: IO () main = defaultMain . testGroup "Laws" $ [ checkPLiftableLaws @PInteger, checkPLiftableLaws @PScriptContext ] ``` -------------------------------- ### Imports for Plutarch validator examples with GHC 9 extensions Source: https://plutarch-plutus.org/examples/VALIDATOR.html Necessary imports for the validator examples, including `Plutarch.LedgerApi.V3` for `PDatum`, `PRedeemer`, `PScriptContext`, and related types, plus `Plutarch.Docs.Run` for `evalWithArgsT` and `Plutarch.Script`. The language extensions `QualifiedDo` and `OverloadedRecordDot` are required. ```haskell {-# LANGUAGE QualifiedDo #-} {-# LANGUAGE OverloadedRecordDot #-} module Plutarch.Docs.ValidatorExample (alwaysSucceeds, checkSignatory, res', res, alwaysFails) where import Plutarch.Prelude import Plutarch.LedgerApi.V3 ( PDatum, PRedeemer, PScriptContext (pscriptContext'scriptInfo, pscriptContext'txInfo), PTxInfo (ptxInfo'signatories), PPubKeyHash, PScriptInfo(PSpendingScript) ) import Plutarch.Docs.Run (evalWithArgsT) import Plutarch.Script (Script) import qualified PlutusTx import PlutusCore.Evaluation.Machine.ExBudget (ExBudget) import Data.Text (Text) ``` -------------------------------- ### Plutarch.Docs.PMatch module header Source: https://plutarch-plutus.org/Concepts/GenericProgramming.html Module header for Plutarch.Docs.PMatch. It enables GHC options to suppress deprecation and redundant-constraint warnings, and imports Plutarch.Prelude, Plutarch.Internal.PlutusType, Data.Kind, GHC.Generics, and Plutarch.Unsafe. This is the required setup for the examples that follow. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-} module Plutarch.Docs.PMatch (Tree(..), swap, TreeRepr) where import Plutarch.Prelude import Plutarch.Internal.PlutusType (PlutusType (pcon', pmatch')) import Data.Kind (Type) import GHC.Generics (Generic) import Plutarch.Unsafe (punsafeCoerce) ``` -------------------------------- ### Imports for PlutusType examples Source: https://plutarch-plutus.org/Typeclasses/PlutusType%2CPCon%2CPMatch.html Imports and language pragmas required for the examples on this page, including the `DeriveAsSOPStruct` constructor and `PlutusType` derivation. ```haskell {-# OPTIONS_GHC -Wno-redundant-constraints #-} {-# OPTIONS_GHC -Wno-deprecations #-} {-# LANGUAGE UndecidableInstances #-} module Plutarch.Docs.PlutusTypePConAndPMatch (PMyType(..), PMyTypeData(..)) where import Data.Kind (Type) import GHC.Generics (Generic) import Generics.SOP qualified as SOP import Plutarch.Prelude ``` -------------------------------- ### Build PList with pcons Source: https://plutarch-plutus.org/Typeclasses/PListLike.html Builds a PList of PInteger using the same code as the PBuiltinList example, only changing the type annotation. ```haskell x' :: Term s (PList PInteger) x' = pcons # 1 #$ pcons # 2 #$ pcons # 3 # pnil ``` -------------------------------- ### Lambda Argument Definition Source: https://plutarch-plutus.org/Introduction/PlutarchTerms/PlutarchLambdas.html Example showing the structure of a lambda definition using plam. ```haskell f :: Term s (PInteger :--> PString :--> a :--> a) f = plam $ \??? ``` -------------------------------- ### Plutarch Introduction module header Source: https://plutarch-plutus.org/Introduction.html Module header for the Plutarch introduction. Imports Plutarch.Prelude, which provides the core types and functions used throughout the guide. ```haskell module Plutarch.Docs.Introduction (hf) where import Plutarch.Prelude ``` -------------------------------- ### Imports for Plutarch.Docs.WorkingWithBoundFields Source: https://plutarch-plutus.org/Tricks/WorkingWithBoundFields.html Imports required for the examples on this page: GHC.Records for getField, GHC.Generics for Generic, Plutarch.Prelude, Plutarch.DataRepr for HRec/HRecOf/PMemberFields, and Plutarch.LedgerApi.V3 for PTxInfo/PScriptContext. ```haskell module Plutarch.Docs.WorkingWithBoundFields (foo, foo', coreValidator) where import GHC.Records (getField) import GHC.Generics (Generic) import Plutarch.Prelude import Plutarch.DataRepr (HRec, HRecOf, PMemberFields) import Plutarch.LedgerApi.V3 (PTxInfo, PScriptContext) ``` -------------------------------- ### Module header and imports for Plutarch.Docs.PList Source: https://plutarch-plutus.org/Types/PList.html Imports the Plutarch prelude and declares the module that exports the three example functions defined on this page. ```haskell module Plutarch.Docs.PList (pFe, pFeElim, pFeList) where import Plutarch.Prelude ``` -------------------------------- ### Using POrd with pif Source: https://plutarch-plutus.org/Typeclasses/PEqAndPOrd.html Example of using (#<) with pif to choose between two PString values. ```haskell pif (1 #< 7) "indeed" "what" ``` -------------------------------- ### Imports for generic deriving Source: https://plutarch-plutus.org/Usage/DerivingWithGenerics.html Imports and module header for the generic deriving example. Requires the `generics-sop` package. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.DerivingGenerics (PMyType (..)) where import Plutarch.Prelude import Data.Kind (Type) import GHC.Generics (Generic) ``` -------------------------------- ### Module imports for Plutarch documentation Source: https://plutarch-plutus.org/Tricks/DifferenceBetweenPconAndPconstant.html Initial module declaration and imports required for the Plutarch documentation examples. ```haskell module Plutarch.Docs.DifferencePconPconstant () where import Plutarch.Prelude import Plutarch.Internal.PlutusType (PlutusType(pcon', pmatch')) ``` -------------------------------- ### PVehicle field access example Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html Example usage of PVehicle: pattern match, pletFields to access fields, and sum them. Demonstrates ergonomic field access after deriving PIsData. ```haskell test :: Term s (PVehicle :--> PInteger) test = plam $ \veh' -> P.do veh <- pmatch veh' case veh of PFourWheeler fwh' -> P.do fwh <- pletFields @'["_0", "_1", "_2", "_3"] fwh' fwh._0 + fwh._1 + fwh._2 + fwh._3 PTwoWheeler twh' -> P.do twh <- pletFields @'["_0", "_1"] twh' twh._0 + twh._1 PImmovableBox _ -> 0 ``` -------------------------------- ### Using PEq with PInteger Source: https://plutarch-plutus.org/Typeclasses/PEqAndPOrd.html Example of using the (#==) operator on PInteger values, yielding a Term s PBool. ```haskell 1 #== 2 ``` -------------------------------- ### Using P.do syntax in Plutarch Source: https://plutarch-plutus.org/Usage/DoSyntaxWithQualifiedDo.html Example of using P.do to perform pattern matching and tracing within a Plutarch term. ```haskell f :: Term s (PScriptPurpose :--> PUnit) f = plam $ \x -> P.do PSpending _ <- pmatch x ptraceInfo "matched spending script purpose" pconstant () ``` -------------------------------- ### Module imports for recursion Source: https://plutarch-plutus.org/Usage/Recursion.html Initial module definition and imports required for Plutarch recursion examples. ```haskell module Plutarch.Docs.Recursion (pfac, pfac') where import Plutarch.Prelude ``` -------------------------------- ### Imports for Plutarch.Docs.OptimizingUnhoistable Source: https://plutarch-plutus.org/Tricks/OptimizingUnhoistableLambdas.html Required imports for the examples on this page. The module exports pfoo and pfoo'. ```haskell module Plutarch.Docs.OptimizingUnhoistable (pfoo, pfoo') where import Plutarch.Prelude ``` -------------------------------- ### Evaluate Fibonacci function Source: https://plutarch-plutus.org/examples/BASIC.html Execution example evaluating the fib function with an input of 2. ```haskell > evalT $ fib # 2 Right (Program () (Version () 1 0 0) (Constant () (Some (ValueOf integer 2)))) ``` -------------------------------- ### Build a PDataRecord with two integer fields Source: https://plutarch-plutus.org/Types/PDataSumAndPDataRecord.html Example of building a PDataRecord with two integer fields named foo and bar using pdcons and pdnil. ```haskell test :: Term s (PDataRecord '[ "foo" ':= PInteger, "bar" ':= PInteger]) test = pdcons # pdata 7 #$ pdcons # pdata 42 # pdnil ``` -------------------------------- ### Importing Plutarch.Monadic for QualifiedDo Source: https://plutarch-plutus.org/Usage/DoSyntaxWithQualifiedDo.html Setup required to use QualifiedDo with Plutarch, including the language extension and the necessary imports. ```haskell {-# LANGUAGE QualifiedDo #-} module Plutarch.Docs.QDo (f) where import Plutarch.LedgerApi.V3 (PScriptPurpose (PSpending)) import qualified Plutarch.Monadic as P import Plutarch.Prelude ``` -------------------------------- ### Derive PLiftable for PInteger using DeriveBuiltinPLiftable Source: https://plutarch-plutus.org/Typeclasses/PLiftable.html Example of deriving PLiftable for PInteger with Haskell equivalent Integer using the DeriveBuiltinPLiftable helper. ```haskell deriving via (DeriveBuiltinPLiftable PInteger Integer) instance PLiftable PInteger ``` -------------------------------- ### Module imports for Plutarch pattern matching Source: https://plutarch-plutus.org/Introduction/PatternMatching.html Imports Plutarch.Prelude and declares the module that exports pisJust. Required for the pattern matching example. ```haskell module Plutarch.Docs.PatternMatching (pisJust) where import Plutarch.Prelude ``` -------------------------------- ### Inefficient Function Usage Source: https://plutarch-plutus.org/Tricks/DontDuplicateWork.html Example of calling the inefficient 'abs' function with an expensive computation. ```haskell abs (reallyExpensiveFunction # arg) ``` -------------------------------- ### Derive PLiftable for PScriptContext using DeriveDataPLiftable Source: https://plutarch-plutus.org/Typeclasses/PLiftable.html Example of deriving PLiftable for PScriptContext with Haskell equivalent ScriptContext using the DeriveDataPLiftable helper. ```haskell deriving via (DeriveDataPLiftable PScriptContext ScriptContext) instance PLiftable PScriptContext ``` -------------------------------- ### Derive PLiftable for PPositive using DeriveNewtypePLiftable Source: https://plutarch-plutus.org/Typeclasses/PLiftable.html Example of deriving PLiftable for PPositive with Haskell equivalent Positive, using DeriveNewtypePLiftable and specifying PPositive's representation as PInteger. ```haskell newtype PPositive s = PPositive (Term s PInteger) deriving stock (Generic) deriving anyclass (PlutusType, PIsData) deriving via DeriveNewtypePLiftable PPositive PInteger Positive instance PLiftable PPositive ``` -------------------------------- ### Construct PScriptPurpose with pdcons and pdnil Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html Constructs a PScriptPurpose by building a PDataRecord with pdcons and pdnil, then applying pcon to the PMinting constructor. Type annotations are included to guide GHC. ```haskell currSym :: Term s PCurrencySymbol currSym = pconstant $ CurrencySymbol "foo" purpose :: Term s PScriptPurpose purpose = pcon $ PMinting fields where currSymDat :: Term _ (PAsData PCurrencySymbol) currSymDat = pdata currSym fields :: Term _ (PDataRecord '[ "_0" ':= PCurrencySymbol ]) fields = pdcons # currSymDat # pdnil ``` -------------------------------- ### Example of Redundant Inlining Source: https://plutarch-plutus.org/Tricks/DontDuplicateWork.html A simple Plutarch term where the binding 'foo' is inlined twice, causing the computation to run multiple times. ```haskell pf :: Term s PInteger pf = let foo :: forall s. Term s PInteger foo = 1 + 2 -- | A Haskell binding. in pif (foo #== 3) -- | A.) ...then inline here... foo -- | B.) ...and inline here. 7 ``` -------------------------------- ### Build static HTML documentation Source: https://plutarch-plutus.org/DEVGUIDE.html Use this command to generate the static HTML site for the documentation. ```bash mdbook build . ``` -------------------------------- ### Run documentation via Nix Source: https://plutarch-plutus.org/DEVGUIDE.html Execute the documentation directly from the Plutarch GitHub repository without needing to clone the repository locally. ```bash nix run github:Plutonomicon/plutarch#combined-docs ``` -------------------------------- ### Example using pif to define one Source: https://plutarch-plutus.org/Usage/Conditionals.html Defines `one` as `pif (pconstant True) 1 2`, which evaluates to `1` of type `Term s PInteger`. ```haskell one :: forall s. Term s PInteger one = pif (pconstant True) 1 2 ``` -------------------------------- ### Identity Function as Plutarch Lambda Source: https://plutarch-plutus.org/Introduction/PlutarchTerms/PlutarchLambdas.html Examples of creating an identity function lambda using plam with a named function or a lambda expression. ```haskell -- | Haskell-level `id` function specialized to the `Term s a` type`` termId :: Term s a -> Term s a termId x = x -- | Plutarch-level `id` lambda pid :: Term s (a :--> a) pid = plam termId -- | Equivalently: pid' :: Term s (a :--> a) pid' = plam $ \x -> x ``` -------------------------------- ### Serve documentation locally with mdbook Source: https://plutarch-plutus.org/DEVGUIDE.html Run this command from the plutarch-docs directory to serve the documentation locally while editing. ```bash mdbook serve . ``` -------------------------------- ### Preview: Plutarch-level Lambda and Haskell-level Function Source: https://plutarch-plutus.org/Introduction.html Preview example showing a Plutarch-level lambda term `pf` and a Haskell-level function `hf` that applies it using the `#` operator. The comment notes that `pf` is truly just a Plutarch `Term` and should not be treated specially. ```haskell __ -- This example is listed here as a preview; the unfamiliar parts will -- be detailed below. -- A Plutarch-level lambda term pf :: Term s (a :--> b :--> c) pf = undefined -- Recovering a Haskell level function from a Plutarch level function hf :: Term s a -> Term s b -> Term s c hf x y = pf # x # y ``` -------------------------------- ### PBuiltinPair module imports Source: https://plutarch-plutus.org/Types/PBuiltinPair.html Initial module definition and imports for PBuiltinPair. ```haskell __ module Plutarch.Docs.PBuiltinPair () where import Plutarch.Prelude () ``` -------------------------------- ### Import Plutarch.Docs.PInteger module Source: https://plutarch-plutus.org/Types/PInteger.html Imports the Plutarch.Prelude module, which provides the necessary definitions for working with PInteger. ```haskell module Plutarch.Docs.PInteger () where import Plutarch.Prelude () ``` -------------------------------- ### Build PBuiltinList with pcons Source: https://plutarch-plutus.org/Typeclasses/PListLike.html Builds a PBuiltinList of PInteger using pcons and pnil. ```haskell x :: Term s (PBuiltinList PInteger) x = pcons # 1 #$ pcons # 2 #$ pcons # 3 # pnil ``` -------------------------------- ### Module header with RankNTypes Source: https://plutarch-plutus.org/Concepts/DataAndScottEncoding.html Module header for the documentation page, enabling RankNTypes and importing Integer and (+) from Prelude. ```haskell {-# LANGUAGE RankNTypes #-} module Plutarch.Docs.DataAndScottEncoding (nothing, just, foo) where import Prelude (Integer, (+)) ``` -------------------------------- ### Construct PBuiltinList with pcon and PCons Source: https://plutarch-plutus.org/Types/PBuiltinList.html Constructs a PBuiltinList containing one element, the byte string 0xfe, using pcon and PCons. The comment notes that pcons from PListLike is preferred. ```haskell listOfBs :: forall s. Term s (PBuiltinList (PAsData PByteString)) listOfBs = pcon $ PCons (pdata $ phexByteStr "fe") $ pcon PNil ``` -------------------------------- ### Inefficient Function Definition Source: https://plutarch-plutus.org/Usage/AvoidWorkDuplicationUsingPlet.html An example of a function that duplicates work by using the argument x multiple times directly. ```haskell pfoo :: forall s. Term s PString -> Term s PString pfoo x = x <> x ``` -------------------------------- ### Mocking ScriptContext and evaluating Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html Creating a mock ScriptContext and evaluating the Plutarch script with it. ```haskell mockCtx :: ScriptContext mockCtx = ScriptContext (TxInfo mempty -- inputs mempty -- reference inputs mempty -- outputs 0 -- fee mempty -- mint mempty -- certs AssocMap.empty -- withdrawals (interval (POSIXTime 1) (POSIXTime 2)) -- valid range mempty -- signatories AssocMap.empty -- redeemers AssocMap.empty -- data "" -- id AssocMap.empty -- votes mempty -- proposal procedures Nothing -- current treasury amount Nothing -- current treasury donation ) (Redeemer . Builtins.mkI $ 0) (MintingScript (CurrencySymbol "")) res :: Either _ _ res = foo `evalWithArgsT` [PlutusTx.toData mockCtx] -- Right (Program () (Version () 1 0 0) (Constant () (Some (ValueOf string "It's minting!")))) ``` -------------------------------- ### TermCont do syntax with pmatchC and ptraceInfoC Source: https://plutarch-plutus.org/Usage/DoSyntaxWithTermCont.html Defines continuation-based helpers pmatchC and ptraceInfoC, then uses them with do syntax in testC. Requires unTermCont to extract the result. ```haskell pmatchC :: PlutusType a => Term s a -> TermCont s (a s) pmatchC = tcont . pmatch ptraceInfoC :: Term s PString -> TermCont s () ptraceInfoC s = tcont $ \f -> ptraceInfo s (f ()) testC :: Term s (PScriptPurpose :--> PUnit) testC = plam $ \x -> unTermCont $ do PSpending _ <- pmatchC x ptraceInfoC "matched spending script purpose" pure $ pconstant () ``` -------------------------------- ### Multi-argument Lambda Type Source: https://plutarch-plutus.org/Introduction/PlutarchTerms/PlutarchLambdas.html Example of a Plutarch function type signature taking an integer, a string, and a generic type. ```haskell f :: Term s (PInteger :--> PString :--> a :--> a) ``` -------------------------------- ### Pattern matching on PScriptContext Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html Demonstrates using pmatch and pfield to deconstruct a PScriptContext and match on its script purpose. ```haskell foo :: Term s (PScriptContext :--> PString) foo = plam $ \ctx -> P.do scriptInfo <- pmatch $ pfield @"scriptInfo" # ctx case scriptInfo of PMintingScript _ -> "It's minting!" PSpendingScript _ -> "It's spending!" PRewardingScript _ -> "It's rewarding!" PCertifyingScript _ -> "It's certifying!" PVotingScript _ -> "It's voting!" PProposingScript _ -> "It's proposing!" ``` -------------------------------- ### Module imports for Plutarch.Docs.PUnit Source: https://plutarch-plutus.org/Types/PUnit.html Imports required for the Plutarch.Docs.PUnit module, including the Plutarch.Prelude module. ```haskell module Plutarch.Docs.PUnit () where import Plutarch.Prelude () ``` -------------------------------- ### Evaluation of foo (just 1) Source: https://plutarch-plutus.org/Concepts/DataAndScottEncoding.html Step-by-step evaluation of foo (just 1) showing how the Scott encoding is applied. ```haskell foo (just 1) foo (\f _ -> f 1) (\f _ -> f 1) (\x -> x + 42) 0 (\x -> x + 42) 1 43 ``` -------------------------------- ### Match on PBuiltinList with pmatch Source: https://plutarch-plutus.org/Types/PBuiltinList.html Matches on a PBuiltinList using pmatch, returning a PString for the empty and non-empty cases. The source recommends using pelimList instead. ```haskell matchOnList :: forall s. Term s PString matchOnList = pmatch (pcon $ PCons (phexByteStr "fe") $ pcon PNil) $ \case PNil -> "hey hey there's nothing here!" PCons _ _ -> "oooo fancy!" ``` -------------------------------- ### A validator that always succeeds Source: https://plutarch-plutus.org/examples/VALIDATOR.html This validator simply returns `()` in all cases, ignoring its datum, redeemer, and context. It can be used as a baseline in examples and tests. ```haskell alwaysSucceeds :: Term s (PAsData PDatum :--> PAsData PRedeemer :--> PAsData PScriptContext :--> PUnit) alwaysSucceeds = plam $ \_datm _redm ctx -> pconstant () ``` -------------------------------- ### Import PString module with OverloadedStrings Source: https://plutarch-plutus.org/Types/PString.html Required imports for using PString, including the OverloadedStrings language extension and the Plutarch.Prelude module. ```haskell {-# LANGUAGE OverloadedStrings #-} module Plutarch.Docs.PString (pfoo) where import Plutarch.Prelude ``` -------------------------------- ### pfromData and pdata type signatures for PAsData instances Source: https://plutarch-plutus.org/Types/PAsData.html Shows the type signatures of pfromData and pdata for several useful instances, including PInteger, PByteString, and PBuiltinList. Using these on builtin primitive types has an associated cost; use them sparingly and plet results when possible. ```haskell pfromData :: Term s (PAsData PInteger) -> Term s PInteger pfromData :: Term s (PAsData PByteString) -> Term s PByteString pfromData :: Term s (PAsData (PBuiltinList (PAsData a))) -> Term s (PBuiltinList (PAsData a)) pdata :: Term s PInteger -> Term s (PAsData PInteger) pdata :: Term s PByteString -> Term s (PAsData PByteString) pdata :: Term s (PBuiltinList (PAsData a)) -> Term s (PAsData (PBuiltinList (PAsData a))) ``` -------------------------------- ### Plutarch.Docs.PData module imports Source: https://plutarch-plutus.org/Types/PData.html Imports Plutarch.Prelude for the PData documentation module. The empty export list and import list indicate this module is for documentation purposes only. ```haskell module Plutarch.Docs.PData () where import Plutarch.Prelude () ``` -------------------------------- ### Boolean or operator (hor) without hoisting Source: https://plutarch-plutus.org/Concepts/Hoisting.html Example of a Haskell-level operator that directly builds a Plutarch term. It uses pif and pconstant to implement boolean or. ```haskell hor :: Term s PBool -> Term s PBool -> Term s PBool x `hor` y = pif x (pconstant True) $ pif y (pconstant True) $ pconstant False ``` -------------------------------- ### Module imports for PTryFrom Source: https://plutarch-plutus.org/Typeclasses/PTryFrom.html Module header for Plutarch.Docs.PTryFrom, enabling FlexibleInstances and disabling deprecation warnings. Imports Plutarch.Prelude and GHC.Generics. ```haskell {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.PTryFrom (recoverListFromPData, theField, untrustedRecord, recoverListPartially, recoverAB) where import Plutarch.Prelude import GHC.Generics (Generic) ``` -------------------------------- ### Construct a PList with pcon (pFeList) Source: https://plutarch-plutus.org/Types/PList.html Constructs a PList PByteString with a single element 0xfe using pcon and the PSCons/PSNil constructors. The source notes that pcons # phexByteStr "fe" # pnil is an alternative. ```haskell pFeList :: forall s. Term s (PList PByteString) pFeList = pcon $ PSCons (phexByteStr "fe") $ pcon PSNil ``` -------------------------------- ### Haskell Vehicle type Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html Haskell type with three constructors, used as the source type for the Plutarch PIsData example. The constructor order matters when deriving PIsData. ```haskell data Vehicle = FourWheeler Integer Integer Integer Integer | TwoWheeler Integer Integer | ImmovableBox ``` -------------------------------- ### Module imports for DelayAndForce Source: https://plutarch-plutus.org/Introduction/DelayAndForce.html Sets up the module with the required Plutarch imports and disables deprecation warnings. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.DelayAndForce (hif, pif') where import Plutarch.Prelude ``` -------------------------------- ### Match on PBuiltinList with pelimList Source: https://plutarch-plutus.org/Types/PBuiltinList.html Uses pelimList from PListLike to match on a PBuiltinList. The first argument handles the PCons case, the second is the empty-list value (evaluated only if the list is empty), and the third is the list. ```haskell matchOnList' :: forall s. Term s PString matchOnList' = pelimList (\_ _ -> "oooo fancy") "hey hey there's nothing here!" $ pcon $ PCons (phexByteStr "fe") $ pcon PNil ``` -------------------------------- ### Tree datatype definition Source: https://plutarch-plutus.org/Concepts/GenericProgramming.html Defines a Haskell datatype Tree with two constructors: Leaf holding an Int and Node holding two Tree values. This is the example datatype used to illustrate Scott and Data encoding. ```haskell data Tree = Leaf Int | Node Tree Tree ``` -------------------------------- ### Implement pcon' for Booleans Source: https://plutarch-plutus.org/DEVGUIDE.html Demonstrates creating Plutarch terms that evaluate to Plutus Core boolean constants. ```haskell import qualified PlutusCore as PLC pcon' PTrue = punsafeConstant . PLC.Some $ PLC.ValueOf PLC.DefaultUniBool True pcon' PFalse = punsafeConstant . PLC.Some $ PLC.ValueOf PLC.DefaultUniBool False ``` -------------------------------- ### Original pmatch pattern matching Source: https://plutarch-plutus.org/Usage/DoSyntaxWithTermCont.html Shows the original, less ergonomic pattern matching with pmatch and a continuation. It traces a message on success and an error on failure. ```haskell test :: Term s (PScriptPurpose :--> PUnit) test = plam $ \x -> pmatch x $ \case PSpending _ -> ptraceInfo "matched spending script purpose" $ pconstant () _ -> ptraceInfoError "pattern match failure" ``` -------------------------------- ### Dynamic Constant Construction with pcon Source: https://plutarch-plutus.org/Introduction/PlutarchTerms/PlutarchConstants.html Using pcon to construct a PMaybe term from a runtime value. ```haskell -- pcon :: a s -> Term s a -- For example: x' :: forall s . Term s PInteger x' = pconstant 3 justTerm :: forall s . Term s (PMaybe PInteger) justTerm = pcon (PJust x') ``` -------------------------------- ### Match a PList with pmatch (pFe) Source: https://plutarch-plutus.org/Types/PList.html Matches on a PList using pmatch and pattern matching on the PSNil and PSCons constructors. The source recommends preferring pelimList from PListLike instead. ```haskell pFe :: forall s. Term s PString pFe = pmatch (pcon $ PSCons (phexByteStr "fe") $ pcon PSNil) $ \case PSNil -> "hey hey there's nothing here!" PSCons _ _ -> "oooo fancy!" ``` -------------------------------- ### A validator that checks a signatory is present, with context and mock evaluation Source: https://plutarch-plutus.org/examples/VALIDATOR.html A more complex validator that selects the `Spending` script info, retrieves the transaction signatories, and checks if a given `PubKeyHash` is present; otherwise it fails. The mock context shows how to build a `ScriptContext` with signatories and the evaluation passes with a `Right` result. Requires GHC 9 extensions `QualifiedDo` and `OverloadedRecordDot` and uses `pmatchC`, `pif`, and `pelem`. ```haskell __ checkSignatory :: Term s (PubKeyHash :--> PData PDatum :--> PData PRedeemer :--> PScriptContext :--> PUnit) checkSignatory = plam $ \ph datm redm ctx' -> unTermCont $ do ctx' <- pmatchC ctx' SpendingScript [] <- pmatchC $ pscriptContext'scriptInfo ctx' txInfo <- pmatchC $ pscriptContext'txInfo ctx' let signatories = ptxInfo'signatories txInfo pure $ pif (pelem # pdata ph # pfromData signatories) -- Success! (pconstant ()) -- Signature not present. perror ``` ```haskell {-# LANGUAGE OverloadedStrings #-} import Plutus.V1.Ledger.Api import Plutus.V1.Ledger.Interval import qualified PlutusTx hashStr :: PubKeyHash hashStr = "abce0f123e" pubKeyHash :: Term s PPubKeyHash pubKeyHash = pconstant hashStr mockCtx :: ScriptContext mockCtx = ScriptContext (TxInfo mempty mempty mempty mempty mempty mempty (interval (POSIXTime 1) (POSIXTime 2)) [fromString hashStr, "f013", "ab45"] mempty "" ) (Spending (TxOutRef "" 1)) > evalWithArgsT (checkSignatory # pubKeyHash) [PlutusTx.toData (), PlutusTx.toData (), PlutusTx.toData mockCtx] Right (Program () (Version () 1 0 0) (Constant () (Some (ValueOf unit ())))) ``` -------------------------------- ### Implement PTryFrom for custom datatype PAB Source: https://plutarch-plutus.org/Typeclasses/PTryFrom.html Shows how to implement PTryFrom for a custom datatype PAB using the generic default. Defines the datatype, derives PlutusTypeData, and provides a PTryFrom instance. Also demonstrates recovering an AB from opaque PData using ptryFrom. ```haskell -- your datatype data PAB (s :: S) = PA (Term s (PDataRecord '["_0" ':= PInteger, "_1" ':= PByteString])) | PB (Term s (PDataRecord '["_0" ':= PBuiltinList (PAsData PInteger), "_1" ':= PByteString])) deriving stock (Generic) deriving anyclass (PlutusType, PIsData) -- getting the generic `Data` representation for your type instance DerivePlutusType PAB where type DPTStrat _ = PlutusTypeData -- getting a generic `PTryFrom` instance that recovers your type -- from an opaque `PData` instance PTryFrom PData (PAsData PAB) -- a valid AB sampleAB :: Term s (PAsData PAB) sampleAB = pdata $ pcon $ PA (pdcons @"_0" # pdata (pconstant 4) #$ pdcons # pdata (pconstant "foo") # pdnil) -- we forget the structure of our `sampleAB` sampleABdata :: Term s PData sampleABdata = pforgetData sampleAB -- recovers an `AB` from an opaque `PData` recoverAB :: Term s (PAsData PAB) recoverAB = unTermCont $ fst <$> tcont (ptryFrom sampleABdata) ``` -------------------------------- ### Evaluating txInfoInputs extraction Source: https://plutarch-plutus.org/DEVGUIDE.html Testing the extraction function on the mock context. ```haskell __ > f `evalWithArgsT` [PlutusTx.toData mockCtx] Right (Program () (Version () 1 0 0) (Constant () (Some (ValueOf list (data) [Constr 0 [Constr 0 [Constr 0 [B ""],I 1],Constr 0 [Constr 0 [Constr 0 [B "\SOH#"],Constr 1 []],Map [],Constr 1 []]]])))) ``` -------------------------------- ### Optimizing with plet Source: https://plutarch-plutus.org/Tricks/DontDuplicateWork.html Implementation of 'pf'' using the 'plet' function to bind the expression and avoid redundant computation. ```haskell {- Note: the letter labels on our annotations match the operations in the previous example. -} pf' :: Term s PInteger pf' = plet (1 + 2) $ -- | D.') Calculate the desired value here (strictly),... \foo -> -- | A.') ...introduce a lambda abstraction,... pif (foo #== 3) -- | B.') ...and apply the argument here... foo -- | C.') ... and here. 7 ``` -------------------------------- ### Recommended: plet before immediate pmatch match Source: https://plutarch-plutus.org/Tricks/PreferMatchingOnPmatchResultImmediately.html Recommended pattern: plet is placed before pmatch, but the pattern match on the pmatch result is immediate, avoiding inlining and extra lambdas. ```haskell this' :: Term s (PScriptPurpose :--> PInteger) this' = plam $ \x -> plet (1 + 2) $ \i -> pmatch x $ \case PMinting _ -> i + 3 PSpending _ -> i + 4 PRewarding _ -> i + 5 PCertifying _ _ -> i + 6 PVoting _ -> i + 7 PProposing _ _ -> i + 8 ``` -------------------------------- ### pfoo' specialized to PBuiltinList Source: https://plutarch-plutus.org/Typeclasses/PListLike.html Shows the specialization of pfoo for PBuiltinList, where the constraint simplifies to PLiftable. ```haskell pfoo' :: PLiftable a => Term s (PBuiltinList a :--> PBuiltinList a) pfoo' = undefined ``` -------------------------------- ### Create Plutarch synonym for HeadList with one force Source: https://plutarch-plutus.org/DEVGUIDE.html Defines pheadBuiltin for the HeadList builtin, which has one type variable and thus requires one force using pforce. ```haskell pheadBuiltin :: Term s (PBuiltinList a :--> a) pheadBuiltin = pforce $ punsafeBuiltin PLC.HeadList ``` -------------------------------- ### Partial recovery with ptryFrom for PAsData (PBuiltinList PData) Source: https://plutarch-plutus.org/Typeclasses/PTryFrom.html Defines a helper that uses ptryFrom to recover a PAsData (PBuiltinList PData) and its excess PData from a PData, allowing partial verification of list structures to reduce fees. The excess is passed to the continuation, enabling cheaper access to only needed parts. ```haskell recoverListPartially :: forall r s. Term s PData -> ((Term s (PAsData (PBuiltinList PData)), Term s (PBuiltinList PData)) -> Term s r) -> Term s r recoverListPartially = ptryFrom @(PAsData (PBuiltinList PData)) @PData ``` -------------------------------- ### Mock ScriptContext and evaluation Source: https://plutarch-plutus.org/DEVGUIDE.html Defining a mock ScriptContext and evaluating the extraction function. ```haskell __ {-# LANGUAGE OverloadedStrings #-} import Plutus.V1.Ledger.Api import Plutus.V1.Ledger.Interval import qualified PlutusTx mockCtx :: ScriptContext mockCtx = ScriptContext (TxInfo [ TxInInfo (TxOutRef "" 1) (TxOut (Address (PubKeyCredential "0123") Nothing) mempty Nothing) ] mempty mempty mempty mempty mempty (interval (POSIXTime 1) (POSIXTime 2)) mempty mempty "" ) (Minting (CurrencySymbol "")) > f `evalWithArgsT` [PlutusTx.toData mockCtx] Right (Program () (Version () 1 0 0) (Constant () (Some (ValueOf data (Constr 0 [List [Constr 0 [Constr 0 [Constr 0 [B ""],I 1],Constr 0 [Constr 0 [Constr 0 [B "\SOH#"],Constr 1 []],Map [],Constr 1 []]]],List [],Map [],Map [],List [],List [],Constr 0 [Constr 0 [Constr 1 [I 1],Constr 1 []],Constr 0 [Constr 1 [I 2],Constr 1 []]],List [],List [],Constr 0 [B ""]]))))) ``` -------------------------------- ### Perform integer division with pdiv Source: https://plutarch-plutus.org/Typeclasses/PIntegral.html Demonstrates the usage of pdiv to perform division on two Term s PInteger values. ```haskell __ pdiv # 6 # 3 ``` -------------------------------- ### Evaluation of alwaysSucceeds with `evalWithArgsT` Source: https://plutarch-plutus.org/examples/VALIDATOR.html Shows how to evaluate `alwaysSucceeds` with three empty `PlutusTx` data units, producing the displayed output right-side. ```haskell res' :: Either Text (Script, ExBudget, [Text]) res' = alwaysSucceeds `evalWithArgsT` [PlutusTx.toData (), PlutusTx.toData (), PlutusTx.toData ()] -- >>> res' -- Right (Program () (Version () 1 0 0) ) ``` -------------------------------- ### Plutarch Tracing Module Imports Source: https://plutarch-plutus.org/Usage/Tracing.html Basic module definition and imports for Plutarch tracing. ```haskell __ module Plutarch.Docs.Tracing () where import Plutarch.Prelude () ``` -------------------------------- ### PIsData instance for PInteger Source: https://plutarch-plutus.org/Typeclasses/PIsData.html Provides the PIsData instance for PInteger. pfromData uses pasInt to extract the integer from an I data value, while pdata wraps the integer into an I data value using punsafeBuiltin PLC.IData. ```haskell instance PIsData PInteger where pfromData x = pasInt # pforgetData x pdata x = punsafeBuiltin PLC.IData # x ``` -------------------------------- ### Construct a Plutus Core List Constant Source: https://plutarch-plutus.org/DEVGUIDE.html Uses DefaultUniApply to specify the element type for a DefaultUniProtoList. ```haskell import qualified PlutusCore as PLC PLC.Some . PLC.ValueOf (PLC.DefaultUniProtoList `PLC.DefaultUniApply` PLC.DefaultUniInteger) ``` -------------------------------- ### Module header for UsingHaskellLevelFunctions Source: https://plutarch-plutus.org/Tricks/UsingHaskellLevelFunctions.html Module header for the Plutarch.Docs.UsingHaskellLevelFunctions module, exporting pelimList and pelimList'. It imports Data.Kind for Type and Plutarch.Prelude while hiding pelimList to avoid conflicts. ```haskell module Plutarch.Docs.UsingHaskellLevelFunctions (pelimList, pelimList') where import Data.Kind (Type) import Plutarch.Prelude hiding (pelimList) ``` -------------------------------- ### Creating PByteString terms with phexByteStr and pconstant Source: https://plutarch-plutus.org/Types/PByteString.html Shows two ways to create Plutarch-level bytestring terms: phexByteStr interprets a hex string literal, and pconstant converts a ByteString. The comments show the resulting byte values. ```haskell notQuiteTheAnswer :: forall s. Term s PByteString notQuiteTheAnswer = phexByteStr "41" -- yields a `Term s PByteString`, which represents [65] aChar :: forall s. Term s PByteString aChar = pconstant (BS.pack [91]) -- yields a `Term s PByteString`, which represents [91] ``` -------------------------------- ### Evaluation of foo nothing Source: https://plutarch-plutus.org/Concepts/DataAndScottEncoding.html Step-by-step evaluation of foo nothing showing the Nothing case returns 0. ```haskell foo nothing foo (\_ n -> n) (\_ n -> n) (\x -> x + 42) 0 0 ``` -------------------------------- ### Eliminate a PList with pelimList (pFeElim) Source: https://plutarch-plutus.org/Types/PList.html Uses pelimList from PListLike to eliminate a PList, providing a function for the cons case and a default for the nil case. This is the preferred alternative to pmatch. ```haskell pFeElim :: forall s. Term s PString pFeElim = pelimList (\_ _ -> "oooo fancy") "hey hey there's nothing here!" $ pcon $ PSCons (phexByteStr "fe") $ pcon PSNil ``` -------------------------------- ### fooConcrete: PAsData PByteString to PAsData PByteString Source: https://plutarch-plutus.org/Types/PAsData.html Defines a function that takes and returns a PAsData PByteString, providing assurance that the Data value represents a builtin bytestring. ```haskell fooConcrete :: Term s (PAsData PByteString :--> PAsData PByteString) fooConcrete = undefined ``` -------------------------------- ### Module header for Plutarch.Docs.Hoisting Source: https://plutarch-plutus.org/Concepts/Hoisting.html Module header for the Plutarch hoisting documentation. It enables the deprecation warning suppression and imports Plutarch.Prelude while hiding the (#||) operator to define it locally. ```haskell {-# OPTIONS_GHC -Wno-deprecations #-} module Plutarch.Docs.Hoisting (hor, (#||)) where import Plutarch.Prelude hiding ((#||)) ``` -------------------------------- ### Create Plutarch synonym for AddInteger using punsafeBuiltin Source: https://plutarch-plutus.org/DEVGUIDE.html Defines addI as a Plutarch term for the Plutus Core AddInteger builtin. Requires the correct type annotation, as with punsafeConstant. ```haskell import qualified PlutusCore as PLC addI :: Term s (PInteger :--> PInteger :--> PInteger) addI = punsafeBuiltin PLC.AddInteger ``` -------------------------------- ### Hoisting a top-level Plutarch function with phoistAcyclic Source: https://plutarch-plutus.org/Concepts/Hoisting.html Recommended pattern for hoisting top-level Plutarch functions with phoistAcyclic. Works as long as the Plutarch lambda has no free variables. ```haskell foo = phoistAcyclic $ plam $ \x -> ``` -------------------------------- ### Type signatures for pdcons and pdnil Source: https://plutarch-plutus.org/Types/PDataSumAndPDataRecord.html Shows the types of pdcons and pdnil, the cons and nil for PDataRecord terms. ```haskell pdcons :: forall label a l s. Term s (PAsData a :--> PDataRecord l :--> PDataRecord ((label ':= a) ': l)) pdnil :: forall s. Term s (PDataRecord '[]) ``` -------------------------------- ### PIsData instance for PBuiltinList Source: https://plutarch-plutus.org/Typeclasses/PIsDataReprAndPDataFields.html PIsData instance for PBuiltinList, restricted to PAsData elements. Use PBuiltinList (PAsData PInteger) as a field type, not PBuiltinList PInteger. ```haskell instance PIsData a => PIsData (PBuiltinList (PAsData a)) ```