smart contract
Quickstart for the SDK
Others • blockstack app store posted the article • 0 comments • 1556 views • 2019-06-28 01:40
About this tutorial and the prerequisites you need
Task 1: Generate an initial Clarity project
Task 2: Investigate the generated project
Task 3: Try to expand the contract
About this tutorial and the prerequisites you need
Note: This tutorial was written on macOS High Sierra 10.13.4. If you use a Windows or Linux system, you can still follow along. However, you will need to "translate" appropriately for your operating system.
For this tutorial, you will use npm to manage dependencies and scripts. The tutorial relies on the npm dependency manager. Before you begin, verify you have installed npm using the which command to verify.
$ which npm
/usr/local/bin/npm
If you don’t find npm in your system, install it.
You use npm to install Yeoman. Yeoman is a generic scaffolding system that helps users rapidly start new projects and streamline the maintenance of existing projects. Verify you have installed yo using the which command.
$ which yo
/usr/local/bin/yo
If you don’t have Yeoman, you can install it with the npm install -g yo command.
Task 1: Generate an initial Clarity project
The SDK uses Yeoman to generate a project scaffold — an initial set of directories and files.
1. Create a new directory for your project.
mkdir hello-clarity-sdk2. Change into your new project directory.cd hello-clarity-sdk3. Use the npm command to initialize a Clarity project.
npm init yo clarity-dev npx: installed 15 in 1.892s create package.json create .vscode/extensions.json ... Project created at /private/tmp/hello-clarity-sdk ✔ create-yo ok!Depending on your connection speed, it may take time to construct the scaffolding.
Task 2: Investigate the generated project
Your project should contain three directories:
The contracts directory contains a single file in sample/hello-world.clar file.
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
The contract exposes 2 rudimentary functions. The say-hi returns a hello world string. The increment-number: echos val.
The project also includes tests/hello-world.ts file. The test is written in Typescript. You can also write tests in Javascript.
import { Client, Provider, ProviderRegistry, Result } from "@blockstack/clarity";
import { assert } from "chai";
describe("hello world contract test suite", () => {
let helloWorldClient: Client;
let provider: Provider;
before(async () => {
provider = await ProviderRegistry.createProvider();
helloWorldClient = new Client("hello-world", "sample/hello-world", provider);
});
it("should have a valid syntax", async () => {
await helloWorldClient.checkContract();
});
describe("deploying an instance of the contract", () => {
before(async () => {
await helloWorldClient.deployContract();
});
it("should print hello world message", async () => {
const query = helloWorldClient.createQuery({ method: { name: "hello-world", args: } });
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
const parsedResult = Buffer.from(result.replace("0x", ""), "hex").toString();
assert.equal(parsedResult, "hello world");
});
it("should echo number", async () => {
const query = helloWorldClient.createQuery({
method: { name: "echo-number", args: ["123"] }
});
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
assert.equal(result, "123");
});
});
after(async () => {
await provider.close();
});
});
The hello-world.ts test file is a client that runs the hello-world.clar contract. Tests are critical for smart contracts as they are intended to manipulate assets and their ownership. These manipulations are irreversible within a blockchain. As you create a contracts, you should not be surprise if you end up spending more time and having more code in your tests than in your contracts directory. The tests/hello-world.ts file in the scaffold has the following content:
The first part of the test (lines 1 -10) sets up the test environment. It defines a Clarity provider and launches it (line 9). The Client instance contains a contract name and the path to the sample code. This test also checks the client (line 14) and then launches it (line 19), this is equivalent to running clarity-cli check with the command line. The remaining test code exercises the contract. Try running this test.
npm run test
> [email protected] test /private/tmp/hello-clarity-sdk
> mocha
hello world contract test suite
✓ should have a valid syntax
deploying an instance of the contract
✓ should print hello world message
✓ should echo number
3 passing (182ms)
In the next section, try your hand at expanding the hello-world.clar program.
Task 3: Try to expand the contract
In this task, you are challenged to expand the contents of the contracts/hello-world.clar file. Use your favorite editor and open the contracts/hello-world.clar file. If you use Visual Studio Code, you can install the Blockstack Clarity extension. The extension provides syntax coloration and some autocompletion.
Edit the hello-world.clar file.
;; Functions
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
Use the + function to create a increment-number-by-10 function.
answer:
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
Use the + and - function to create a decrement-number user-defined method.
answer: ;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
Finally, try adding a counter variable and be sure to store it. Increment counter in your code and add a get-counter funtion to return the result. Here is a hint, you can add a var` to a contract by adding the following line (before the function):
```cl ;; Storage (define-data-var internal-value int 0)
answer:
;; Storage
(define-data-var counter int 0)
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
(define (increment-counter)
(set-var! counter (+ 1 counter)))
(define (get-counter)
(counter))
To review other, longer sample programs visit the ]clarity-js-sdk[/url] repository.
view all
About this tutorial and the prerequisites you need
Task 1: Generate an initial Clarity project
Task 2: Investigate the generated project
Task 3: Try to expand the contract
About this tutorial and the prerequisites you need
Note: This tutorial was written on macOS High Sierra 10.13.4. If you use a Windows or Linux system, you can still follow along. However, you will need to "translate" appropriately for your operating system.
For this tutorial, you will use npm to manage dependencies and scripts. The tutorial relies on the npm dependency manager. Before you begin, verify you have installed npm using the which command to verify.
$ which npm
/usr/local/bin/npm
If you don’t find npm in your system, install it.
You use npm to install Yeoman. Yeoman is a generic scaffolding system that helps users rapidly start new projects and streamline the maintenance of existing projects. Verify you have installed yo using the which command.
$ which yo
/usr/local/bin/yo
If you don’t have Yeoman, you can install it with the npm install -g yo command.
Task 1: Generate an initial Clarity project
The SDK uses Yeoman to generate a project scaffold — an initial set of directories and files.
1. Create a new directory for your project.
mkdir hello-clarity-sdk2. Change into your new project directory.
cd hello-clarity-sdk3. Use the npm command to initialize a Clarity project.
npm init yo clarity-dev npx: installed 15 in 1.892s create package.json create .vscode/extensions.json ... Project created at /private/tmp/hello-clarity-sdk ✔ create-yo ok!Depending on your connection speed, it may take time to construct the scaffolding.
Task 2: Investigate the generated project
Your project should contain three directories:

