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.
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.
$clarinet new counter
Create a counter contract
Inside your project directory, run clarinet contract new counter
to create your contract. This will generate and update the proper files for writing and testing your code.
$cd counter$clarinet contract new counter
[contracts.counter]path = 'contracts/counter.clar'clarity_version = 2epoch = 2.5
Variables and functions
Inside your contracts/counter.clar
file:
- 1Define a map called
Counters
to store the count associated with each user. - 2Define a public function called
count-up
that increments the count of the user who calls it. - 3Add 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
Now it's time to validate your contract. This command will check your contract for errors and typos.
$clarinet check
Once your contract is validated, you can interact with it locally with the clarinet console
inside your project directory.
$clarinet console
Here are some example interactions you can perform with your contract:
- 1Call the
count-up
function on your contract to increment the count. - 2Verify the count of the user has been incremented by calling the
get-count
function with thetx-sender
as the argument.
$(contract-call? .counter count-up)$(contract-call? .counter get-count tx-sender)