Writing basic validator scripts

Validator scripts are the programs that can be used to lock transaction outputs on the chain. Validator scripts are Plutus Core programs, but we can use Plutus Tx to write them easily in Haskell.

Validator arguments

Validators receive some information from the validating node:

  • The redeemer, which is some script-specific data specified by the party spending the output.

  • The datum, which is some script-specific data specified by the party who created the output.

  • The validation context, which contains a representation of the spending transaction, as well as the index of the input whose validator is currently being run.

The validator is a function which receives these three inputs as arguments. The validating node is responsible for passing them in and running the validator.

The Data type

But how are the validator’s arguments passed? At least the redeemer and datum can be of different types depending on the script.

The answer is that we pass them as a generic structured data type Language.PlutusTx.Data.Data. Data is designed to make it easy to encode structured data into it, and to be itself encoded as CBOR.

Consequently, the validator scripts we will write in this tutorial take three arguments of type Data.

However, you will typically not want to use Data directly in your program, rather you will want to use your own datatypes. We can easily convert to and from Data with the Language.PlutusTx.IsData.Class.IsData typeclass.

You usually don’t need to write your own IsData instances. Instead, you can use the makeIsData Template Haskell function to generate one.

-- | A specific date.
newtype Date = Date Integer
-- | Either a specific end date, or "never".
data EndDate = Fixed Integer | Never

-- 'makeIsData' is a TemplateHaskell function that takes a type name and
-- generates an 'IsData' instance definition for it. It should work for most
-- types, including newtypes and sum types.
makeIsData ''Date
makeIsData ''EndDate

Signaling failure

The most important thing that a validator can do is fail. This indicates that the attempt to spend the output is invalid and that transaction validation should fail. A validator succeeds if it does not explicitly fail. The actual value returned by the validator is irrelevant.

How does a validator fail? It does so by using the Language.PlutusTx.Builtins.error builtin. Some other builtins may also trigger failure if they are used incorrectly (e.g. 1/0).

Validator functions

We write validator scripts as Haskell functions, which we compile with Plutus Tx into Plutus Core. The type of a validator function is Data -> Data -> Data -> (), that is, a function which takes three arguments of type Data, and returns a value of type () (“unit” or “the empty tuple” – since the return type doesn’t matter we just pick something trivial).

Here are two examples of simple validators that always succeed and always fail, respectively:

alwaysSucceeds :: Data -> Data -> Data -> ()
alwaysSucceeds _ _ _ = ()

alwaysFails :: Data -> Data -> Data -> ()
alwaysFails _ _ _ = error ()

-- We can use 'compile' to turn a validator function into a compiled Plutus Core program.
-- Here's a reminder of how to do it.
alwaysSucceedsCompiled :: CompiledCode PLC.DefaultUni (Data -> Data -> Data -> ())
alwaysSucceedsCompiled = $$(compile [|| alwaysSucceeds ||])

If we want to write a validator that uses types other than Data, we’ll need to use the functions from IsData to decode them. Importantly, fromData can fail: in our example if the Data in the second argument is not a correctly encoded Date then it will return Nothing, indicating that it couldn’t decode it. However, a decoding failure indicates a mistake in the transaction that was submitted, and so we can simply fail the validation.

Important

Unfortunately there’s no way to provide failure diagnostics when a validator fails on chain – it just fails. However, since transaction validation is entirely deterministic, you’ll always be informed of this before you submit the transaction to the chain, so you can debug it locally.

Here’s an example that uses our date types to check whether the date which was provided is less than the stored limit in the datum.

-- | Checks if a date is before the given end date.
beforeEnd :: Date -> EndDate -> Bool
beforeEnd (Date d) (Fixed e) = d <= e
beforeEnd (Date _) Never     = True

-- | Check that the date in the redeemer is before the limit in the datum.
validateDate :: Data -> Data -> Data -> ()
-- The 'check' function takes a 'Bool' and fails if it is false.
-- This is handy since it's more natural to talk about booleans.
validateDate datum redeemer _ = check $ case (fromData datum, fromData redeemer) of
    -- We can decode both the arguments at the same time: 'Just' means that
    -- decoding succeeded.
    (Just endDate, Just date) -> beforeEnd date endDate
    -- One or the other failed to decode.
    _                         -> False

Using the validation context

Validators have access to the validation context as their third argument. This will always be a value of type Ledger.Validation.ValidatorCtx encoded as Data.

The validation context gives validators a great deal of power, because it allows them to inspect other inputs and outputs of the current transaction. For example, here is a validator that will only accept the transaction if a particular payment is made as part of it.

validatePayment :: Data -> Data -> Data -> ()
validatePayment _ _ ctx = check $ case fromData ctx of
    Just valCtx ->
        -- The 'TxInfo' in the validation context is the representation of the
        -- transaction being validated
        let txinfo = valCtxTxInfo valCtx
        -- 'pubKeyOutputsAt' collects the 'Value' at all outputs which pay to
        -- the given public key hash
            values = pubKeyOutputsAt myKeyHash txinfo
        -- 'fold' sums up all the values, we assert that there must be more
        -- than 1 Ada (more stuff is fine!)
        in fold values `geq` adaValueOf 1
    _ -> False

This makes use of some useful functions from Ledger.Validation for working with validation contexts.

Automatically wrapping validator functions

It is annoying to have to manually decode all the arguments from Data and call check at the end. Fortunately, we provide the Ledger.Typed.Scripts.wrapValidator function to do this for you.

validateDate' :: Data -> Data -> Data -> ()
validateDate' = wrapValidator validateDateTyped
    where
        validateDateTyped :: EndDate -> Date -> ValidatorCtx -> Bool
        validateDateTyped endDate date _ = beforeEnd date endDate