Clarity Crash Course

The Stacks ecosystem has its own smart contract programming language called Clarity.

source: Hiro Blog

Intro

This is designed for people with some programming experience who are new to Clarity. You don't need prior smart contract development experience, but if you have experience with languages like Solidity, you'll pick this up quickly.

Once you've briefly familiarized yourself with the language, consider the Clarity Book or the course Clarity Universe to continue your learning.

Clarity is developed as a joint effort of Hiro PBC, Algorand, and various other stakeholders, that originally targets the Stacks blockchain.

Your First Clarity Smart Contract

We're going to walkthrough a basic Clarity smart contract using the Clarity Playground, an online REPL environment where you can write and run Clarity code in the browser. Visit that link and it will open up a new example contract for you on the left view, with an interactive REPL on the right view.

The example counter contract provided when visiting the Clarity Playground

Clarity Playground is a new tool to write and run Clarity code directly in the browser. With Clarity Playground, developers can test out concepts, try new ideas, or just, well…play around. Learn more here.

The example contract you'll see is a simple counter contract that will store the value of a count in a data variable and increment the count value by invoking a defined public function.

counter.clar
(define-data-var count uint u0)
(define-data-var contract-owner principal tx-sender)
(define-data-var cost uint u10)

(define-read-only (get-count)
  (var-get count)
)

(define-public (increment)
  (begin
    (print u"incrementing count")
    (ok (var-set count (+ (var-get count) u1)))
  )
)

Clarity's syntax is inspired by LISP: everything is an expression wrapped in parentheses. Function definitions, variable declarations, and parameters are lists inside lists. This makes Clarity concise and readable once you get used to it. Here are some characteristics of Clarity you'll notice:

1

Everything in parentheses is an expression

Clarity treats everything as expressions inside parentheses. Function definitions are calls to built-in functions; the function body is an expression. This uniformity helps reasoning about programs in Clarity.

2

Uses LISP-like nesting

Expect nested parentheses and expressions. You’ll often read code as lists inside lists, where each parentheses-enclosed group represents a call or expression.

In Clarity, there are public, private, and read-only functions:

  • public: can modify chain state and be called externally.

  • private: can modify state but only be called within the contract.

  • read-only: will fail if they attempt to modify state.

Let's expand on these ideas by walking through that example counter contract line by line.

Defining data variables

The built-in Clarity function of define-data-var allows you to define a new persisted variable for the contract. Only modifiable by the contract.

;; defining a `count` variable to store a variable unsigned integer value
(define-data-var count uint u0)

;; defining a `contract-owner` for a specific `principal` value
(define-data-var contract-owner principal tx-sender)

;; defining a `cost` variable with an initial unsigned integer value of 10
(define-data-var cost uint u10)

Defining a read-only function to read the current count value

The built-in Clarity function of define-read-only defines a public read-only function. Cannot modify data maps or call mutating functions. May return any type.

;; allows anyone to read the current `count` value in the contract
(define-read-only (get-count)
  (var-get count)
)

Defining a public function to increment the count value

This function prints a log event saying it's incrementing a counter, then reads the current counter, adds 1, saves it back on-chain, and returns success.

;; Defines a public function named increment that anyone can call
(define-public (increment)
  ;; Starts a begin block, which allows multiple expressions to run in order.
  (begin
    ;; Logs/prints the text "incrementing count" (as a Unicode string) to 
    ;; the transaction output or event stream.
    (print u"incrementing count")
    ;; adds u1 to the current count and wraps the resulting value in a response type
    (ok (var-set count (+ (var-get count) u1)))
  )
)

Interact With Your Contract

The Clarity Playground allows you to call your functions on the right side view via a REPL console that runs a simnet environment.

What is Simnet?

Simnet is optimized for providing fast feedback loops at the cost of correctness. Simnet does not provide a full simulated blockchain environment, so there are no concepts of transaction fees, new blocks, or consensus mechanisms.

Instead, simnet focuses on letting you quickly iterate on your code and test the code of the contract locally through unit testing and integration testing. It’s a good preliminary debugging step before introducing the additional variables that come with a fully-fledged blockchain environment.

Simnet is a local environment spun up on your machine and is a private instance—you cannot share a simnet environment with other devs and collaborate with them—and further, simnet has no persistent state. It resets with each run.

On page load of the Clarity Playground, the example counter contract is automatically deployed to the REPL console on the right side. If you made any changes to the contract in the code editor on the left view, be sure to click on Deploy.

Calling contracts in the console or calling any externally deployed contracts will need to be passed into the built-in Clarity function called contract-call? .

Follow the steps below to interact with your counter contract:

1

Call the read-only `get-count` function

In the bottom right Clarity command console, paste in the below command to call your get-count function to see the current count value.

clarity command console
(contract-call? .contract-0 get-count)

The console should return an initial value of u0 since we haven't incremented the count yet.

2

Call the public `increment` function

Now let's finally increment our count value. In the bottom right Clarity command console, paste in the below command to call your increment function, which will increment the count value by 1.

The console should return a value of (ok true) . This means the public function executed successfully and the count should have incremented.

clarity command console
(contract-call? .contract-0 increment)
3

Call our `get-count` function again

To see if our count value was really incremented, let's call our read-only get-count function once again.

clarity command console
(contract-call? .contract-0 get-count)

The console should now returns a value of u1 which is exactly what we'd expect.

Great! You just interacted with your first Clarity smart contract. Hopefully this gives you a good introduction to how the Clarity smart contract language looks and feels.


Read Access into Bitcoin

Smart contracts on the Stacks layer can read Bitcoin state and can be triggered by standard Bitcoin transactions. This is because Stacks nodes also run Bitcoin nodes as part of consensus, and they read and index Bitcoin state.

Reading Bitcoin state in Clarity is made by possible by the built-in function: get-burn-block-info? and the keyword burn-block-height .

  • burn-block-height : This keyword returns the current block height of the underlying burnchain: Bitcoin. Check out the example snippet below:

(> burn-block-height u1000) 
;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks.
  • get-burn-block-info? : This function fetches block data of the burnchain: Bitcoin. Check out the example snippet below:

(get-burn-block-info? header-hash u677050)
;; Returns (some 0xe671...)

Testing Clarity Smart Contracts

Once you get to writing more advanced smart contracts, properly testing them is paramount to protecting anyone who interacts with your contract.


Additional Resources

This brief overview should get your feet wet with Clarity. For deeper learning, we recommend:

If you prefer jumping into Clarity's reference materials for definitions on all its types, functions, and keywords, head to Clarity's Reference section of the docs.

Last updated

Was this helpful?