Quickstart

Learn how to create a simple counter contract using Clarinet.

In this quickstart guide, you will write a simple counter contract with Clarity. Throughout this tutorial, you'll learn how to generate a new project, create a smart contract, and validate your smart contract code using the Clarinet CLI.

Check out the create a new project and validate a contract guides for a deeper look.


Prerequisites

To follow this quickstart guide, you will need to have Clarinet installed on your machine.

brew install clarinet

If you need more installation options, check out the installation guide.


Generate your counter project

Start by creating a new Clarinet project. This command will create a new directory named counter and set up a basic Clarinet project inside it.

Terminal
clarinet new counter

Navigate to the newly created directory:

cd counter

You should see the following files and folders:

Devnet.toml
Mainnet.toml
Testnet.toml
.gitignore
Clarinet.toml
package.json
tsconfig.json
vitest.config.js

Create a counter contract

Inside your project, create your first contract. This command will create an empty counter.clar file in the contracts folder as well as a counter.test.ts file in the tests folder.

Terminal
clarinet contract new counter
counter.clar
counter.test.ts
.gitignore
Clarinet.toml
package.json
tsconfig.json
vitest.config.js

It also updates the Clarinet.toml file inside your project with the necessary settings.

Clarinet.toml
[contracts.counter]
path = 'contracts/counter.clar'
clarity_version = 2
epoch = 2.5

Variables and functions

In Clarity, you can define variables and functions to store and manipulate data. Inside your contracts/counter.clar file:

  1. Define a map called Counters to store the count associated with each user.
  2. Define a public function called count-up that increments the count of the user who calls it.
  3. Add a read-only function called get-count that returns the count of the user who calls it.
counter.clar
(define-map Counters principal uint)

(define-public (count-up)
  (ok (map-set Counters tx-sender (+ (get-count tx-sender) u1)))
)

(define-read-only (get-count (who principal))
  (default-to u0 (map-get? Counters who))
)

Validate your counter contract

Now it's time to validate your contract. This command will check your contract for errors and typos.

Terminal
clarinet check

When the validation is successful, you should see the following output: ✔ 1 contract checked.

You can go one step further and test your valid contract in a local REPL with the following steps:

  1. Run clarinet console from the terminal inside of your project.
  2. Call your contract by running (contract-call? .counter count-up).
  3. Verify the count of the user has been incremented by calling the get-count function with the tx-sender as the argument.
(contract-call? .counter count-up)
(contract-call? .counter get-count tx-sender)

Next steps