You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
6
14
7
-
Once you've familiarized yourself with the language, consider the book [Clarity of Mind](https://book.clarity-lang.org/title-page.html) or the course [Clarity Universe](https://clarity-lang.org/universe) to continue your learning.
15
+
Once you've briefly familiarized yourself with the language, consider the [Clarity Book](https://book.clarity-lang.org/) or the course [Clarity Universe](https://clarity-lang.org/universe) to continue your learning.
8
16
9
17
{% hint style="info" %}
10
18
Clarity is developed as a joint effort of [Hiro PBC](https://hiro.so/), [Algorand](http://algorand.com/), and various other stakeholders, that originally targets the Stacks blockchain.
11
19
{% endhint %}
12
20
13
21
### Your First Clarity Smart Contract
14
22
15
-
We're going to build a basic Clarity smart contract using [Clarity Tools](https://clarity.tools/code/new), so you won't have to install anything for this introduction. Visit that link and it will open up a new contract for you.
23
+
We're going to walkthrough a basic Clarity smart contract using the [Clarity Playground](https://play.hiro.so/), 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.
16
24
17
-
Clarity Tools evaluates Clarity code in real-time — handy for experimenting and seeing immediate results.
25
+
<divdata-with-frame="true"><figure><imgsrc="../.gitbook/assets/clarity-playground.png"alt=""><figcaption><p>The example counter contract provided when visiting the Clarity Playground</p></figcaption></figure></div>
18
26
19
-
The initial example contains comments (two semicolons) and a public function declaration. 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.
27
+
{% hint style="info" %}
28
+
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](https://www.hiro.so/blog/meet-clarity-playground).
29
+
{% endhint %}
20
30
21
-
{% stepper %}
22
-
{% step %}
23
-
#### Understanding a simple expression
31
+
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.
24
32
25
-
We can think of some constructs as function calls. For example:
33
+
{% code title="counter.clar" %}
34
+
```clarity
35
+
(define-data-var count uint u0)
36
+
(define-data-var contract-owner principal tx-sender)
37
+
(define-data-var cost uint u10)
26
38
27
-
* Call a function called `define-read-only` (a built-in function).
28
-
* Pass it a parameter `hello`, which corresponds to the method signature.
29
-
* Pass it a parameter `"Hello"`, which corresponds to the function body.
39
+
(define-read-only (get-count)
40
+
(var-get count)
41
+
)
30
42
31
-
You can refer to the [`define-read-only`](https://docs.stacks.co/docs/write-smart-contracts/clarity-language/language-functions#define-read-only) documentation for details.
32
-
{% endstep %}
43
+
(define-public (increment)
44
+
(begin
45
+
(print u"incrementing count")
46
+
(ok (var-set count (+ (var-get count) u1)))
47
+
)
48
+
)
49
+
```
50
+
{% endcode %}
33
51
52
+
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:
53
+
54
+
{% stepper %}
34
55
{% step %}
35
-
#### Everything is an expression
56
+
#### Everything in parentheses is an expression
36
57
37
-
Clarity treats everything as expressions inside expressions. Function definitions are calls to built-in functions; the function body is an expression. This uniformity helps reasoning about programs in Clarity.
58
+
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.
38
59
{% endstep %}
39
60
40
61
{% step %}
41
-
#### Use LISP-like nesting
62
+
#### Uses LISP-like nesting
42
63
43
64
Expect nested parentheses and expressions. You’ll often read code as lists inside lists, where each parentheses-enclosed group represents a call or expression.
44
65
{% endstep %}
45
66
{% endstepper %}
46
67
47
-
Let's expand on these ideas by creating a new function. Paste this into Clarity Tools:
68
+
{% hint style="info" %}
69
+
In Clarity, there are public, private, and read-only functions:
70
+
71
+
* public: can modify chain state and be called externally.
72
+
* private: can modify state but only be called within the contract.
73
+
* read-only: will fail if they attempt to modify state.
74
+
{% endhint %}
75
+
76
+
Let's expand on these ideas by walking through that example counter contract line by line.
77
+
78
+
#### Defining data variables
79
+
80
+
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.
81
+
82
+
```clarity
83
+
;; defining a `count` variable to store a variable unsigned integer value
84
+
(define-data-var count uint u0)
85
+
86
+
;; defining a `contract-owner` for a specific `principal` value
87
+
(define-data-var contract-owner principal tx-sender)
88
+
89
+
;; defining a `cost` variable with an initial unsigned integer value of 10
90
+
(define-data-var cost uint u10)
91
+
```
92
+
93
+
#### Defining a read-only function to read the current count value
94
+
95
+
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.
96
+
97
+
```clarity
98
+
;; allows anyone to read the current `count` value in the contract
99
+
(define-read-only (get-count)
100
+
(var-get count)
101
+
)
102
+
```
103
+
104
+
#### Defining a public function to increment the count value
105
+
106
+
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.
48
107
49
-
{% code title="contract.clar" %}
50
108
```clarity
51
-
(define-data-var count int 0)
52
-
(define-public (add-number (number int))
53
-
(let
54
-
(
55
-
(current-count count)
56
-
)
57
-
58
-
(var-set count (+ 1 number))
59
-
(ok (var-get count))
60
-
)
109
+
;; Defines a public function named increment that anyone can call
110
+
(define-public (increment)
111
+
;; Starts a begin block, which allows multiple expressions to run in order.
112
+
(begin
113
+
;; Logs/prints the text "incrementing count" (as a Unicode string) to
114
+
;; the transaction output or event stream.
115
+
(print u"incrementing count")
116
+
;; adds u1 to the current count and wraps the resulting value in a response type
117
+
(ok (var-set count (+ (var-get count) u1)))
118
+
)
61
119
)
120
+
```
121
+
122
+
### Interact With Your Contract
123
+
124
+
The Clarity Playground allows you to call your functions on the right side view via a REPL console that runs a simnet environment.
125
+
126
+
<details>
127
+
128
+
<summary><strong>What is Simnet?</strong></summary>
129
+
130
+
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.
131
+
132
+
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.
133
+
134
+
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.
62
135
136
+
</details>
63
137
64
-
(add-number 5)
138
+
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.
139
+
140
+
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?` .
141
+
142
+
Follow the steps below to interact with your counter contract:
143
+
144
+
{% stepper %}
145
+
{% step %}
146
+
#### Call the read-only \`get-count\` function
147
+
148
+
In the bottom right Clarity command console, paste in the below command to call your `get-count` function to see the current `count` value.
149
+
150
+
{% code title="clarity command console" %}
151
+
```clarity
152
+
(contract-call? .contract-0 get-count)
65
153
```
66
154
{% endcode %}
67
155
68
-
If you type that into Clarity Tools, you'll see the result printed is 6.
156
+
The console should return an initial value of `u0` since we haven't incremented the `count` yet.
157
+
{% endstep %}
69
158
70
-
#### What this code does
159
+
{% step %}
160
+
#### Call the public \`increment\` function
71
161
72
-
* (define-data-var count int 0)\
73
-
Defines a persistent state variable `count` initialized to 0. This value is persisted on-chain when the contract is deployed.
74
-
* Clarity is interpreted, not compiled. When the contract is deployed, top-level expressions run (so the data var initialization happens at deploy time).
75
-
* (define-public (add-number (number int)) ...)\
76
-
Defines a public function `add-number` that takes a single parameter `number` of type `int`. Public functions can modify chain state and be called from outside the contract.
162
+
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.
77
163
78
-
{% hint style="info" %}
79
-
In Clarity, there are public, private, and read-only functions:
164
+
The console should return a value of `(ok true)` . This means the public function executed successfully and the count should have incremented.
80
165
81
-
* public: can modify chain state and be called externally.
82
-
* private: can modify state but only be called within the contract.
83
-
* read-only: will fail if they attempt to modify state.
84
-
{% endhint %}
166
+
{% code title="clarity command console" %}
167
+
```clarity
168
+
(contract-call? .contract-0 increment)
169
+
```
170
+
{% endcode %}
171
+
{% endstep %}
85
172
86
-
* (let ((current-count count)) ...)\
87
-
The `let` expression wraps multiple steps into a single expression (function bodies must evaluate to a single expression). It also declares local variables for use inside the function. Here `current-count` is a function-local variable set to `count`.
88
-
* (var-set count (+ 1 number))\
89
-
Sets the persistent `count` to `1 + number`. The `+` is itself a function call with operands as parameters.
90
-
* (ok (var-get count))\
91
-
Returns the new value of `count` wrapped in an `ok` response to indicate success.
92
-
* (add-number 5)\
93
-
Calls the function with parameter 5 (this is how you can invoke the function in an interactive environment like Clarity Tools).
173
+
{% step %}
174
+
#### Call our \`get-count\` function again
175
+
176
+
To see if our count value was really incremented, let's call our read-only `get-count` function once again.
177
+
178
+
{% code title="clarity command console" %}
179
+
```clarity
180
+
(contract-call? .contract-0 get-count)
181
+
```
182
+
{% endcode %}
183
+
184
+
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.
191
+
192
+
***
193
+
194
+
### Read Access into Bitcoin
195
+
196
+
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.
197
+
198
+
Reading Bitcoin state in Clarity is made by possible by the built-in function: `get-burn-block-info?` and the keyword `burn-block-height` .
199
+
200
+
*`burn-block-height` : This keyword returns the current block height of the underlying burnchain: Bitcoin. Check out the example snippet below:
201
+
202
+
```clarity
203
+
(> burn-block-height u1000)
204
+
;; returns true if the current height of the underlying burn blockchain has passed 1000 blocks.
205
+
```
206
+
207
+
*`get-burn-block-info?` : This function fetches block data of the burnchain: Bitcoin. Check out the example snippet below:
208
+
209
+
```clarity
210
+
(get-burn-block-info? header-hash u677050)
211
+
;; Returns (some 0xe671...)
212
+
```
94
213
95
214
***
96
215
97
-
### Testing Your Clarity Contract
216
+
### Testing Clarity Smart Contracts
217
+
218
+
Once you get to writing more advanced smart contracts, properly testing them is paramount to protecting anyone who interacts with your contract. 
98
219
99
220
{% hint style="danger" %}
100
221
Smart contracts are immutable once deployed. Bugs are permanent. Test them thoroughly.
@@ -111,8 +232,12 @@ This brief overview should get your feet wet with Clarity. For deeper learning,
*\[[Hiro Blog](https://www.hiro.so/blog/web3-programming-languages-clarity-vs-solidity)] Web3 Programming Languages: Clarity vs. Solidity
114
238
*\[[Stacks YT](https://youtu.be/hFqH1bJEvnw?si=yQADCvRNNjotuAga)] How Stacks' Language Clarity Enables Next Gen Smart Contracts
115
239
*\[[StacksDevs YT](https://www.youtube.com/watch?v=WZe1DgJ1w-E)] How Stacks’ Smart Contract Language Prevents Exploitation
116
240
*\[[Chainlink YT](https://youtu.be/OAVwd6SNJVU?si=UgfjmisBRbIYv27U)] Marvin Janssen: Clarity Smart Contracts for Stacks 
241
+
*[100+ Days of Clarity video series by Setzeus](https://youtube.com/playlist?list=PLFHm9eE6H5uhNQ4cUXRE-4HkXF1ekS0ZG\&si=q0NmD-e9_QBomK3a)
117
242
118
-
If you prefer jumping into reference material and examples, the Clarity docs contain guides and sample contracts to explore.
243
+
If you prefer jumping into Clarity's reference materials for definitions on all its types, functions, and keywords, head to [Clarity's Reference section](https://app.gitbook.com/s/GVj1Z9vMuEOMe7oH7Wnq/clarity/functions) of the docs.
0 commit comments