Writing Your First Plutus Smart Contract


3) Writing Your First Plutus Code

Your smart contract, which lives on-chain, is also called a ValidatorScript. All Plutus code you write will exist inside of the ValidatorScript. We will now begin by writing our very first ValidatorScript.

In Haskell, typically we write the type of the function/value which we are creating first. This is called it’s type signature.

myFirstValidator :: ValidatorScript

This means that the name of our ValidatorScript we are creating is myFirstValidator and after the :: is it’s type. In our case the type is ValidatorScript. Now we will begin writing the definition of myFirstValidator.

myFirstValidator = ...

We write definitions by writing the name first and then an =. Next we need to create a ValidatorScript thus we must use it’s constructor to do so.

myFirstValidator = ValidatorScript (...)

This uses concepts which are outside of scope for this tutorial, but if you are interested in learning how Template Haskell and GHC plugins are used to generate Plutus Core code check out the IOHK Plutus Repository. We now need to use a bit of “magic” in order to allow the compiler to compile the Plutus code.

myFirstValidator = ValidatorScript (fromCompiledCode $$(PlutusTx.compile [|| ||]) )

In short, our Plutus code will live between the [|| and ||]. This is where all of our logic for the on-chain code will live. To finish creating our first empty ValidatorScript we will need to write a lambda function (an unnamed/anonymous function) which takes 3 inputs and returns a value.

myFirstValidator = ValidatorScript (fromCompiledCode $$(PlutusTx.compile
[|| \(a :: ()) (b :: ()) (c :: ()) -> () ||]) )

Lambda functions are created by using a \ following whatever inputs the function takes (in our case 3 inputs with an empty type () ), then a ->, and finally the body of the function. In our case the body is empty and does not use the 3 inputs (yet).

module MyFirstPlutusSmartContract where

import qualified Language.PlutusTx as PlutusTx
import Ledger

myFirstValidator :: ValidatorScript
myFirstValidator = ValidatorScript (fromCompiledCode $$(PlutusTx.compile
[|| \(a :: ()) (b :: ()) (c :: ()) -> () ||]))

We have now successfully written our first Plutus code. Compile the code to make sure it works and continue to the next section.

Get Updates

To keep up to date with the latest lessons, sign up and get them straight in your mailbox.
You can also follow us on Twitter or join our Telegram channel