plutus-ledger-api-1.60.0.0: Interface to the Plutus ledger for the Cardano ledger.
Safe HaskellSafe-Inferred
LanguageHaskell2010

PlutusLedgerApi.Common

Description

The types and functions that are common among all ledger Plutus versions.

Synopsis

serialiseUPLC :: DefaultFun () -> SerialisedScript #

Turns a program's AST (most likely manually constructed) into a binary format that is understood by the network and can be stored on-chain.

deserialiseScript #

Arguments

:: forall m. MonadError ScriptDecodeError m 
=> PlutusLedgerLanguage

the Plutus ledger language of the script.

-> MajorProtocolVersion

which major protocol version the script was submitted in.

-> SerialisedScript

the script to deserialise.

-> m ScriptForEvaluation 

The deserialization from a serialised script into a ScriptForEvaluation, ready to be evaluated on-chain. Called inside phase-1 validation (i.e., deserialisation error is a phase-1 error).

uncheckedDeserialiseUPLC :: SerialisedScript -> DefaultFun () #

Deserialises a SerialisedScript back into an AST. Does *not* do ledger-language-version-specific checks like for allowable builtins.

data ScriptDecodeError #

An error that occurred during script deserialization.

Constructors

CBORDeserialiseError !DeserialiseFailureInfo

an error from the underlying CBOR/serialise library

RemainderError !ByteString

Script was successfully parsed, but more (runaway) bytes encountered after script's position

LedgerLanguageNotAvailableError

the plutus version of the given script is not enabled yet

Fields

PlutusCoreLanguageNotAvailableError 

Fields

Instances

Instances details
DefaultFun ()))))

Script evaluation

evaluateScriptCounting #

Arguments

:: PlutusLedgerLanguage

The Plutus ledger language of the script under execution.

-> MajorProtocolVersion

Which major protocol version to run the operation in

-> VerboseMode

Whether to produce log output

-> EvaluationContext

Includes the cost model to use for tallying up the execution costs

-> ScriptForEvaluation

The script to evaluate

-> [Data]

The arguments to the script

-> (LogOutput, Either EvaluationError ExBudget) 

Evaluates a script, returning the minimum budget that the script would need to evaluate successfully. This will take as long as the script takes, if you need to limit the execution time of the script also, you can use evaluateScriptRestricting, which also returns the used budget.

Note: Parameterized over the ledger-plutus-version since the builtins allowed (during decoding) differs.

evaluateScriptRestricting #

Arguments

:: PlutusLedgerLanguage

The Plutus ledger language of the script under execution.

-> MajorProtocolVersion

Which major protocol version to run the operation in

-> VerboseMode

Whether to produce log output

-> EvaluationContext

Includes the cost model to use for tallying up the execution costs

-> ExBudget

The resource budget which must not be exceeded during evaluation

-> ScriptForEvaluation

The script to evaluate

-> [Data]

The arguments to the script

-> (LogOutput, Either EvaluationError ExBudget) 

Evaluates a script, with a cost model and a budget that restricts how many resources it can use according to the cost model. Also returns the budget that was actually used.

Can be used to calculate budgets for scripts, but even in this case you must give a limit to guard against scripts that run for a long time or loop.

Note: Parameterized over the LedgerPlutusVersion since 1. The builtins allowed (during decoding) differ, and 2. The Plutus language versions allowed differ.

evaluateTerm :: DefaultFun #

Evaluate a fully-applied term using the CEK machine. Useful for mimicking the behaviour of the on-chain evaluator.

data VerboseMode #

A simple toggle indicating whether or not we should accumulate logs during script execution.

Constructors

Verbose

accumulate all traces

Quiet

don't accumulate anything

Instances

Instances details
FreeVariableError

An error in the pre-evaluation step of converting from de-Bruijn indices

CodecError !ScriptDecodeError

A deserialisation error TODO: make this error more informative when we have more information about what went wrong

CostModelParameterMismatch

An error indicating that the cost model parameters didn't match what we expected

InvalidReturnValue

The script evaluated to a value that is not a valid return value.

Instances

Instances details
Doc ann #

Network's versioning

The network's behaviour (and plutus's by extension) can change via hard forks, which directly correspond to major-number protocol version bumps.

newtype MajorProtocolVersion #

This represents the major component of the Cardano protocol version. The ledger can only supply the major component of the protocol version, not the minor component, and Plutus should only need to care about the major component anyway. This relies on careful understanding between us and the ledger as to what this means.

Constructors

MajorProtocolVersion 
Decoder s [MajorProtocolVersion] #

type Rep MajorProtocolVersion # 
Instance details

Defined in PlutusLedgerApi.Common.ProtocolVersions