The contracts directory contains a single file in sample/hello-world.clar file.
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
The contract exposes 2 rudimentary functions. The say-hi returns a hello world string. The increment-number: echos val.
The project also includes tests/hello-world.ts file. The test is written in Typescript. You can also write tests in Javascript.
import { Client, Provider, ProviderRegistry, Result } from "@blockstack/clarity";
import { assert } from "chai";
describe("hello world contract test suite", () => {
let helloWorldClient: Client;
let provider: Provider;
before(async () => {
provider = await ProviderRegistry.createProvider();
helloWorldClient = new Client("hello-world", "sample/hello-world", provider);
});
it("should have a valid syntax", async () => {
await helloWorldClient.checkContract();
});
describe("deploying an instance of the contract", () => {
before(async () => {
await helloWorldClient.deployContract();
});
it("should print hello world message", async () => {
const query = helloWorldClient.createQuery({ method: { name: "hello-world", args: } });
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
const parsedResult = Buffer.from(result.replace("0x", ""), "hex").toString();
assert.equal(parsedResult, "hello world");
});
it("should echo number", async () => {
const query = helloWorldClient.createQuery({
method: { name: "echo-number", args: ["123"] }
});
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
assert.equal(result, "123");
});
});
after(async () => {
await provider.close();
});
});The hello-world.ts test file is a client that runs the hello-world.clar contract. Tests are critical for smart contracts as they are intended to manipulate assets and their ownership. These manipulations are irreversible within a blockchain. As you create a contracts, you should not be surprise if you end up spending more time and having more code in your tests than in your contracts directory. The tests/hello-world.ts file in the scaffold has the following content:
The first part of the test (lines 1 -10) sets up the test environment. It defines a Clarity provider and launches it (line 9). The Client instance contains a contract name and the path to the sample code. This test also checks the client (line 14) and then launches it (line 19), this is equivalent to running clarity-cli check with the command line. The remaining test code exercises the contract. Try running this test.
npm run test
> [email protected] test /private/tmp/hello-clarity-sdk
> mocha
hello world contract test suite
✓ should have a valid syntax
deploying an instance of the contract
✓ should print hello world message
✓ should echo number
3 passing (182ms)
In the next section, try your hand at expanding the hello-world.clar program.
Task 3: Try to expand the contract
In this task, you are challenged to expand the contents of the contracts/hello-world.clar file. Use your favorite editor and open the contracts/hello-world.clar file. If you use Visual Studio Code, you can install the Blockstack Clarity extension. The extension provides syntax coloration and some autocompletion.
Edit the hello-world.clar file.
;; Functions
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
Use the + function to create a increment-number-by-10 function.
answer:
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
Use the + and - function to create a decrement-number user-defined method.
answer:
;; FunctionsFinally, try adding a counter variable and be sure to store it. Increment counter in your code and add a get-counter funtion to return the result. Here is a hint, you can add a var` to a contract by adding the following line (before the function):
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
```cl ;; Storage (define-data-var internal-value int 0)
answer:
;; Storage
(define-data-var counter int 0)
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
(define (increment-counter)
(set-var! counter (+ 1 counter)))
(define (get-counter)
(counter))
To review other, longer sample programs visit the ]clarity-js-sdk[/url] repository.
clarity smart contract language - cli command line
Others • blockstack app store posted the article • 0 comments • 1385 views • 2019-06-28 01:27
You use the clarity-cli command to work with smart contracts within the Blockstack virtual environment. This command has the following subcommands:
initialize
mine_block
get_block_height
check
launch
eval
eval_raw
repl
execute
generate_address
initialize
clarity-cli initialize [vm-state.db]Initializes a local VM state database. If the database exists, this command throws an error.
mine_block
clarity-cli mine_block [block time] [vm-state.db]Simulates mining a new block.
get_block_height
clarity-cli get_block_height [vm-state.db]
Prints the simulated block height.
check
clarity-cli check [program-file.scm] (vm-state.db)
Type checks a potential contract definition.
launch
clarity-cli launch [contract-name] [contract-definition.scm] [vm-state.db]Launches a new contract in the local VM state database.
eval
clarity-cli eval [context-contract-name] (program.scm) [vm-state.db]Evaluates, in read-only mode, a program in a given contract context.
eval_raw
Type check and evaluate an expression for validity inside of a function’s source. It does not evaluate within a contract or database context.
repl
clarity-cli repl
Type check and evaluate expressions in a stdin/stdout loop.
execute
clarity-cli execute [vm-state.db] [contract-name] [public-function-name] [sender-address] [args...]
Executes a public function of a defined contract.
generate_address
clarity-cli generate_addressGenerates a random Stacks public address for testing purposes.
view all
You use the clarity-cli command to work with smart contracts within the Blockstack virtual environment. This command has the following subcommands:
initialize
mine_block
get_block_height
check
launch
eval
eval_raw
repl
execute
generate_address
initialize
clarity-cli initialize [vm-state.db]Initializes a local VM state database. If the database exists, this command throws an error.mine_block
clarity-cli mine_block [block time] [vm-state.db]Simulates mining a new block.
get_block_height
clarity-cli get_block_height [vm-state.db]Prints the simulated block height.
check
clarity-cli check [program-file.scm] (vm-state.db)Type checks a potential contract definition.
launch
clarity-cli launch [contract-name] [contract-definition.scm] [vm-state.db]Launches a new contract in the local VM state database.
eval
clarity-cli eval [context-contract-name] (program.scm) [vm-state.db]Evaluates, in read-only mode, a program in a given contract context.
eval_raw
Type check and evaluate an expression for validity inside of a function’s source. It does not evaluate within a contract or database context.
repl
clarity-cli replType check and evaluate expressions in a stdin/stdout loop.
execute
clarity-cli execute [vm-state.db] [contract-name] [public-function-name] [sender-address] [args...]
Executes a public function of a defined contract.
generate_address
clarity-cli generate_addressGenerates a random Stacks public address for testing purposes.
How to use Clarity smart contract language to define functions and data maps
Others • blockstack app store posted the article • 0 comments • 1722 views • 2019-06-28 00:59
define and define-public functions
define-read-only functions
define-map functions for data
List operations and functions
Intra-contract calls
Reading from other smart contracts
define and define-public functions
Functions specified via define-public statements are public functions. Functions without these designations, simple define statements, are private functions. You can run a contract’s public functions directly via the clarity-cli execute command line directly or from other contracts. You can use the clarity eval or clarity eval_raw commands to evaluate private functions via the command line.
Public functions return a Response type result. If the function returns an ok type, then the function call is considered valid, and any changes made to the blockchain state will be materialized. If the function returns an err type, it is considered invalid, and has no effect on the smart contract’s state.
For example, consider two functions, foo.A and bar.B where the foo.A function calls bar.B, the table below shows the data materialization that results from the possible combination of return values:
Defining of constants and functions are allowed for simplifying code using a define statement. However, these are purely syntactic. If a definition cannot be inlined, the contract is rejected as illegal. These definitions are also private, in that functions defined this way may only be called by other functions defined in the given smart contract.
define-read-only functions
Functions specified via define-read-only statements are public. Unlike functions created by define-public, functions created with define-read-only may return any type. However, define-read-only statements cannot perform state mutations. Any attempts to modify contract state by these functions or functions called by these functions result in an error.
define-map functions for data
Data within a smart contract’s data-space is stored within maps. These stores relate a typed-tuple to another typed-tuple (almost like a typed key-value store). As opposed to a table data structure, a map only associates a given key with exactly one value. A smart contract defines the data schema of a data map with the define-map function.
(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))
Clarity contracts can only call the define-map function in the top-level of the smart-contract (similar to define. This function accepts a name for the map, and a definition of the structure of the key and value types. Each of these is a list of (name, type) pairs. Types are either the values 'principal, 'integer, 'bool or the output of one of the hash calls which is an n-byte fixed-length buffer.
To support the use of named fields in keys and values, Clarity allows the construction of tuples using a function (tuple ((key0 expr0) (key1 expr1) ...)), for example:
(tuple (name "blockstack") (id 1337))
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. To access a named value of a given tuple, the function (get #name tuple) will return that item from the tuple.
The define-map interface, as described, disallows range-queries and queries-by-prefix on data maps. Within a smart contract function, you cannot iterate over an entire map. Values in a given mapping are set or fetched using the following functions:
Data maps make reasoning about functions easier. By inspecting a given function definition, it is clear which maps will be modified and, even within those maps, which keys are affected by a given invocation. Also, the interface of data maps ensures that the return types of map operations are fixed length; Fixed length returns is a requirement for static analysis of a contract’s runtime, costs, and other properties.
List operations and functions
Lists may be multi-dimensional. However, note that runtime admission checks on typed function-parameters and data-map functions like set-entry! are charged based on the maximal size of the multi-dimensional list.
You can call filter map and fold functions with user-defined functions (that is, functions defined with (define ...), (define-read-only ...), or (define-public ...)) or simple, native functions (for example, +, -, not).
Intra-contract calls
A smart contract may call functions from other smart contracts using a (contract-call!) function:(contract-call! contract-name function-name arg0 arg1 ...)
This function accepts a function name and the smart contract’s name as input. For example, to call the function token-transfer in the smart contract, you would use:
(contract-call! tokens token-transfer burn-address name-price))
For intra-contract calls dynamic dispatch is not supported. When a contract is launched, any contracts it depends on (calls) must exist. Additionally, no cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs. A static analysis of the call graph detects such structures and they are rejected by the network.
A smart contract may not modify other smart contracts’ data directly; it can read data stored in those smart contracts’ maps. This read ability does not alter any confidentiality guarantees of Clarity. All data in a smart contract is inherently public, andis readable through querying the underlying database in any case.
Reading from other smart contracts
To read another contract’s data, use (fetch-contract-entry) function. This behaves identically to (fetch-entry), though it accepts a contract principal as an argument in addition to the map name:
(fetch-contract-entry
'contract-name
'map-name
'key-tuple) ;; value tuple or none
For example, you could do this:
(fetch-contract-entry
names
name-map
1) ;;returns owner principal of name
Just as with the (contract-call) function, the map name and contract principal arguments must be constants, specified at the time of publishing.
Finally, and importantly, the tx-sender variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. However, the static analysis guarantees of Clarity allow clients to know a priori which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
view all
define and define-public functions
define-read-only functions
define-map functions for data
List operations and functions
Intra-contract calls
Reading from other smart contracts
define and define-public functions
Functions specified via define-public statements are public functions. Functions without these designations, simple define statements, are private functions. You can run a contract’s public functions directly via the clarity-cli execute command line directly or from other contracts. You can use the clarity eval or clarity eval_raw commands to evaluate private functions via the command line.
Public functions return a Response type result. If the function returns an ok type, then the function call is considered valid, and any changes made to the blockchain state will be materialized. If the function returns an err type, it is considered invalid, and has no effect on the smart contract’s state.
For example, consider two functions, foo.A and bar.B where the foo.A function calls bar.B, the table below shows the data materialization that results from the possible combination of return values:

Defining of constants and functions are allowed for simplifying code using a define statement. However, these are purely syntactic. If a definition cannot be inlined, the contract is rejected as illegal. These definitions are also private, in that functions defined this way may only be called by other functions defined in the given smart contract.
define-read-only functions
Functions specified via define-read-only statements are public. Unlike functions created by define-public, functions created with define-read-only may return any type. However, define-read-only statements cannot perform state mutations. Any attempts to modify contract state by these functions or functions called by these functions result in an error.
define-map functions for data
Data within a smart contract’s data-space is stored within maps. These stores relate a typed-tuple to another typed-tuple (almost like a typed key-value store). As opposed to a table data structure, a map only associates a given key with exactly one value. A smart contract defines the data schema of a data map with the define-map function.
(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))
Clarity contracts can only call the define-map function in the top-level of the smart-contract (similar to define. This function accepts a name for the map, and a definition of the structure of the key and value types. Each of these is a list of (name, type) pairs. Types are either the values 'principal, 'integer, 'bool or the output of one of the hash calls which is an n-byte fixed-length buffer.
To support the use of named fields in keys and values, Clarity allows the construction of tuples using a function (tuple ((key0 expr0) (key1 expr1) ...)), for example:
(tuple (name "blockstack") (id 1337))
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. To access a named value of a given tuple, the function (get #name tuple) will return that item from the tuple.
The define-map interface, as described, disallows range-queries and queries-by-prefix on data maps. Within a smart contract function, you cannot iterate over an entire map. Values in a given mapping are set or fetched using the following functions:

Data maps make reasoning about functions easier. By inspecting a given function definition, it is clear which maps will be modified and, even within those maps, which keys are affected by a given invocation. Also, the interface of data maps ensures that the return types of map operations are fixed length; Fixed length returns is a requirement for static analysis of a contract’s runtime, costs, and other properties.
List operations and functions
Lists may be multi-dimensional. However, note that runtime admission checks on typed function-parameters and data-map functions like set-entry! are charged based on the maximal size of the multi-dimensional list.
You can call filter map and fold functions with user-defined functions (that is, functions defined with (define ...), (define-read-only ...), or (define-public ...)) or simple, native functions (for example, +, -, not).
Intra-contract calls
A smart contract may call functions from other smart contracts using a (contract-call!) function:
(contract-call! contract-name function-name arg0 arg1 ...)
This function accepts a function name and the smart contract’s name as input. For example, to call the function token-transfer in the smart contract, you would use:
(contract-call! tokens token-transfer burn-address name-price))
For intra-contract calls dynamic dispatch is not supported. When a contract is launched, any contracts it depends on (calls) must exist. Additionally, no cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs. A static analysis of the call graph detects such structures and they are rejected by the network.
A smart contract may not modify other smart contracts’ data directly; it can read data stored in those smart contracts’ maps. This read ability does not alter any confidentiality guarantees of Clarity. All data in a smart contract is inherently public, andis readable through querying the underlying database in any case.
Reading from other smart contracts
To read another contract’s data, use (fetch-contract-entry) function. This behaves identically to (fetch-entry), though it accepts a contract principal as an argument in addition to the map name:
(fetch-contract-entry
'contract-name
'map-name
'key-tuple) ;; value tuple or none
For example, you could do this:
(fetch-contract-entry
names
name-map
1) ;;returns owner principal of name
Just as with the (contract-call) function, the map name and contract principal arguments must be constants, specified at the time of publishing.
Finally, and importantly, the tx-sender variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. However, the static analysis guarantees of Clarity allow clients to know a priori which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
Principals-a Clarity (smart contract language for blockstack dapps)native type
Others • blockstack app store posted the article • 0 comments • 1497 views • 2019-06-28 00:49
Principals and tx-sender
A principal is represented by a public-key hash or multi-signature Stacks address. Assets in Clarity and the Stacks blockchain are “owned” by objects of the principal type; put another way, principal object types may own an asset.
A given principal operates on its assets by issuing a signed transaction on the Stacks blockchain. A Clarity contract can use a globally defined tx-sender variable to obtain the current principal.
The following user-defined function transfers an asset, in this case, tokens, between two principals:
(define (transfer! (sender principal) (recipient principal) (amount int))
(if (and
(not (eq? sender recipient))
(debit-balance! sender amount)
(credit-balance! recipient amount))
'true
'false))
The principal’s signature is not checked by the smart contract, but by the virtual machine.
Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract’s identifier. You create the identifier when you launch the contract, for example, the contract identifier here is hanomine.
clarity-cli launch hanomine /data/hano.clar /data/db
A smart contract may use the special variable contract-name to refer to its own principal.
To allow smart contracts to operate on assets it owns, smart contracts may use the special (as-contract expr) function. This function executes the expression (passed as an argument) with the tx-sender set to the contract’s principal, rather than the current sender. The as-contract function returns the value of the provided expression.
For example, a smart contract that implements something like a “token faucet” could be implemented as so:
(define-public (claim-from-faucet)
(if (is-none? (fetch-entry claimed-before (tuple (sender tx-sender))))
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(begin
(insert-entry! claimed-before (tuple (sender requester)) (tuple (claimed 'true)))
(as-contract (stacks-transfer! requester 1)))))
(err 1))
In this example, the public function claim-from-faucet:
Checks if the sender has claimed from the faucet before.Assigns the tx sender to a requester variable.Adds an entry to the tracking map.Uses as-contract to send 1 microstack
Contract writers can use the primitive function is-contract? to determine whether a given principal corresponds to a smart contract.
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
view all
Principals and tx-sender
A principal is represented by a public-key hash or multi-signature Stacks address. Assets in Clarity and the Stacks blockchain are “owned” by objects of the principal type; put another way, principal object types may own an asset.
A given principal operates on its assets by issuing a signed transaction on the Stacks blockchain. A Clarity contract can use a globally defined tx-sender variable to obtain the current principal.
The following user-defined function transfers an asset, in this case, tokens, between two principals:
(define (transfer! (sender principal) (recipient principal) (amount int))
(if (and
(not (eq? sender recipient))
(debit-balance! sender amount)
(credit-balance! recipient amount))
'true
'false))
The principal’s signature is not checked by the smart contract, but by the virtual machine.
Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract’s identifier. You create the identifier when you launch the contract, for example, the contract identifier here is hanomine.
clarity-cli launch hanomine /data/hano.clar /data/db
A smart contract may use the special variable contract-name to refer to its own principal.
To allow smart contracts to operate on assets it owns, smart contracts may use the special (as-contract expr) function. This function executes the expression (passed as an argument) with the tx-sender set to the contract’s principal, rather than the current sender. The as-contract function returns the value of the provided expression.
For example, a smart contract that implements something like a “token faucet” could be implemented as so:
(define-public (claim-from-faucet)
(if (is-none? (fetch-entry claimed-before (tuple (sender tx-sender))))
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(begin
(insert-entry! claimed-before (tuple (sender requester)) (tuple (claimed 'true)))
(as-contract (stacks-transfer! requester 1)))))
(err 1))
In this example, the public function claim-from-faucet:
- Checks if the sender has claimed from the faucet before.
- Assigns the tx sender to a requester variable.
- Adds an entry to the tracking map.
- Uses as-contract to send 1 microstack
Contract writers can use the primitive function is-contract? to determine whether a given principal corresponds to a smart contract.
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
Clarity-Blockstack smart contract language tutorials and docs
Others • blockstack app store posted the article • 0 comments • 1757 views • 2019-06-28 00:38
Who should use smart contracts?
Language and program design
The coding environment
Basic building blocks of Clarity contracts
hello-world example
Language rules and limitations
Who should use smart contracts?
You can use Clarity to write standalone contracts or to write contracts that are part of decentralized applications (DApps) you write with the blockstack.js library. Smart contracts allow two parties to exchange anything of value (money, property, shares), in an automated, auditable, and secure way without the services of a middleman. Nick Szabo introduced the canonical metaphor for smart contracts, a vending machine.
In Nick Szabo’s metaphor, the vending machine is the smart contract. The buyer and machine owner are the two parties. A vending machine executes a set of hard-coded actions when the buyer engages with it. The machine displays the items and their prices. A buyer enters money into the machine which determines if the amount fails to mee, meets, or exceeds an item’s price. Based on the amount, the machine asks for more money, dispenses an item, or dispenses and item and change.
Not every application requires smart contracts. If you are not sure or are new to smart contracts concepts, you should read ]a good general explanation of smart contracts[/url] before working with Clarity.
Language and program design
Clarity differs from most other smart contract languages in two essential ways:
The language is not intended to be compiled.The language is not Turing complete.
These differences allow for static analysis of programs to determine properties like runtime cost and data usage.
A Clarity smart contract is composed of two parts — a data-space and a set of functions. Only the associated smart contract may modify its corresponding data-space on the blockchain. Functions are private unless they are defined as public functions. Users call smart contracts’ public functions by broadcasting a transaction on the blockchain which invokes the public function.
Contracts can also call public functions from other smart contracts. The ability to do a static analysis of a smart contract allows a user to determine dependency between contracts.
The coding environment
Clarity is a list processing (LISP) language, as such it is not compiled. Omitting compilation prevents the possibility of error or bugs introduced at the compiler level. You can write Clarity smart contract programs on any operating system with a text editor. You can use any editor you are comfortable with such as Atom, Vim, or even Notepad. The Clarity files you create with an editor have a .clar extension.
Clarity is in pre-release and does not yet directly interact with the live Stacks blockchain. For the pre-release period you need a test environment to run Clarity contracts. Blockstack provides a Docker image called clarity-developer-preview that you can use or you can build a test environment locally from code. Either the Docker image or a local environment is sufficient for testing Clarity programming for standalone contracts.
You use the clarity-cli command line to check, launch, and execute standalone Clarity contracts. You can use this same command line to create simulate mining Stacks and inspecting a blockchain.
Blockstack expects that some decentralized applications (DApp) will want to make use of Clarity contracts as part of their applications. For this purpose, you should use the Clarity SDK, also in pre-release. The SDK is a development environment, testing framework, and deployment tool. It provides a library for safe interactions with Clarity contracts from a DApp written with the blockstack.js library.
Basic building blocks of Clarity contracts
The basic building blocks of Clarity are atoms and lists. An atom is a number or string of contiguous characters. Some examples of atoms:
token-sender10000SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR
Atoms can be native functions, user-defined functions, variables, and values that appear in a program. Functions that mutate data by convention terminate with an ! exclamation point, for example the insert-entry! function.
A list is a sequences of atoms enclosed with () parentheses. Lists can contain other lists. Some examples of lists are:
(get-block-info time 10)(and 'true 'false)(is-none (get id (fetch-entry names-map (tuple (name \"blockstack\")))))
You can add comments to your Clarity contracts using ;; (double semi-colons). Both standalone and inline comments are supported.
;; Transfers tokens to a specified principal (define-public (transfer (recipient principal) (amount int)) (transfer! tx-sender recipient amount)) ;; returns: boolean
You use the clarity-cli command to check and launch a Clarity (.clar) program.
hello-world example
The easiest program to run in any language is a hello world program. In Clarity, you can write this hello-world.clar program.
(begin
(print "hello world"))
This program defines a single hello-world expression that is excuted when the contract launches. The begin is a native Clarity function that evaluates the expressions input to it and returns the value of the last expression. Here there is a single print expression. Both the begin and the print are enclosed in ()parentheses.
For the pre-release, the Blockstack test environment includes the clarity-cli command for interacting with the contract and SQLite to support the data space. You create a SQLLite database to hold data related to Clarity contracts. This database simulates the blockchain by recording the contract activity.
You can’t run even an a hello-world program without first initializing a Clarity contract’s data space within the database. You can use the clarity-cli initialize command to set up the database.
clarity-cli initialize /data/db
This command initializes the db database which resides in the /data directory of the container. You can name the database anything you like, the name db is not required. You can use SQLite to query this database:
sqlite> .open db
sqlite> .tables
contracts maps_table type_analysis_table
data_table simmed_block_table
sqlite>
After you initialize the contract’s data space, you can check a Clarity program for problems.
clarity-cli check ./hello.clar /data/db
As the name implies, the check ensures the contract definition passes a type check; passing programs will returns an exit code of 0 (zero). Once a contract passes a check, you launch it.
root@4224dd95b5f5:/data# clarity-cli launch hello ./hello.clar /data/db
Buffer(BuffData { data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] })
Contract initialized!
Because Clarity does not support simple strings, it stores the hello world string in a buffer. Printing out that string displays the ASCII representation for each character. You can see the record of this contract’s launch in the corresponding database:
sqlite> select * from contracts;
1|hello|{"contract_context":{"name":"hello","variables":{},"functions":{}}}
sqlite> select * from type_analysis_table;
1|hello|{"private_function_types":{},"variable_types":{},"public_function_types":{},"read_only_function_types":{},"map_types":{}}
sqlite>
Language rules and limitations
The Clarity smart contract has the following limitations:
The only atomic types are booleans, integers, fixed length buffers, and principalsRecursion is illegal and there is no lambda function.Looping may only be performed via map, filter, or foldThere is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.Variables are created via let binding and there is no support for mutating functions like set.
view all
Who should use smart contracts?
Language and program design
The coding environment
Basic building blocks of Clarity contracts
hello-world example
Language rules and limitations
Who should use smart contracts?
You can use Clarity to write standalone contracts or to write contracts that are part of decentralized applications (DApps) you write with the blockstack.js library. Smart contracts allow two parties to exchange anything of value (money, property, shares), in an automated, auditable, and secure way without the services of a middleman. Nick Szabo introduced the canonical metaphor for smart contracts, a vending machine.
In Nick Szabo’s metaphor, the vending machine is the smart contract. The buyer and machine owner are the two parties. A vending machine executes a set of hard-coded actions when the buyer engages with it. The machine displays the items and their prices. A buyer enters money into the machine which determines if the amount fails to mee, meets, or exceeds an item’s price. Based on the amount, the machine asks for more money, dispenses an item, or dispenses and item and change.
Not every application requires smart contracts. If you are not sure or are new to smart contracts concepts, you should read ]a good general explanation of smart contracts[/url] before working with Clarity.
Language and program design
Clarity differs from most other smart contract languages in two essential ways:
- The language is not intended to be compiled.
- The language is not Turing complete.
These differences allow for static analysis of programs to determine properties like runtime cost and data usage.
A Clarity smart contract is composed of two parts — a data-space and a set of functions. Only the associated smart contract may modify its corresponding data-space on the blockchain. Functions are private unless they are defined as public functions. Users call smart contracts’ public functions by broadcasting a transaction on the blockchain which invokes the public function.
Contracts can also call public functions from other smart contracts. The ability to do a static analysis of a smart contract allows a user to determine dependency between contracts.
The coding environment
Clarity is a list processing (LISP) language, as such it is not compiled. Omitting compilation prevents the possibility of error or bugs introduced at the compiler level. You can write Clarity smart contract programs on any operating system with a text editor. You can use any editor you are comfortable with such as Atom, Vim, or even Notepad. The Clarity files you create with an editor have a .clar extension.
Clarity is in pre-release and does not yet directly interact with the live Stacks blockchain. For the pre-release period you need a test environment to run Clarity contracts. Blockstack provides a Docker image called clarity-developer-preview that you can use or you can build a test environment locally from code. Either the Docker image or a local environment is sufficient for testing Clarity programming for standalone contracts.
You use the clarity-cli command line to check, launch, and execute standalone Clarity contracts. You can use this same command line to create simulate mining Stacks and inspecting a blockchain.
Blockstack expects that some decentralized applications (DApp) will want to make use of Clarity contracts as part of their applications. For this purpose, you should use the Clarity SDK, also in pre-release. The SDK is a development environment, testing framework, and deployment tool. It provides a library for safe interactions with Clarity contracts from a DApp written with the blockstack.js library.
Basic building blocks of Clarity contracts
The basic building blocks of Clarity are atoms and lists. An atom is a number or string of contiguous characters. Some examples of atoms:
- token-sender
- 10000
- SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR
Atoms can be native functions, user-defined functions, variables, and values that appear in a program. Functions that mutate data by convention terminate with an ! exclamation point, for example the insert-entry! function.
A list is a sequences of atoms enclosed with () parentheses. Lists can contain other lists. Some examples of lists are:
- (get-block-info time 10)
- (and 'true 'false)
- (is-none (get id (fetch-entry names-map (tuple (name \"blockstack\")))))
You can add comments to your Clarity contracts using ;; (double semi-colons). Both standalone and inline comments are supported.
;; Transfers tokens to a specified principal (define-public (transfer (recipient principal) (amount int)) (transfer! tx-sender recipient amount)) ;; returns: boolean
You use the clarity-cli command to check and launch a Clarity (.clar) program.
hello-world example
The easiest program to run in any language is a hello world program. In Clarity, you can write this hello-world.clar program.
(begin
(print "hello world"))
This program defines a single hello-world expression that is excuted when the contract launches. The begin is a native Clarity function that evaluates the expressions input to it and returns the value of the last expression. Here there is a single print expression. Both the begin and the print are enclosed in ()parentheses.
For the pre-release, the Blockstack test environment includes the clarity-cli command for interacting with the contract and SQLite to support the data space. You create a SQLLite database to hold data related to Clarity contracts. This database simulates the blockchain by recording the contract activity.
You can’t run even an a hello-world program without first initializing a Clarity contract’s data space within the database. You can use the clarity-cli initialize command to set up the database.
clarity-cli initialize /data/db
This command initializes the db database which resides in the /data directory of the container. You can name the database anything you like, the name db is not required. You can use SQLite to query this database:
sqlite> .open db
sqlite> .tables
contracts maps_table type_analysis_table
data_table simmed_block_table
sqlite>
After you initialize the contract’s data space, you can check a Clarity program for problems.
clarity-cli check ./hello.clar /data/db
As the name implies, the check ensures the contract definition passes a type check; passing programs will returns an exit code of 0 (zero). Once a contract passes a check, you launch it.
root@4224dd95b5f5:/data# clarity-cli launch hello ./hello.clar /data/db
Buffer(BuffData { data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] })
Contract initialized!
Because Clarity does not support simple strings, it stores the hello world string in a buffer. Printing out that string displays the ASCII representation for each character. You can see the record of this contract’s launch in the corresponding database:
sqlite> select * from contracts;
1|hello|{"contract_context":{"name":"hello","variables":{},"functions":{}}}
sqlite> select * from type_analysis_table;
1|hello|{"private_function_types":{},"variable_types":{},"public_function_types":{},"read_only_function_types":{},"map_types":{}}
sqlite>
Language rules and limitations
The Clarity smart contract has the following limitations:
- The only atomic types are booleans, integers, fixed length buffers, and principals
- Recursion is illegal and there is no lambda function.
- Looping may only be performed via map, filter, or fold
- There is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.
- Variables are created via let binding and there is no support for mutating functions like set.
Quickstart for the SDK
Others • blockstack app store posted the article • 0 comments • 1556 views • 2019-06-28 01:40
About this tutorial and the prerequisites you need
Task 1: Generate an initial Clarity project
Task 2: Investigate the generated project
Task 3: Try to expand the contract
About this tutorial and the prerequisites you need
Note: This tutorial was written on macOS High Sierra 10.13.4. If you use a Windows or Linux system, you can still follow along. However, you will need to "translate" appropriately for your operating system.
For this tutorial, you will use npm to manage dependencies and scripts. The tutorial relies on the npm dependency manager. Before you begin, verify you have installed npm using the which command to verify.
$ which npm
/usr/local/bin/npm
If you don’t find npm in your system, install it.
You use npm to install Yeoman. Yeoman is a generic scaffolding system that helps users rapidly start new projects and streamline the maintenance of existing projects. Verify you have installed yo using the which command.
$ which yo
/usr/local/bin/yo
If you don’t have Yeoman, you can install it with the npm install -g yo command.
Task 1: Generate an initial Clarity project
The SDK uses Yeoman to generate a project scaffold — an initial set of directories and files.
1. Create a new directory for your project.
mkdir hello-clarity-sdk2. Change into your new project directory.cd hello-clarity-sdk3. Use the npm command to initialize a Clarity project.
npm init yo clarity-dev npx: installed 15 in 1.892s create package.json create .vscode/extensions.json ... Project created at /private/tmp/hello-clarity-sdk ✔ create-yo ok!Depending on your connection speed, it may take time to construct the scaffolding.
Task 2: Investigate the generated project
Your project should contain three directories:
The contracts directory contains a single file in sample/hello-world.clar file.
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
The contract exposes 2 rudimentary functions. The say-hi returns a hello world string. The increment-number: echos val.
The project also includes tests/hello-world.ts file. The test is written in Typescript. You can also write tests in Javascript.
import { Client, Provider, ProviderRegistry, Result } from "@blockstack/clarity";
import { assert } from "chai";
describe("hello world contract test suite", () => {
let helloWorldClient: Client;
let provider: Provider;
before(async () => {
provider = await ProviderRegistry.createProvider();
helloWorldClient = new Client("hello-world", "sample/hello-world", provider);
});
it("should have a valid syntax", async () => {
await helloWorldClient.checkContract();
});
describe("deploying an instance of the contract", () => {
before(async () => {
await helloWorldClient.deployContract();
});
it("should print hello world message", async () => {
const query = helloWorldClient.createQuery({ method: { name: "hello-world", args: } });
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
const parsedResult = Buffer.from(result.replace("0x", ""), "hex").toString();
assert.equal(parsedResult, "hello world");
});
it("should echo number", async () => {
const query = helloWorldClient.createQuery({
method: { name: "echo-number", args: ["123"] }
});
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
assert.equal(result, "123");
});
});
after(async () => {
await provider.close();
});
});
The hello-world.ts test file is a client that runs the hello-world.clar contract. Tests are critical for smart contracts as they are intended to manipulate assets and their ownership. These manipulations are irreversible within a blockchain. As you create a contracts, you should not be surprise if you end up spending more time and having more code in your tests than in your contracts directory. The tests/hello-world.ts file in the scaffold has the following content:
The first part of the test (lines 1 -10) sets up the test environment. It defines a Clarity provider and launches it (line 9). The Client instance contains a contract name and the path to the sample code. This test also checks the client (line 14) and then launches it (line 19), this is equivalent to running clarity-cli check with the command line. The remaining test code exercises the contract. Try running this test.
npm run test
> [email protected] test /private/tmp/hello-clarity-sdk
> mocha
hello world contract test suite
✓ should have a valid syntax
deploying an instance of the contract
✓ should print hello world message
✓ should echo number
3 passing (182ms)
In the next section, try your hand at expanding the hello-world.clar program.
Task 3: Try to expand the contract
In this task, you are challenged to expand the contents of the contracts/hello-world.clar file. Use your favorite editor and open the contracts/hello-world.clar file. If you use Visual Studio Code, you can install the Blockstack Clarity extension. The extension provides syntax coloration and some autocompletion.
Edit the hello-world.clar file.
;; Functions
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
Use the + function to create a increment-number-by-10 function.
answer:
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
Use the + and - function to create a decrement-number user-defined method.
answer: ;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
Finally, try adding a counter variable and be sure to store it. Increment counter in your code and add a get-counter funtion to return the result. Here is a hint, you can add a var` to a contract by adding the following line (before the function):
```cl ;; Storage (define-data-var internal-value int 0)
answer:
;; Storage
(define-data-var counter int 0)
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
(define (increment-counter)
(set-var! counter (+ 1 counter)))
(define (get-counter)
(counter))
To review other, longer sample programs visit the ]clarity-js-sdk[/url] repository.
view all
About this tutorial and the prerequisites you need
Task 1: Generate an initial Clarity project
Task 2: Investigate the generated project
Task 3: Try to expand the contract
About this tutorial and the prerequisites you need
Note: This tutorial was written on macOS High Sierra 10.13.4. If you use a Windows or Linux system, you can still follow along. However, you will need to "translate" appropriately for your operating system.
For this tutorial, you will use npm to manage dependencies and scripts. The tutorial relies on the npm dependency manager. Before you begin, verify you have installed npm using the which command to verify.
$ which npm
/usr/local/bin/npm
If you don’t find npm in your system, install it.
You use npm to install Yeoman. Yeoman is a generic scaffolding system that helps users rapidly start new projects and streamline the maintenance of existing projects. Verify you have installed yo using the which command.
$ which yo
/usr/local/bin/yo
If you don’t have Yeoman, you can install it with the npm install -g yo command.
Task 1: Generate an initial Clarity project
The SDK uses Yeoman to generate a project scaffold — an initial set of directories and files.
1. Create a new directory for your project.
mkdir hello-clarity-sdk2. Change into your new project directory.
cd hello-clarity-sdk3. Use the npm command to initialize a Clarity project.
npm init yo clarity-dev npx: installed 15 in 1.892s create package.json create .vscode/extensions.json ... Project created at /private/tmp/hello-clarity-sdk ✔ create-yo ok!Depending on your connection speed, it may take time to construct the scaffolding.
Task 2: Investigate the generated project
Your project should contain three directories:

The contracts directory contains a single file in sample/hello-world.clar file.
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
The contract exposes 2 rudimentary functions. The say-hi returns a hello world string. The increment-number: echos val.
The project also includes tests/hello-world.ts file. The test is written in Typescript. You can also write tests in Javascript.
import { Client, Provider, ProviderRegistry, Result } from "@blockstack/clarity";
import { assert } from "chai";
describe("hello world contract test suite", () => {
let helloWorldClient: Client;
let provider: Provider;
before(async () => {
provider = await ProviderRegistry.createProvider();
helloWorldClient = new Client("hello-world", "sample/hello-world", provider);
});
it("should have a valid syntax", async () => {
await helloWorldClient.checkContract();
});
describe("deploying an instance of the contract", () => {
before(async () => {
await helloWorldClient.deployContract();
});
it("should print hello world message", async () => {
const query = helloWorldClient.createQuery({ method: { name: "hello-world", args: } });
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
const parsedResult = Buffer.from(result.replace("0x", ""), "hex").toString();
assert.equal(parsedResult, "hello world");
});
it("should echo number", async () => {
const query = helloWorldClient.createQuery({
method: { name: "echo-number", args: ["123"] }
});
const receipt = await helloWorldClient.submitQuery(query);
const result = Result.unwrap(receipt);
assert.equal(result, "123");
});
});
after(async () => {
await provider.close();
});
});The hello-world.ts test file is a client that runs the hello-world.clar contract. Tests are critical for smart contracts as they are intended to manipulate assets and their ownership. These manipulations are irreversible within a blockchain. As you create a contracts, you should not be surprise if you end up spending more time and having more code in your tests than in your contracts directory. The tests/hello-world.ts file in the scaffold has the following content:
The first part of the test (lines 1 -10) sets up the test environment. It defines a Clarity provider and launches it (line 9). The Client instance contains a contract name and the path to the sample code. This test also checks the client (line 14) and then launches it (line 19), this is equivalent to running clarity-cli check with the command line. The remaining test code exercises the contract. Try running this test.
npm run test
> [email protected] test /private/tmp/hello-clarity-sdk
> mocha
hello world contract test suite
✓ should have a valid syntax
deploying an instance of the contract
✓ should print hello world message
✓ should echo number
3 passing (182ms)
In the next section, try your hand at expanding the hello-world.clar program.
Task 3: Try to expand the contract
In this task, you are challenged to expand the contents of the contracts/hello-world.clar file. Use your favorite editor and open the contracts/hello-world.clar file. If you use Visual Studio Code, you can install the Blockstack Clarity extension. The extension provides syntax coloration and some autocompletion.
Edit the hello-world.clar file.
;; Functions
(define (hello-world)
"hello world")
(define (echo-number (val int))
val)
Use the + function to create a increment-number-by-10 function.
answer:
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
Use the + and - function to create a decrement-number user-defined method.
answer:
;; FunctionsFinally, try adding a counter variable and be sure to store it. Increment counter in your code and add a get-counter funtion to return the result. Here is a hint, you can add a var` to a contract by adding the following line (before the function):
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
```cl ;; Storage (define-data-var internal-value int 0)
answer:
;; Storage
(define-data-var counter int 0)
;; Functions
(define (say-hi)
"hello world")
(define (increment-number (number int))
(+ 1 number))
(define (increment-number-by-10 (number int))
(+ 10 number))
(define (decrement-number (number int))
(- number 1))
(define (increment-counter)
(set-var! counter (+ 1 counter)))
(define (get-counter)
(counter))
To review other, longer sample programs visit the ]clarity-js-sdk[/url] repository.
clarity smart contract language - cli command line
Others • blockstack app store posted the article • 0 comments • 1385 views • 2019-06-28 01:27
You use the clarity-cli command to work with smart contracts within the Blockstack virtual environment. This command has the following subcommands:
initialize
mine_block
get_block_height
check
launch
eval
eval_raw
repl
execute
generate_address
initialize
clarity-cli initialize [vm-state.db]Initializes a local VM state database. If the database exists, this command throws an error.
mine_block
clarity-cli mine_block [block time] [vm-state.db]Simulates mining a new block.
get_block_height
clarity-cli get_block_height [vm-state.db]
Prints the simulated block height.
check
clarity-cli check [program-file.scm] (vm-state.db)
Type checks a potential contract definition.
launch
clarity-cli launch [contract-name] [contract-definition.scm] [vm-state.db]Launches a new contract in the local VM state database.
eval
clarity-cli eval [context-contract-name] (program.scm) [vm-state.db]Evaluates, in read-only mode, a program in a given contract context.
eval_raw
Type check and evaluate an expression for validity inside of a function’s source. It does not evaluate within a contract or database context.
repl
clarity-cli repl
Type check and evaluate expressions in a stdin/stdout loop.
execute
clarity-cli execute [vm-state.db] [contract-name] [public-function-name] [sender-address] [args...]
Executes a public function of a defined contract.
generate_address
clarity-cli generate_addressGenerates a random Stacks public address for testing purposes.
view all
You use the clarity-cli command to work with smart contracts within the Blockstack virtual environment. This command has the following subcommands:
initialize
mine_block
get_block_height
check
launch
eval
eval_raw
repl
execute
generate_address
initialize
clarity-cli initialize [vm-state.db]Initializes a local VM state database. If the database exists, this command throws an error.mine_block
clarity-cli mine_block [block time] [vm-state.db]Simulates mining a new block.
get_block_height
clarity-cli get_block_height [vm-state.db]Prints the simulated block height.
check
clarity-cli check [program-file.scm] (vm-state.db)Type checks a potential contract definition.
launch
clarity-cli launch [contract-name] [contract-definition.scm] [vm-state.db]Launches a new contract in the local VM state database.
eval
clarity-cli eval [context-contract-name] (program.scm) [vm-state.db]Evaluates, in read-only mode, a program in a given contract context.
eval_raw
Type check and evaluate an expression for validity inside of a function’s source. It does not evaluate within a contract or database context.
repl
clarity-cli replType check and evaluate expressions in a stdin/stdout loop.
execute
clarity-cli execute [vm-state.db] [contract-name] [public-function-name] [sender-address] [args...]
Executes a public function of a defined contract.
generate_address
clarity-cli generate_addressGenerates a random Stacks public address for testing purposes.
How to use Clarity smart contract language to define functions and data maps
Others • blockstack app store posted the article • 0 comments • 1722 views • 2019-06-28 00:59
define and define-public functions
define-read-only functions
define-map functions for data
List operations and functions
Intra-contract calls
Reading from other smart contracts
define and define-public functions
Functions specified via define-public statements are public functions. Functions without these designations, simple define statements, are private functions. You can run a contract’s public functions directly via the clarity-cli execute command line directly or from other contracts. You can use the clarity eval or clarity eval_raw commands to evaluate private functions via the command line.
Public functions return a Response type result. If the function returns an ok type, then the function call is considered valid, and any changes made to the blockchain state will be materialized. If the function returns an err type, it is considered invalid, and has no effect on the smart contract’s state.
For example, consider two functions, foo.A and bar.B where the foo.A function calls bar.B, the table below shows the data materialization that results from the possible combination of return values:
Defining of constants and functions are allowed for simplifying code using a define statement. However, these are purely syntactic. If a definition cannot be inlined, the contract is rejected as illegal. These definitions are also private, in that functions defined this way may only be called by other functions defined in the given smart contract.
define-read-only functions
Functions specified via define-read-only statements are public. Unlike functions created by define-public, functions created with define-read-only may return any type. However, define-read-only statements cannot perform state mutations. Any attempts to modify contract state by these functions or functions called by these functions result in an error.
define-map functions for data
Data within a smart contract’s data-space is stored within maps. These stores relate a typed-tuple to another typed-tuple (almost like a typed key-value store). As opposed to a table data structure, a map only associates a given key with exactly one value. A smart contract defines the data schema of a data map with the define-map function.
(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))
Clarity contracts can only call the define-map function in the top-level of the smart-contract (similar to define. This function accepts a name for the map, and a definition of the structure of the key and value types. Each of these is a list of (name, type) pairs. Types are either the values 'principal, 'integer, 'bool or the output of one of the hash calls which is an n-byte fixed-length buffer.
To support the use of named fields in keys and values, Clarity allows the construction of tuples using a function (tuple ((key0 expr0) (key1 expr1) ...)), for example:
(tuple (name "blockstack") (id 1337))
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. To access a named value of a given tuple, the function (get #name tuple) will return that item from the tuple.
The define-map interface, as described, disallows range-queries and queries-by-prefix on data maps. Within a smart contract function, you cannot iterate over an entire map. Values in a given mapping are set or fetched using the following functions:
Data maps make reasoning about functions easier. By inspecting a given function definition, it is clear which maps will be modified and, even within those maps, which keys are affected by a given invocation. Also, the interface of data maps ensures that the return types of map operations are fixed length; Fixed length returns is a requirement for static analysis of a contract’s runtime, costs, and other properties.
List operations and functions
Lists may be multi-dimensional. However, note that runtime admission checks on typed function-parameters and data-map functions like set-entry! are charged based on the maximal size of the multi-dimensional list.
You can call filter map and fold functions with user-defined functions (that is, functions defined with (define ...), (define-read-only ...), or (define-public ...)) or simple, native functions (for example, +, -, not).
Intra-contract calls
A smart contract may call functions from other smart contracts using a (contract-call!) function:(contract-call! contract-name function-name arg0 arg1 ...)
This function accepts a function name and the smart contract’s name as input. For example, to call the function token-transfer in the smart contract, you would use:
(contract-call! tokens token-transfer burn-address name-price))
For intra-contract calls dynamic dispatch is not supported. When a contract is launched, any contracts it depends on (calls) must exist. Additionally, no cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs. A static analysis of the call graph detects such structures and they are rejected by the network.
A smart contract may not modify other smart contracts’ data directly; it can read data stored in those smart contracts’ maps. This read ability does not alter any confidentiality guarantees of Clarity. All data in a smart contract is inherently public, andis readable through querying the underlying database in any case.
Reading from other smart contracts
To read another contract’s data, use (fetch-contract-entry) function. This behaves identically to (fetch-entry), though it accepts a contract principal as an argument in addition to the map name:
(fetch-contract-entry
'contract-name
'map-name
'key-tuple) ;; value tuple or none
For example, you could do this:
(fetch-contract-entry
names
name-map
1) ;;returns owner principal of name
Just as with the (contract-call) function, the map name and contract principal arguments must be constants, specified at the time of publishing.
Finally, and importantly, the tx-sender variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. However, the static analysis guarantees of Clarity allow clients to know a priori which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
view all
define and define-public functions
define-read-only functions
define-map functions for data
List operations and functions
Intra-contract calls
Reading from other smart contracts
define and define-public functions
Functions specified via define-public statements are public functions. Functions without these designations, simple define statements, are private functions. You can run a contract’s public functions directly via the clarity-cli execute command line directly or from other contracts. You can use the clarity eval or clarity eval_raw commands to evaluate private functions via the command line.
Public functions return a Response type result. If the function returns an ok type, then the function call is considered valid, and any changes made to the blockchain state will be materialized. If the function returns an err type, it is considered invalid, and has no effect on the smart contract’s state.
For example, consider two functions, foo.A and bar.B where the foo.A function calls bar.B, the table below shows the data materialization that results from the possible combination of return values:

Defining of constants and functions are allowed for simplifying code using a define statement. However, these are purely syntactic. If a definition cannot be inlined, the contract is rejected as illegal. These definitions are also private, in that functions defined this way may only be called by other functions defined in the given smart contract.
define-read-only functions
Functions specified via define-read-only statements are public. Unlike functions created by define-public, functions created with define-read-only may return any type. However, define-read-only statements cannot perform state mutations. Any attempts to modify contract state by these functions or functions called by these functions result in an error.
define-map functions for data
Data within a smart contract’s data-space is stored within maps. These stores relate a typed-tuple to another typed-tuple (almost like a typed key-value store). As opposed to a table data structure, a map only associates a given key with exactly one value. A smart contract defines the data schema of a data map with the define-map function.
(define-map map-name ((key-name-0 key-type-0) ...) ((val-name-0 val-type-0) ...))
Clarity contracts can only call the define-map function in the top-level of the smart-contract (similar to define. This function accepts a name for the map, and a definition of the structure of the key and value types. Each of these is a list of (name, type) pairs. Types are either the values 'principal, 'integer, 'bool or the output of one of the hash calls which is an n-byte fixed-length buffer.
To support the use of named fields in keys and values, Clarity allows the construction of tuples using a function (tuple ((key0 expr0) (key1 expr1) ...)), for example:
(tuple (name "blockstack") (id 1337))
This allows for creating named tuples on the fly, which is useful for data maps where the keys and values are themselves named tuples. To access a named value of a given tuple, the function (get #name tuple) will return that item from the tuple.
The define-map interface, as described, disallows range-queries and queries-by-prefix on data maps. Within a smart contract function, you cannot iterate over an entire map. Values in a given mapping are set or fetched using the following functions:

Data maps make reasoning about functions easier. By inspecting a given function definition, it is clear which maps will be modified and, even within those maps, which keys are affected by a given invocation. Also, the interface of data maps ensures that the return types of map operations are fixed length; Fixed length returns is a requirement for static analysis of a contract’s runtime, costs, and other properties.
List operations and functions
Lists may be multi-dimensional. However, note that runtime admission checks on typed function-parameters and data-map functions like set-entry! are charged based on the maximal size of the multi-dimensional list.
You can call filter map and fold functions with user-defined functions (that is, functions defined with (define ...), (define-read-only ...), or (define-public ...)) or simple, native functions (for example, +, -, not).
Intra-contract calls
A smart contract may call functions from other smart contracts using a (contract-call!) function:
(contract-call! contract-name function-name arg0 arg1 ...)
This function accepts a function name and the smart contract’s name as input. For example, to call the function token-transfer in the smart contract, you would use:
(contract-call! tokens token-transfer burn-address name-price))
For intra-contract calls dynamic dispatch is not supported. When a contract is launched, any contracts it depends on (calls) must exist. Additionally, no cycles may exist in the call graph of a smart contract. This prevents recursion (and re-entrancy bugs. A static analysis of the call graph detects such structures and they are rejected by the network.
A smart contract may not modify other smart contracts’ data directly; it can read data stored in those smart contracts’ maps. This read ability does not alter any confidentiality guarantees of Clarity. All data in a smart contract is inherently public, andis readable through querying the underlying database in any case.
Reading from other smart contracts
To read another contract’s data, use (fetch-contract-entry) function. This behaves identically to (fetch-entry), though it accepts a contract principal as an argument in addition to the map name:
(fetch-contract-entry
'contract-name
'map-name
'key-tuple) ;; value tuple or none
For example, you could do this:
(fetch-contract-entry
names
name-map
1) ;;returns owner principal of name
Just as with the (contract-call) function, the map name and contract principal arguments must be constants, specified at the time of publishing.
Finally, and importantly, the tx-sender variable does not change during inter-contract calls. This means that if a transaction invokes a function in a given smart contract, that function is able to make calls into other smart contracts on your behalf. This enables a wide variety of applications, but it comes with some dangers for users of smart contracts. However, the static analysis guarantees of Clarity allow clients to know a priori which functions a given smart contract will ever call. Good clients should always warn users about any potential side effects of a given transaction.
Principals-a Clarity (smart contract language for blockstack dapps)native type
Others • blockstack app store posted the article • 0 comments • 1497 views • 2019-06-28 00:49
Principals and tx-sender
A principal is represented by a public-key hash or multi-signature Stacks address. Assets in Clarity and the Stacks blockchain are “owned” by objects of the principal type; put another way, principal object types may own an asset.
A given principal operates on its assets by issuing a signed transaction on the Stacks blockchain. A Clarity contract can use a globally defined tx-sender variable to obtain the current principal.
The following user-defined function transfers an asset, in this case, tokens, between two principals:
(define (transfer! (sender principal) (recipient principal) (amount int))
(if (and
(not (eq? sender recipient))
(debit-balance! sender amount)
(credit-balance! recipient amount))
'true
'false))
The principal’s signature is not checked by the smart contract, but by the virtual machine.
Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract’s identifier. You create the identifier when you launch the contract, for example, the contract identifier here is hanomine.
clarity-cli launch hanomine /data/hano.clar /data/db
A smart contract may use the special variable contract-name to refer to its own principal.
To allow smart contracts to operate on assets it owns, smart contracts may use the special (as-contract expr) function. This function executes the expression (passed as an argument) with the tx-sender set to the contract’s principal, rather than the current sender. The as-contract function returns the value of the provided expression.
For example, a smart contract that implements something like a “token faucet” could be implemented as so:
(define-public (claim-from-faucet)
(if (is-none? (fetch-entry claimed-before (tuple (sender tx-sender))))
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(begin
(insert-entry! claimed-before (tuple (sender requester)) (tuple (claimed 'true)))
(as-contract (stacks-transfer! requester 1)))))
(err 1))
In this example, the public function claim-from-faucet:
Checks if the sender has claimed from the faucet before.Assigns the tx sender to a requester variable.Adds an entry to the tracking map.Uses as-contract to send 1 microstack
Contract writers can use the primitive function is-contract? to determine whether a given principal corresponds to a smart contract.
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
view all
Principals and tx-sender
A principal is represented by a public-key hash or multi-signature Stacks address. Assets in Clarity and the Stacks blockchain are “owned” by objects of the principal type; put another way, principal object types may own an asset.
A given principal operates on its assets by issuing a signed transaction on the Stacks blockchain. A Clarity contract can use a globally defined tx-sender variable to obtain the current principal.
The following user-defined function transfers an asset, in this case, tokens, between two principals:
(define (transfer! (sender principal) (recipient principal) (amount int))
(if (and
(not (eq? sender recipient))
(debit-balance! sender amount)
(credit-balance! recipient amount))
'true
'false))
The principal’s signature is not checked by the smart contract, but by the virtual machine.
Smart contracts as principals
Smart contracts themselves are principals and are represented by the smart contract’s identifier. You create the identifier when you launch the contract, for example, the contract identifier here is hanomine.
clarity-cli launch hanomine /data/hano.clar /data/db
A smart contract may use the special variable contract-name to refer to its own principal.
To allow smart contracts to operate on assets it owns, smart contracts may use the special (as-contract expr) function. This function executes the expression (passed as an argument) with the tx-sender set to the contract’s principal, rather than the current sender. The as-contract function returns the value of the provided expression.
For example, a smart contract that implements something like a “token faucet” could be implemented as so:
(define-public (claim-from-faucet)
(if (is-none? (fetch-entry claimed-before (tuple (sender tx-sender))))
(let ((requester tx-sender)) ;; set a local variable requester = tx-sender
(begin
(insert-entry! claimed-before (tuple (sender requester)) (tuple (claimed 'true)))
(as-contract (stacks-transfer! requester 1)))))
(err 1))
In this example, the public function claim-from-faucet:
- Checks if the sender has claimed from the faucet before.
- Assigns the tx sender to a requester variable.
- Adds an entry to the tracking map.
- Uses as-contract to send 1 microstack
Contract writers can use the primitive function is-contract? to determine whether a given principal corresponds to a smart contract.
Unlike other principals, there is no private key associated with a smart contract. As it lacks a private key, a Clarity smart contract cannot broadcast a signed transaction on the blockchain.
Clarity-Blockstack smart contract language tutorials and docs
Others • blockstack app store posted the article • 0 comments • 1757 views • 2019-06-28 00:38
Who should use smart contracts?
Language and program design
The coding environment
Basic building blocks of Clarity contracts
hello-world example
Language rules and limitations
Who should use smart contracts?
You can use Clarity to write standalone contracts or to write contracts that are part of decentralized applications (DApps) you write with the blockstack.js library. Smart contracts allow two parties to exchange anything of value (money, property, shares), in an automated, auditable, and secure way without the services of a middleman. Nick Szabo introduced the canonical metaphor for smart contracts, a vending machine.
In Nick Szabo’s metaphor, the vending machine is the smart contract. The buyer and machine owner are the two parties. A vending machine executes a set of hard-coded actions when the buyer engages with it. The machine displays the items and their prices. A buyer enters money into the machine which determines if the amount fails to mee, meets, or exceeds an item’s price. Based on the amount, the machine asks for more money, dispenses an item, or dispenses and item and change.
Not every application requires smart contracts. If you are not sure or are new to smart contracts concepts, you should read ]a good general explanation of smart contracts[/url] before working with Clarity.
Language and program design
Clarity differs from most other smart contract languages in two essential ways:
The language is not intended to be compiled.The language is not Turing complete.
These differences allow for static analysis of programs to determine properties like runtime cost and data usage.
A Clarity smart contract is composed of two parts — a data-space and a set of functions. Only the associated smart contract may modify its corresponding data-space on the blockchain. Functions are private unless they are defined as public functions. Users call smart contracts’ public functions by broadcasting a transaction on the blockchain which invokes the public function.
Contracts can also call public functions from other smart contracts. The ability to do a static analysis of a smart contract allows a user to determine dependency between contracts.
The coding environment
Clarity is a list processing (LISP) language, as such it is not compiled. Omitting compilation prevents the possibility of error or bugs introduced at the compiler level. You can write Clarity smart contract programs on any operating system with a text editor. You can use any editor you are comfortable with such as Atom, Vim, or even Notepad. The Clarity files you create with an editor have a .clar extension.
Clarity is in pre-release and does not yet directly interact with the live Stacks blockchain. For the pre-release period you need a test environment to run Clarity contracts. Blockstack provides a Docker image called clarity-developer-preview that you can use or you can build a test environment locally from code. Either the Docker image or a local environment is sufficient for testing Clarity programming for standalone contracts.
You use the clarity-cli command line to check, launch, and execute standalone Clarity contracts. You can use this same command line to create simulate mining Stacks and inspecting a blockchain.
Blockstack expects that some decentralized applications (DApp) will want to make use of Clarity contracts as part of their applications. For this purpose, you should use the Clarity SDK, also in pre-release. The SDK is a development environment, testing framework, and deployment tool. It provides a library for safe interactions with Clarity contracts from a DApp written with the blockstack.js library.
Basic building blocks of Clarity contracts
The basic building blocks of Clarity are atoms and lists. An atom is a number or string of contiguous characters. Some examples of atoms:
token-sender10000SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR
Atoms can be native functions, user-defined functions, variables, and values that appear in a program. Functions that mutate data by convention terminate with an ! exclamation point, for example the insert-entry! function.
A list is a sequences of atoms enclosed with () parentheses. Lists can contain other lists. Some examples of lists are:
(get-block-info time 10)(and 'true 'false)(is-none (get id (fetch-entry names-map (tuple (name \"blockstack\")))))
You can add comments to your Clarity contracts using ;; (double semi-colons). Both standalone and inline comments are supported.
;; Transfers tokens to a specified principal (define-public (transfer (recipient principal) (amount int)) (transfer! tx-sender recipient amount)) ;; returns: boolean
You use the clarity-cli command to check and launch a Clarity (.clar) program.
hello-world example
The easiest program to run in any language is a hello world program. In Clarity, you can write this hello-world.clar program.
(begin
(print "hello world"))
This program defines a single hello-world expression that is excuted when the contract launches. The begin is a native Clarity function that evaluates the expressions input to it and returns the value of the last expression. Here there is a single print expression. Both the begin and the print are enclosed in ()parentheses.
For the pre-release, the Blockstack test environment includes the clarity-cli command for interacting with the contract and SQLite to support the data space. You create a SQLLite database to hold data related to Clarity contracts. This database simulates the blockchain by recording the contract activity.
You can’t run even an a hello-world program without first initializing a Clarity contract’s data space within the database. You can use the clarity-cli initialize command to set up the database.
clarity-cli initialize /data/db
This command initializes the db database which resides in the /data directory of the container. You can name the database anything you like, the name db is not required. You can use SQLite to query this database:
sqlite> .open db
sqlite> .tables
contracts maps_table type_analysis_table
data_table simmed_block_table
sqlite>
After you initialize the contract’s data space, you can check a Clarity program for problems.
clarity-cli check ./hello.clar /data/db
As the name implies, the check ensures the contract definition passes a type check; passing programs will returns an exit code of 0 (zero). Once a contract passes a check, you launch it.
root@4224dd95b5f5:/data# clarity-cli launch hello ./hello.clar /data/db
Buffer(BuffData { data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] })
Contract initialized!
Because Clarity does not support simple strings, it stores the hello world string in a buffer. Printing out that string displays the ASCII representation for each character. You can see the record of this contract’s launch in the corresponding database:
sqlite> select * from contracts;
1|hello|{"contract_context":{"name":"hello","variables":{},"functions":{}}}
sqlite> select * from type_analysis_table;
1|hello|{"private_function_types":{},"variable_types":{},"public_function_types":{},"read_only_function_types":{},"map_types":{}}
sqlite>
Language rules and limitations
The Clarity smart contract has the following limitations:
The only atomic types are booleans, integers, fixed length buffers, and principalsRecursion is illegal and there is no lambda function.Looping may only be performed via map, filter, or foldThere is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.Variables are created via let binding and there is no support for mutating functions like set.
view all
Who should use smart contracts?
Language and program design
The coding environment
Basic building blocks of Clarity contracts
hello-world example
Language rules and limitations
Who should use smart contracts?
You can use Clarity to write standalone contracts or to write contracts that are part of decentralized applications (DApps) you write with the blockstack.js library. Smart contracts allow two parties to exchange anything of value (money, property, shares), in an automated, auditable, and secure way without the services of a middleman. Nick Szabo introduced the canonical metaphor for smart contracts, a vending machine.
In Nick Szabo’s metaphor, the vending machine is the smart contract. The buyer and machine owner are the two parties. A vending machine executes a set of hard-coded actions when the buyer engages with it. The machine displays the items and their prices. A buyer enters money into the machine which determines if the amount fails to mee, meets, or exceeds an item’s price. Based on the amount, the machine asks for more money, dispenses an item, or dispenses and item and change.
Not every application requires smart contracts. If you are not sure or are new to smart contracts concepts, you should read ]a good general explanation of smart contracts[/url] before working with Clarity.
Language and program design
Clarity differs from most other smart contract languages in two essential ways:
- The language is not intended to be compiled.
- The language is not Turing complete.
These differences allow for static analysis of programs to determine properties like runtime cost and data usage.
A Clarity smart contract is composed of two parts — a data-space and a set of functions. Only the associated smart contract may modify its corresponding data-space on the blockchain. Functions are private unless they are defined as public functions. Users call smart contracts’ public functions by broadcasting a transaction on the blockchain which invokes the public function.
Contracts can also call public functions from other smart contracts. The ability to do a static analysis of a smart contract allows a user to determine dependency between contracts.
The coding environment
Clarity is a list processing (LISP) language, as such it is not compiled. Omitting compilation prevents the possibility of error or bugs introduced at the compiler level. You can write Clarity smart contract programs on any operating system with a text editor. You can use any editor you are comfortable with such as Atom, Vim, or even Notepad. The Clarity files you create with an editor have a .clar extension.
Clarity is in pre-release and does not yet directly interact with the live Stacks blockchain. For the pre-release period you need a test environment to run Clarity contracts. Blockstack provides a Docker image called clarity-developer-preview that you can use or you can build a test environment locally from code. Either the Docker image or a local environment is sufficient for testing Clarity programming for standalone contracts.
You use the clarity-cli command line to check, launch, and execute standalone Clarity contracts. You can use this same command line to create simulate mining Stacks and inspecting a blockchain.
Blockstack expects that some decentralized applications (DApp) will want to make use of Clarity contracts as part of their applications. For this purpose, you should use the Clarity SDK, also in pre-release. The SDK is a development environment, testing framework, and deployment tool. It provides a library for safe interactions with Clarity contracts from a DApp written with the blockstack.js library.
Basic building blocks of Clarity contracts
The basic building blocks of Clarity are atoms and lists. An atom is a number or string of contiguous characters. Some examples of atoms:
- token-sender
- 10000
- SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR
Atoms can be native functions, user-defined functions, variables, and values that appear in a program. Functions that mutate data by convention terminate with an ! exclamation point, for example the insert-entry! function.
A list is a sequences of atoms enclosed with () parentheses. Lists can contain other lists. Some examples of lists are:
- (get-block-info time 10)
- (and 'true 'false)
- (is-none (get id (fetch-entry names-map (tuple (name \"blockstack\")))))
You can add comments to your Clarity contracts using ;; (double semi-colons). Both standalone and inline comments are supported.
;; Transfers tokens to a specified principal (define-public (transfer (recipient principal) (amount int)) (transfer! tx-sender recipient amount)) ;; returns: boolean
You use the clarity-cli command to check and launch a Clarity (.clar) program.
hello-world example
The easiest program to run in any language is a hello world program. In Clarity, you can write this hello-world.clar program.
(begin
(print "hello world"))
This program defines a single hello-world expression that is excuted when the contract launches. The begin is a native Clarity function that evaluates the expressions input to it and returns the value of the last expression. Here there is a single print expression. Both the begin and the print are enclosed in ()parentheses.
For the pre-release, the Blockstack test environment includes the clarity-cli command for interacting with the contract and SQLite to support the data space. You create a SQLLite database to hold data related to Clarity contracts. This database simulates the blockchain by recording the contract activity.
You can’t run even an a hello-world program without first initializing a Clarity contract’s data space within the database. You can use the clarity-cli initialize command to set up the database.
clarity-cli initialize /data/db
This command initializes the db database which resides in the /data directory of the container. You can name the database anything you like, the name db is not required. You can use SQLite to query this database:
sqlite> .open db
sqlite> .tables
contracts maps_table type_analysis_table
data_table simmed_block_table
sqlite>
After you initialize the contract’s data space, you can check a Clarity program for problems.
clarity-cli check ./hello.clar /data/db
As the name implies, the check ensures the contract definition passes a type check; passing programs will returns an exit code of 0 (zero). Once a contract passes a check, you launch it.
root@4224dd95b5f5:/data# clarity-cli launch hello ./hello.clar /data/db
Buffer(BuffData { data: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] })
Contract initialized!
Because Clarity does not support simple strings, it stores the hello world string in a buffer. Printing out that string displays the ASCII representation for each character. You can see the record of this contract’s launch in the corresponding database:
sqlite> select * from contracts;
1|hello|{"contract_context":{"name":"hello","variables":{},"functions":{}}}
sqlite> select * from type_analysis_table;
1|hello|{"private_function_types":{},"variable_types":{},"public_function_types":{},"read_only_function_types":{},"map_types":{}}
sqlite>
Language rules and limitations
The Clarity smart contract has the following limitations:
- The only atomic types are booleans, integers, fixed length buffers, and principals
- Recursion is illegal and there is no lambda function.
- Looping may only be performed via map, filter, or fold
- There is support for lists of the atomic types, however, the only variable length lists in the language appear as function inputs; There is no support for list operations like append or join.
- Variables are created via let binding and there is no support for mutating functions like set.