Quickstart

Create a simple counter contract

You will learn the following:

  • Generate a new project
  • Create a smart contract with Clarity
  • Test and validate your smart contract code

Install clarinet

To get started, install the package on your machine:

Terminal
brew install clarinet

Generate a new counter project

Navigate to a directory in your terminal where you want to create your project. Then in your terminal, run the following command:

Terminal
clarinet new counter

You should have a new counter directory resembling the following:

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

Create a counter contract

  1. Navigate to your project by running cd counter in your terminal.
  2. Inside your project, use the clarinet contract new command to generate a new contract.
Terminal
clarinet contract new counter

This will add 2 files to your project: counter.clar and counter.test.ts.

counter.clar
counter.test.ts
.gitignore
Clarinet.toml
package.json
tsconfig.json
vitest.config.js

It also updates the Clarinet.toml file with your new contract.

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. To complete a working counter example:

  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.
(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 contract

In order to verify that the syntax of your code is valid, run clarinet check inside of your project.

Terminal
clarinet check
 1 contract checked

And now to test the code, you can run clarinet console to bring up a REPL where you can interact with your contract directly.

  1. Run clarinet console in your terminal.
Terminal
clarinet console
  1. In the console, run (contract-call? .counter count-up) to call the count-up function.
Console
(contract-call? .counter count-up)
  1. Then verify the count of the user has been incremented by calling the get-count function with the tx-sender as the argument.
Console
(contract-call? .counter get-count tx-sender)

Next steps

Last updated on