type Rep MajorProtocolVersion = D1 ('MetaData "MajorProtocolVersion" "PlutusLedgerApi.Common.ProtocolVersions" "plutus-ledger-api-1.60.0.0-inplace" 'True) (C1 ('MetaCons "MajorProtocolVersion" 'PrefixI 'True) (S1 ('MetaSel ('Just "getMajorProtocolVersion") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int)))

data PlutusLedgerLanguage #

The Plutus ledger language. These are entirely different script languages from the ledger's perspective, which on our side are interpreted in very similar ways.

It is a simple enumerated datatype (there is no major and minor components as in protocol version) and the ordering of constructors is essential for deriving Enum,Ord,Bounded.

IMPORTANT: this is different from the Plutus Core language version, Version

Constructors

PlutusV1

introduced in Alonzo HF

PlutusV2

introduced in Vasil HF

PlutusV3

introduced in Chang HF

Instances

Instances details
Doc ann #

Decoder s [PlutusLedgerLanguage] #

type Rep PlutusLedgerLanguage # 
Instance details

Defined in PlutusLedgerApi.Common.Versions

type Rep PlutusLedgerLanguage = D1 ('MetaData "PlutusLedgerLanguage" "PlutusLedgerApi.Common.Versions" "plutus-ledger-api-1.60.0.0-inplace" 'False) (C1 ('MetaCons "PlutusV1" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "PlutusV2" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "PlutusV3" 'PrefixI 'False) (U1 :: Type -> Type)))

data Version #

The version of Plutus Core used by this program.

The intention is to convey different levels of backwards compatibility for existing scripts: - Major version changes are backwards-incompatible - Minor version changes are backwards-compatible - Patch version changes should be entirely invisible (and we will likely not use this level)

The version used should be changed only when the language itself changes. For example, adding a new kind of term to the language would require a minor version bump; removing a kind of term would require a major version bump.

Similarly, changing the semantics of the language will require a version bump, typically a major one. This is the main reason why the version is actually tracked in the AST: we can have two language versions with identical ASTs but different semantics, so we need to track the version explicitly.

Compatibility is about compatibility for specific scripts, not about e.g. tools which consume scripts. Adding a new kind of term does not change how existing scripts behave, but does change what tools would need to do to process scripts.

Constructors

Version 

Fields

  • _versionMajor :: DefaultFun) #

    Given a ledger language, return a map indicating which builtin functions were introduced in which MajorProtocolVersion. This must be updated when new builtins are added. It is not necessary to add entries for protocol versions where no new builtins are added. See Note [New builtins/language versions and protocol versions]

builtinsAvailableIn :: PlutusLedgerLanguage -> MajorProtocolVersion -> DefaultFun #

Return a set containing the builtins which are available in a given LL in a given PV. All builtins are available in all LLs from vanRossemPV onwards.

ledgerLanguageIntroducedIn :: PlutusLedgerLanguage -> MajorProtocolVersion #

Query the protocol version that a specific Plutus ledger language was first introduced in.

ledgerLanguagesAvailableIn :: MajorProtocolVersion -> Set PlutusLedgerLanguage #

Which Plutus language versions are available in the given MajorProtocolVersion? See Note [New builtins/language versions and protocol versions]. This function (and others in this module) assumes that once a LL is available it remains available in all later PVs and that if m <= n, PlutusVm is introduced no later than PlutusVn.

Protocol Versions

shelleyPV :: MajorProtocolVersion #

Shelley era was introduced in protocol version 2.0

allegraPV :: MajorProtocolVersion #

Allegra era was introduced in protocol version 3.0

maryPV :: MajorProtocolVersion #

Mary era was introduced in protocol version 4.0

alonzoPV :: MajorProtocolVersion #

Alonzo era was introduced in protocol version 5.0

vasilPV :: MajorProtocolVersion #

The Vasil HF introduced the Babbage era and Plutus V2

valentinePV :: MajorProtocolVersion #

Valentine was an intra-era HF where builtin functions VerifyEcdsaSecp256k1Signature and VerifySchnorrSecp256k1Signature were enabled.

changPV :: MajorProtocolVersion #

The Chang HF introduced the Conway era and Plutus V3

plominPV :: MajorProtocolVersion #

The Plomin HF was an intra-era HF where some new builtin functions were introduced in Plutus V2 and V3.

vanRossemPV :: MajorProtocolVersion #

The van Rossem HF will be an intra-era HF.

knownPVs :: [MajorProtocolVersion] #

The set of protocol versions that are "known", i.e. that have been released and have actual differences associated with them. This is currently only used for testing, so efficiency is not parmount and a list is fine.

Costing-related types

data ExBudget #

Constructors

ExBudget 

Instances

Instances details
PlutusCore.Evaluation.Machine.ExBudget

type Rep ExBudget = D1 ('MetaData "ExBudget" "PlutusCore.Evaluation.Machine.ExBudget" "plutus-core-1.60.0.0-inplace" 'False) (C1 ('MetaCons "ExBudget" 'PrefixI 'True) (S1 ('MetaSel ('Just "exBudgetCPU") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedUnpack) (Rec0 ExCPU) :*: S1 ('MetaSel ('Just "exBudgetMemory") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedUnpack) (Rec0 ExMemory)))

newtype ExCPU #

Counts CPU units in picoseconds: maximum value for SatInt is 2^63 ps, or appproximately 106 days.

Constructors

ExCPU Data.SatInt

Associated Types

type Rep SatInt :: Type -> Type #

Methods

from :: SatInt -> Rep SatInt x #

to :: Rep SatInt x -> SatInt #

Num SatInt

In the Num instance, we plug in our own addition, multiplication and subtraction function that perform overflow-checking.

Instance details

Defined in Data.SatInt

type Rep SatInt = D1 ('MetaData "SatInt" "Data.SatInt" "plutus-core-1.60.0.0-inplace-satint" 'True) (C1 ('MetaCons "SI" 'PrefixI 'True) (S1 ('MetaSel ('Just "unSatInt") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int)))

fromSatInt :: Num a => SatInt -> a #

An optimized version of fromIntegral . unSatInt.

Network's costing parameters

A less drastic approach (that does not rely on a HF) to affect the network's (and plutus's by extension) behaviour is by tweaking the values of the cost model parameters.

The network does not associate names to cost model parameters; Plutus attaches names to the network's cost model parameters (values) either in a raw textual form or typed by a specific plutus version.

See Note [Cost model parameters]

type CostModelParams = Text Int64 #

A raw representation of the ledger's cost model parameters.

The associated keys/names to the parameter values are arbitrarily set by the plutus team; the ledger does not hold any such names.

See Note [Cost model parameters]

toCostModelParams :: IsParamName p => [(p, Int64)] -> CostModelParams #

Untags the plutus version from the typed cost model parameters and returns their raw textual form (internally used by CostModelInterface).

class (Enum a, Bounded a) => IsParamName a where #

A parameter name for different plutus versions.

Each Plutus version should expose such an enumeration as an ADT and create an instance of ParamName out of it.

A valid parameter name has to be enumeration, bounded, ordered, and prettyprintable to a "lower-Kebab" string.

Minimal complete definition

showParamName

Methods

showParamName :: a -> Text #

Produce the raw textual form for a given typed-by-plutus-version cost model parameter Any implementation *must be* an injective function. The GIsParamName generic implementation guarantees injectivity.

readParamName :: Doc ann #

Evaluation context

data EvaluationContext #

An opaque type that contains all the static parameters that the evaluator needs to evaluate a script. This is so that they can be computed once and cached, rather than being recomputed on every evaluation.

Different protocol versions may require different bundles of machine parameters, which allows us for example to tweak the shape of the costing function of a builtin, so that the builtin costs less. Currently this means that we have to create multiple DefaultMachineParameters per language version, which we put into a cache (represented by an association list) in order to avoid costly recomputation of machine parameters.

In order to get the appropriate DefaultMachineParameters at validation time we look it up in the cache using a semantics variant as a key. We compute the semantics variant from the protocol version using the stored function. Note that the semantics variant depends on the language version too, but the latter is known statically (because each language version has its own evaluation context), hence there's no reason to require it to be provided at runtime.

To say it differently, there's a matrix of semantics variants indexed by (LL, PV) pairs and we cache its particular row corresponding to the statically given LL in an EvaluationContext.

The reason why we associate a DefaultMachineParameters with a semantics variant rather than a protocol version are

  1. generally there are far more protocol versions than semantics variants supported by a specific language version, so we save on pointless duplication of bundles of machine parameters
  2. builtins don't know anything about protocol versions, only semantics variants. It is therefore more semantically precise to associate bundles of machine parameters with semantics variants than with protocol versions

Constructors

EvaluationContext 

Fields

Instances

Instances details
DefaultFun) -> CostModelParams -> m EvaluationContext #

Create an EvaluationContext given all builtin semantics variants supported by the provided language version.

The input is a Map of Texts to cost integer values (aka CostModelParams, CostModel) See Note [Inlining meanings of builtins].

IMPORTANT: the toSemVar argument computes the semantics variant for each MajorProtocolVersion and it must only return semantics variants from the semVars list, as well as cover ANY MajorProtocolVersion, including those that do not exist yet (i.e. toSemVar must never fail).

IMPORTANT: The evaluation context of every Plutus version must be recreated upon a protocol update with the updated cost model parameters.

 

Shared helper for the evaluation functions: evaluateScriptCounting and evaluateScriptRestricting,

Given a ScriptForEvaluation:

1) applies the term to a list of Data arguments (e.g. Datum, Redeemer, ScriptContext) 2) checks that the applied-term is well-scoped 3) returns the applied-term

Supporting types used in the context types

Builtins

data BuiltinByteString #

An opaque type representing Plutus Core ByteStrings.

Instances

Instances details
HasFromOpaque arep a => arep -> a #

Data

data Data #

A generic "data" type.

The main constructor Constr represents a datatype value in sum-of-products form: Constr i args represents a use of the ith constructor along with its arguments.

The other constructors are various primitives.

Constructors

Constr DefaultUni Data)

data BuiltinData #

A type corresponding to the Plutus Core builtin equivalent of Data.

The point of this type is to be an opaque equivalent of Data, so as to ensure that it is only used in ways that the compiler can handle.

As such, you should use this type in your on-chain code, and in any data structures that you want to be representable on-chain.

For off-chain usage, there are conversion functions builtinDataToData and dataToBuiltinData, but note that these will not work on-chain.

Constructors

BuiltinData ~Data 

Instances

Instances details
BuiltinBLS12_381_G1_Element

For the BLS12-381 G1 and G2 types we use the compress functions to convert to a ByteString and then encode that as Data as usual. We have to be more careful going the other way because we decode a Data object to (possibly) get a BuiltinByteString and then uncompress the underlying ByteString to get a group element. However uncompression can fail so we have to check what happens: we don't use bls12_381_G?_uncompress because that invokes error if something goes wrong (but we do use it for unsafeFromData).

Instance details

Defined in BuiltinBLS12_381_MlResult

We do not provide instances of any of these classes for BuiltinBLS12_381_MlResult since there is no serialisation format: we expect that values of that type will only occur as the result of on-chain computations.

Instance details

Defined in PlutusTx.IsData.Class

Methods

toBuiltinData :: [a] -> BuiltinData #

(ToData k, ToData v) => ToData (Map k v)

Hand-written instances to use the underlying Map type in Data, and to be reasonably efficient.

Instance details

Defined in PlutusTx.IsData.Class

(FromData k, FromData v) => FromData (Map k v)

A hand-written transformation from Data to Map. Compared to unsafeFromBuiltinData, it is safe to call when it is unknown if the Data is built with Datas Map constructor. Note that it is, however, unsafe in the sense that it assumes that any map encoded in the Data is well-formed, i.e. fromBuiltinData does not perform any deduplication of keys or of key-value pairs!

Instance details

Defined in error if this fails. This is typically much faster than fromBuiltinData.

When implementing this function, make sure to call unsafeFromBuiltinData rather than fromBuiltinData when converting substructures!

This is a simple type without any validation, use with caution.

Instances

Instances details
UnsafeFromData PlutusTx.IsData.Class

(UnsafeFromData k, UnsafeFromData v) => UnsafeFromData (Map k v)

A hand-written transformation from Data to Map. It is unsafe because the caller must provide the guarantee that the Data is constructed using the Datas Map constructor. Note that it assumes, like the fromBuiltinData transformation, that the map encoded in the Data is well-formed, i.e. unsafeFromBuiltinData does not perform any deduplication of keys or of key-value pairs!

Instance details

Defined in These a b #

toData :: ToData a => a -> Data #

Convert a value to Data.

Note: off-chain only.

fromData :: FromData a => Data -> Maybe a #

Convert a value from Data, returning Nothing if this fails.

Note: off-chain only.

unsafeFromData :: UnsafeFromData a => Data -> a #

Convert a value from Data, throwing if this fails.

Note: off-chain only.

dataToBuiltinData :: Data -> BuiltinData #

NOT a builtin. Converts a Data into a BuiltinData. Only works off-chain.

builtinDataToData :: BuiltinData -> Data #

NOT a builtin. Converts a BuiltinData into a Data. Only works off-chain.

Misc

class Monad m => MonadError e (m :: Type -> Type) | m -> e #

The strategy of combining computations that can throw exceptions by bypassing bound functions from the point an exception is thrown to the point that it is handled.

Is parameterized over the type of error information and the monad type constructor. It is common to use Either String as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the MonadError class. You can also define your own error type and/or use a monad type constructor other than Either String or Either IOError. In these cases you will have to explicitly define instances of the MonadError class. (If you are using the deprecated Control.Monad.Error or Control.Monad.Trans.Error, you may also have to define an Error instance.)

Minimal complete definition

BuiltinFailure logs. This is to compensate for the historical lack of error message content in operational errors (structural ones don't have this problem) in our evaluators (the CK and CEK machines). It would be better to fix the underlying issue and allow operational evaluation errors to carry some form of content, but for now we just fix the symptom in order for the end user to see the error message that they are supposed to see. The fix even makes some sense: what we do here is we emulate logging when the thrown unlifting error is an operational one, i.e. this is similar to what some builtins do manually (like when a crypto builtin fails and puts info about the failure into the logs).

Instance details

Defined in CekM uni fun s a #