### Install Dependencies Source: https://github.com/clarity-lang/book/blob/main/README.md Run this command to install the necessary build dependencies for the Clarity book. ```bash npm install ``` -------------------------------- ### Run Local Development Server Source: https://github.com/clarity-lang/book/blob/main/README.md Use this command to start a local instance of the Clarity book. It will automatically rebuild when file changes are detected. ```bash npm run dev ``` -------------------------------- ### Create a List of ASCII Strings in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch02-02-sequence-types.md This example demonstrates creating a list where all elements are ASCII strings. ```Clarity (list "Hello" "World" "!") ``` -------------------------------- ### Verify Homebrew Installation Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Check if Homebrew has been installed correctly by running the version command. This confirms the package manager is accessible. ```bash % brew --version Homebrew 3.6.3 ``` -------------------------------- ### Install Clarinet on macOS using Homebrew Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Install the Clarinet command line tool on macOS using the Homebrew package manager. Follow any on-screen prompts. ```bash brew install clarinet ``` -------------------------------- ### Build Clarinet from Source using Cargo Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Clone the Clarinet repository, navigate into the directory, and use Cargo to build and install Clarinet. Ensure you have Rust and Cargo installed. ```bash git clone https://github.com/hirosystems/clarinet.git --recursive cd clarinet cargo clarinet-install ``` -------------------------------- ### Install Clarinet on Windows using Winget Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Install Clarinet on Windows using the Winget package manager. This command is run in PowerShell. ```powershell winget install clarinet ``` -------------------------------- ### Install Build Dependencies on Debian/Ubuntu Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Install necessary packages for building Clarinet from source on Debian and Ubuntu-based systems. These include build-essential, pkg-config, and libssl-dev. ```bash sudo apt install build-essential pkg-config libssl-dev ``` -------------------------------- ### Install Homebrew on macOS Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Install Homebrew, the macOS package manager, using the provided script. This is a prerequisite for installing Clarinet via Homebrew. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Install the command line tools for Xcode, which are required by Homebrew. Run this in your Terminal application. ```bash xcode-select --install ``` -------------------------------- ### Verify Clarinet Installation Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Confirm that Clarinet has been installed successfully by running the `clarinet --version` command in your terminal. This displays the installed Clarinet CLI version. ```bash % clarinet --version clarinet-cli 3.2.0 ``` -------------------------------- ### Get the Length of a String in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch02-02-sequence-types.md This example demonstrates using the `len` function to find the length of a string. ```Clarity (len "How long is this string?") ``` -------------------------------- ### Example of try! with response types Source: https://github.com/clarity-lang/book/blob/main/src/ch06-02-try.md This example defines a function that uses try! to handle response types. It shows how try! propagates 'err' values and allows the function to complete successfully with 'ok' values. ```Clarity (define-public (try-example (input (response uint uint))) (begin (try! input) (ok "end of the function") ) ) ``` ```Clarity (print (try-example (ok u1))) ``` ```Clarity (print (try-example (err u2))) ``` -------------------------------- ### Start Clarinet console Source: https://github.com/clarity-lang/book/blob/main/src/ch07-03-interacting-with-your-contract.md Initiates an interactive Clarinet console session. Clarinet automatically deploys contracts defined in `Clarinet.toml`. Press CTRL + D to exit. ```bash clarinet console ``` -------------------------------- ### Download and Install Clarinet from Pre-built Binary (Linux) Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Download the latest Clarinet binary for Linux, extract it, make it executable, and move it to a directory in your system's PATH. Replace v3.2.0 with the latest version. ```sh # note: you can change v3.2.0 with the latest version available on the releases page. wget -nv https://github.com/hirosystems/clarinet/releases/download/v3.2.0/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz tar -xf clarinet-linux-x64.tar.gz chmod +x ./clarinet mv ./clarinet /usr/local/bin ``` -------------------------------- ### Create a List of Signed Integers in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch02-02-sequence-types.md Lists are fixed-length sequences containing items of the same type. This example shows a list of signed integers. ```Clarity (list 4 8 15 16 23 42) ``` -------------------------------- ### Match Expression Example Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Demonstrates the `match` expression in Clarity, which is used for conditional execution based on the structure of an input, such as an optional value. ```Clarity (match (some "inner string") inner-str (print inner-str) (print "got nothing") ) ``` -------------------------------- ### Asserts! Passing Example Source: https://github.com/clarity-lang/book/blob/main/src/ch06-01-asserts.md Demonstrates a successful assertion where the boolean expression evaluates to true. Execution proceeds normally. ```Clarity (asserts! true (err "failed")) ``` -------------------------------- ### Reduce Contract Calls: After Optimization Source: https://github.com/clarity-lang/book/blob/main/src/ch12-00-runtime-cost-analysis.md This optimized example shows how to consolidate calls to a storage contract into a single call, returning a tuple to reduce read costs. ```Clarity (define-public (example-2) (let ( ;; Here the storage is called only once. Cost savings! (value-a-b (contract-call? .storage-contract get-value-a-and-b)) ;; The value returned is a tuple containing both values. (value-a (get a value-a-b)) (value-b (get b value-a-b)) ) ;; Business logic here... (ok true) ) ) ``` -------------------------------- ### Clarity Cost Report Example Source: https://github.com/clarity-lang/book/blob/main/src/ch12-00-runtime-cost-analysis.md An example of a Clarity cost analysis report generated by Clarinet. It shows the resource consumption of contract functions relative to mainnet block limits. ```text Running counter/tests/counter_test.ts * get-count returns u0 for principals that never called count-up before ... ok (5ms) * count-up counts up for the tx-sender ... ok (6ms) * counters are specific to the tx-sender ... ok (13ms) test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out (382ms) Contract calls cost synthesis +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ | | Runtime (units) | Read Count | Read Length (bytes) | Write Count | Write Length (bytes) | Tx per Block | +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ | counter::count-up | 6692 (0.00%) | 5 (0.03%) | 418 (0.00%) | 1 (0.01%) | 165 (0.00%) | 1550 | +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ | counter::get-count | 3213 (0.00%) | 4 (0.03%) | 418 (0.00%) | 0 | 0 | 1937 | +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ | | +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ | Mainnet Block Limits (Stacks 2.0) | 5000000000 | 15000 | 100000000 | 15000 | 15000000 | / | +-----------------------------------+-----------------+------------+---------------------+-------------+----------------------+--------------+ ``` -------------------------------- ### Define a Public 'hello-world' Function Source: https://github.com/clarity-lang/book/blob/main/src/ch05-00-functions.md Defines a public function named 'hello-world' that takes no parameters and returns a success result with the string 'Hello World!'. This is a basic example of a public function. ```Clarity (define-public (hello-world) (ok "Hello World!") ) (print (hello-world)) ``` -------------------------------- ### Transfer Tokens With Memo Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Example of transferring 100 tokens with a memo (`0x123456`). This demonstrates both the FT transfer event and a subsequent print event containing the memo. ```Clarity >> (contract-call? .clarity-coin transfer u100 tx-sender 'ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK (some 0x123456)) Events emitted {"type":"ft_transfer_event","ft_transfer_event":{"asset_identifier":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.clarity-coin::clarity-coin","sender":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE","recipient":"ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK","amount":"100"}} {"type":"contract_event","contract_event":{"contract_identifier":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.clarity-coin","topic":"print","value":"0x123456"}} (ok true) ``` -------------------------------- ### Map Principal to Unsigned Integer Balances Source: https://github.com/clarity-lang/book/blob/main/src/ch04-03-maps.md Example of defining a map for principal-to-uint balances, setting a sender's balance, and retrieving it. Note that `map-get?` returns an optional type. ```Clarity ;; A map that creates a principal => uint relation. (define-map balances principal uint) ;; Set the "balance" of the tx-sender to u500. (map-set balances tx-sender u500) ;; Retrieve the balance. (print (map-get? balances tx-sender)) ``` -------------------------------- ### Implement SIP010 Get Balance Function Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Implement the read-only `get-balance` function to return the token balance for a given principal by wrapping the built-in `ft-get-balance`. ```Clarity (define-read-only (get-balance (who principal)) (ok (ft-get-balance clarity-coin who)) ) ``` -------------------------------- ### Query Token Balance Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Example of querying the balance of a specific principal (`ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK`) for the custom token. This verifies the total balance after transfers. ```Clarity >> (contract-call? .clarity-coin get-balance 'ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK) (ok u350) ``` -------------------------------- ### Analyze cost of 'sha512' function Source: https://github.com/clarity-lang/book/blob/main/src/ch12-00-runtime-cost-analysis.md Analyze the runtime cost of cryptographic functions like `sha512`. This example demonstrates the cost associated with hashing a small unsigned integer. ```clarity >> ::get_costs (sha512 u1234) +----------------------+----------+------------+ | | Consumed | Limit | +----------------------+----------+------------+ | Runtime | 193 | 5000000000 | +----------------------+----------+------------+ | Read count | 0 | 15000 | +----------------------+----------+------------+ | Read length (bytes) | 0 | 100000000 | +----------------------+----------+------------+ | Write count | 0 | 15000 | +----------------------+----------+------------+ | Write length (bytes) | 0 | 15000000 | +----------------------+----------+------------+ 0x523be47185d0ffe54cb649d4e6303db92f54d2949becd8b6c0c91830006523b155fd9eaad1095c0f208012c9fffd6618e5730caf511cfc41786005089c0dc013 ``` -------------------------------- ### Reduce Contract Calls: Before Optimization Source: https://github.com/clarity-lang/book/blob/main/src/ch12-00-runtime-cost-analysis.md This example demonstrates a scenario where a storage contract is called twice, leading to increased read costs. Consider optimizing by consolidating calls. ```Clarity (define-public (example-1) (let ( ;; Here the storage contract is called twice, which means ;; the contract code is loaded twice, which in turn means ;; the read dimension is incremented twice. (value-a (contract-call? .storage-contract get-value-a)) (value-b (contract-call? .storage-contract get-value-b)) ) ;; Business logic here... (ok true) ) ) ``` -------------------------------- ### Clarinet test execution output Source: https://github.com/clarity-lang/book/blob/main/src/ch07-04-testing-your-contract.md Example output from running Clarinet tests using 'npm test', indicating successful execution of all three tests. ```bash ✓ tests/counter.test.ts (3) ✓ get-count returns u0 for principals that never called count-up before ✓ count-up counts up for the tx-sender ✓ counters are specific to the tx-sender ``` -------------------------------- ### Import necessary testing utilities and Clarity types Source: https://github.com/clarity-lang/book/blob/main/src/ch08-02-smart-claimant.md Imports required for Vitest and Clarity transactions. Ensure `npm install` is run and necessary packages are added. ```javascript import { describe, expect, test } from "vitest"; import { Cl } from "@stacks/transactions"; ``` ```typescript import { Cl } from "@stacks/transactions"; import { expect, test } from "vitest"; ``` -------------------------------- ### Implement SIP010 Get Decimals Function Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Implement the read-only `get-decimals` function to specify the number of decimal places for the fungible token, used for display purposes. ```Clarity (define-read-only (get-decimals) (ok u6) ) ``` -------------------------------- ### Mint Tokens via Contract Call Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Example of minting 1000 tokens for the current transaction sender using the `mint` function. This demonstrates the FT mint event emission. ```Clarity >> (contract-call? .clarity-coin mint u1000 tx-sender) Events emitted {"type":"ft_mint_event","ft_mint_event":{"asset_identifier":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.clarity-coin::clarity-coin","recipient":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE","amount":"1000"}} (ok true) ``` -------------------------------- ### Loop Unrolling for Cost Reduction in Clarity Source: https://context7.com/clarity-lang/book/llms.txt Reduces runtime cost for small, fixed-size lists by unrolling loops. This example sums values from a list of five elements. ```clarity ;; Loop unrolling to reduce runtime cost for small fixed-size lists (define-read-only (sum-values-unwind (values (list 10 uint))) (+ (default-to u0 (element-at? values u0)) (default-to u0 (element-at? values u1)) (default-to u0 (element-at? values u2)) (default-to u0 (element-at? values u3)) (default-to u0 (element-at? values u4)) ) ) ``` -------------------------------- ### TypeScript Unit Tests for Get Vote Functionality Source: https://github.com/clarity-lang/book/blob/main/src/ch08-03-multi-signature-vault.md Tests for the read-only 'get-vote' function. This snippet verifies that a member's vote status for a specific principal can be correctly retrieved. It includes setup for starting the vault, depositing funds, and casting a vote. ```typescript describe("Testing get-vote", () => { test("Can retrieve a member's vote for a principal", () => { simnet.callPublicFn( "multisig-vault", "start", [members, Cl.uint(members.list.length)], deployer ); simnet.callPublicFn( "multisig-vault", "deposit", [Cl.uint(stxVaultAmount)], deployer ); simnet.callPublicFn( "multisig-vault", "vote", [Cl.principal(deployer), Cl.bool(true)], wallet1 ); const voteResponse = simnet.callReadOnlyFn( "multisig-vault", "get-vote", [Cl.principal(wallet1), Cl.principal(deployer)], deployer ); expect(voteResponse.result).toBeBool(true); }); }); ``` -------------------------------- ### Get the Length of a Buffer in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch02-02-sequence-types.md The `len` function retrieves the length of a sequence. This example shows getting the length of a buffer. ```Clarity (len 0x68656c6c6f21) ``` -------------------------------- ### Get the Length of a List in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch02-02-sequence-types.md Use the `len` function to determine the number of elements in a list. This example gets the length of a list of integers. ```Clarity (len (list 4 8 15 16 23 42)) ``` -------------------------------- ### Build HTML Version Source: https://github.com/clarity-lang/book/blob/main/README.md Execute this command to generate an HTML version of the Clarity book, outputting to the `build` folder. ```bash npm run build ``` -------------------------------- ### Initialize New Clarinet Project Source: https://github.com/clarity-lang/book/blob/main/src/ch07-01-creating-a-new-project.md Use this command to create a new project directory with the basic structure required by Clarinet. This includes directories for contracts, settings, and tests, along with essential configuration files. ```bash clarinet new counter ``` -------------------------------- ### Retrieve a tuple member by name Source: https://github.com/clarity-lang/book/blob/main/src/ch02-03-composite-types.md Use the `get` function to access a specific member of a tuple by its name. For example, `(get username my-tuple)`. ```Clarity (get username { id: 5, username: "ClarityIsAwesome" }) ``` -------------------------------- ### Monolithic DAO Contract Example Source: https://github.com/clarity-lang/book/blob/main/src/ch13-03-contract-upgradability.md A monolithic Clarity contract for a DAO-like system managing proposals and votes. It includes logic for submitting proposals, voting, and managing members, all within a single contract. ```clarity (define-constant err-not-whitelisted (err u100)) (define-constant err-unknown-proposal (err u101)) (define-constant err-not-member (err u102)) (define-constant err-already-voted (err u103)) (define-constant err-voting-ended (err u104)) (define-constant proposal-duration u1440) (define-data-var proposal-nonce uint u0) (define-map proposals uint { proposer: principal, title: (string-ascii 100), end-height: uint, yes-votes: uint, no-votes: uint } ) (define-map proposal-votes {voter: principal, proposal-id: uint} {vote-height: uint, for: bool}) (define-map members principal bool) (define-map whitelisted-members principal bool) (define-read-only (get-proposal (proposal-id uint)) (ok (map-get? proposals proposal-id)) ) (define-public (submit-proposal (title (string-ascii 100))) (let ( (proposal-id (+ (var-get proposal-nonce) u1)) ) (asserts! (default-to false (map-get? whitelisted-members tx-sender)) err-not-whitelisted) (map-set proposals proposal-id { proposer: tx-sender, title: title, end-height: (+ block-height proposal-duration), yes-votes: u0, no-votes: u0 } ) (var-set proposal-nonce proposal-id) (ok proposal-id) ) ) (define-read-only (get-vote (member principal) (proposal-id uint)) (map-get? proposal-votes {voter: member, proposal-id: proposal-id}) ) (define-public (vote (for bool) (proposal-id uint)) (let ( (proposal (unwrap! (map-get? proposals proposal-id) err-unknown-proposal)) ) (asserts! (default-to false (map-get? members tx-sender)) err-not-member) (asserts! (< block-height (get end-height proposal)) err-voting-ended) (asserts! (is-none (get-vote tx-sender proposal-id)) err-already-voted) (map-set proposal-votes {voter: tx-sender, proposal-id: proposal-id} {vote-height: block-height, for: for}) (if for (map-set proposals proposal-id (merge proposal {yes-votes: (+ (get yes-votes proposal) u1)})) (map-set proposals proposal-id (merge proposal {no-votes: (+ (get no-votes proposal) u1)})) ) (ok true) ) ) ``` -------------------------------- ### Create a new Clarinet project Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Use the `clarinet new` command to initialize a new project for your smart contract development. ```bash clarinet new sip010-ft ``` -------------------------------- ### TypeScript Unit Tests for Voting Functionality Source: https://github.com/clarity-lang/book/blob/main/src/ch08-03-multi-signature-vault.md Tests for the 'vote' function. Verifies that only members can vote and that non-members receive an appropriate error. It also includes setup for starting the vault and depositing funds. ```typescript describe("Testing vote", () => { test("Allows members to vote", () => { simnet.callPublicFn( "multisig-vault", "start", [members, Cl.uint(members.list.length)], deployer ); simnet.callPublicFn( "multisig-vault", "deposit", [Cl.uint(stxVaultAmount)], deployer ); const voteResponse = simnet.callPublicFn( "multisig-vault", "vote", [Cl.principal(deployer), Cl.bool(true)], deployer ); expect(voteResponse.result).toBeOk(Cl.bool(true)); }); test("Does not allow non-members to vote", () => { // Without deployer const members = Cl.list([ Cl.principal(wallet1), Cl.principal(wallet2), Cl.principal(wallet3), Cl.principal(wallet4), ]); simnet.callPublicFn( "multisig-vault", "start", [members, Cl.uint(members.list.length)], deployer ); simnet.callPublicFn( "multisig-vault", "deposit", [Cl.uint(stxVaultAmount)], deployer ); const voteResponse = simnet.callPublicFn( "multisig-vault", "vote", [Cl.principal(deployer), Cl.bool(true)], deployer ); expect(voteResponse.result).toBeErr(Cl.uint(103)); }); }); ``` -------------------------------- ### Implement Read-only Function to Get Counter by Principal Source: https://github.com/clarity-lang/book/blob/main/src/ch05-03-read-only-functions.md This snippet requires implementing a read-only function to fetch a counter value associated with a specific principal from a map. It includes setup for the map and sample data, along with assertions for validation. ```Clarity (define-map counters principal uint) (map-set counters 'ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK u5) (map-set counters 'ST20ATRN26N9P05V2F1RHFRV24X8C8M3W54E427B2 u10) (define-read-only (get-counter-of (who principal)) ;; Implement. ) ;; These exist: (print (get-counter-of 'ST1J4G6RR643BCG8G8SR6M2D9Z9KXT2NJDRK3FBTK)) (print (get-counter-of 'ST20ATRN26N9P05V2F1RHFRV24X8C8M3W54E427B2)) ;; This one does not: (print (get-counter-of 'ST21HMSJATHZ888PD0S0SSTWP4J61TCRJYEVQ0STB)) ``` -------------------------------- ### Create a new Clarinet project Source: https://github.com/clarity-lang/book/blob/main/src/ch10-02-creating-a-sip009-nft.md Initialize a new Clarinet project for your NFT contract using the `clarinet new` command. ```bash clarinet new sip009-nft ``` -------------------------------- ### Map String Key with Optional Retrieval and Unwrap Source: https://github.com/clarity-lang/book/blob/main/src/ch04-03-maps.md Example of mapping a string-ascii key to a principal. Demonstrates retrieving a value that exists, a value that does not exist (returning `none`), and unwrapping a value using `unwrap-panic`. ```Clarity ;; A map that creates a string-ascii => uint relation. (define-map names (string-ascii 34) principal) ;; Point the name "Clarity" to the tx-sender. (map-set names "Clarity" tx-sender) ;; Retrieve the principal related to the name "Clarity". (print (map-get? names "Clarity")) ;; Retrieve the principal for a key that does not exist. It will return `none`. (print (map-get? names "bogus")) ;; Unwrap a value: (print (unwrap-panic (map-get? names "Clarity"))) ``` -------------------------------- ### Clarinet Project Initialization Output Source: https://github.com/clarity-lang/book/blob/main/src/ch07-01-creating-a-new-project.md This output shows the files and directories created when initializing a new Clarinet project. It includes the project folder, contract and test directories, configuration files, and VS Code settings. ```bash Creating directory counter Creating directory counter/contracts Creating directory counter/settings Creating directory counter/tests Creating file counter/Clarinet.toml Creating file counter/settings/Devnet.toml Creating file counter/settings/Mocknet.toml Creating directory counter/.vscode Creating file counter/.vscode/settings.json ``` -------------------------------- ### Measure Runtime Cost of 'begin' in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch13-01-coding-style.md Demonstrates the runtime cost difference between a simple addition and the same addition wrapped in a 'begin' statement. Using 'begin' incurs a higher cost. ```Clarity >> ::get_costs (+ 1 2) +----------------------+ | | Consumed | Limit | +----------------------+ | Runtime | 4000 | 5000000000 | +----------------------+ 3 ``` ```Clarity >> ::get_costs (begin (+ 1 2)) +----------------------+ | | Consumed | Limit | +----------------------+ | Runtime | 6000 | 5000000000 | +----------------------+ 3 ``` -------------------------------- ### Mint a token using Clarinet console Source: https://github.com/clarity-lang/book/blob/main/src/ch10-02-creating-a-sip009-nft.md Example of minting a new token for the transaction sender using the `mint` function via the Clarinet console, showing the emitted NFT mint event and the transaction result. ```Clarity >> (contract-call? .stacksies mint tx-sender) Events emitted {"type":"nft_mint_event","nft_mint_event":{"asset_identifier":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.stacksies::stacksies","recipient":"ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE","value":"u1"}} (ok u1) ``` -------------------------------- ### Map Insert, Set, and Delete Operations Source: https://github.com/clarity-lang/book/blob/main/src/ch04-03-maps.md Shows the difference between `map-insert` (which fails if the key exists) and `map-set` (which overwrites). Also demonstrates deleting an entry with `map-delete`. ```Clarity (define-map scores principal uint) ;; Insert a value. (map-insert scores tx-sender u100) ;; This second insert will do nothing because the key already exists. (map-insert scores tx-sender u200) ;; The score for tx-sender will be u100. (print (map-get? scores tx-sender)) ;; Delete the entry for tx-sender. (map-delete scores tx-sender) ;; Will return none because the entry got deleted. (print (map-get? scores tx-sender)) ``` -------------------------------- ### Intermediary Response Example Source: https://github.com/clarity-lang/book/blob/main/src/ch06-04-response-checking.md This example shows an intermediary response `(err false)` within a `begin` block that is not checked, leading to an analysis error. ```Clarity (begin true ;; this is a boolean, so it is fine. (err false) ;; this is an *intermediary response*. (ok true) ;; this is the response returned by the begin. ) ``` -------------------------------- ### Optimise Contract Calls in Clarity Source: https://context7.com/clarity-lang/book/llms.txt Demonstrates batching contract calls to reduce read-length overhead by making a single call instead of multiple. ```clarity ;; Optimisation: batch contract calls to reduce read-length overhead (define-public (example-optimised) (let ( ;; One call instead of two — reads contract code once, not twice (value-a-b (contract-call? .storage-contract get-value-a-and-b)) (value-a (get a value-a-b)) (value-b (get b value-a-b)) ) (ok true) ) ) ``` -------------------------------- ### Use 'begin' for Multi-Expression Function Body Source: https://github.com/clarity-lang/book/blob/main/src/ch05-00-functions.md Demonstrates the use of the 'begin' special form to execute multiple expressions within a function body, returning the result of the last expression. This is essential for complex function logic. ```Clarity (define-public (print-twice (first (string-ascii 40)) (second (string-ascii 40))) (begin (print first) (print second) (ok true) ) ) (print-twice "Hello world!" "Multiple prints!") ``` -------------------------------- ### Get Listing Details Source: https://github.com/clarity-lang/book/blob/main/src/ch11-02-listing-and-cancelling.md Retrieves the details of a specific NFT listing by its ID. ```APIDOC ## get-listing ### Description Retrieves the details of a specific NFT listing from the marketplace using its unique listing ID. ### Method (define-read-only get-listing) ### Parameters - **listing-id** (uint) - The unique identifier of the listing to retrieve. ### Response #### Success Response (map-get? listings listing-id) - Returns a tuple containing the listing details if found, otherwise returns none. ``` -------------------------------- ### Clarinet Test Execution Output Source: https://github.com/clarity-lang/book/blob/main/src/ch07-04-testing-your-contract.md Example output indicating a successful test run for the 'counter.test.ts' file. ```bash ✓ tests/counter.test.ts (1) ✓ get-count returns u0 for principals that never called count-up before ``` -------------------------------- ### Assigning unwrapped map data with let and unwrap! Source: https://github.com/clarity-lang/book/blob/main/src/ch06-03-unwrap-flavours.md This example demonstrates using `unwrap!` within a `let` binding to safely retrieve and assign data from a map, exiting with a specific error if the key is not found. ```Clarity ;; Some error constants (define-constant err-unknown-listing (err u100)) (define-constant err-not-the-maker (err u101)) ;; Define an example map called listings, identified by a uint. (define-map listings {id: uint} {name: (string-ascii 50), maker: principal} ) ;; Insert some sample data (map-set listings {id: u1} {name: "First Listing", maker: tx-sender}) (map-set listings {id: u2} {name: "Second Listing", maker: tx-sender}) ;; Simple function to get a listing (define-read-only (get-listing (id uint)) (map-get? listings {id: id}) ) ;; Update name function that only the maker for a specific listing ;; can call. (define-public (update-name (id uint) (new-name (string-ascii 50))) (let ( ;; The magic happens here. (listing (unwrap! (get-listing id) err-unknown-listing)) ) (asserts! (is-eq contract-caller (get maker listing)) err-not-the-maker) (map-set listings {id: id} (merge listing {name: new-name})) (ok true) ) ) ;; Two test calls (print (update-name u1 "New name!")) (print (update-name u9999 "Nonexistent listing...")) ``` -------------------------------- ### Implement SIP010 Get Symbol Function Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Implement the read-only `get-symbol` function to return a human-readable symbol for the fungible token. ```Clarity (define-read-only (get-symbol) (ok "CC") ) ``` -------------------------------- ### Create a new Clarity contract Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Use the `clarinet contract new` command to generate a new smart contract file within your project. ```bash clarinet contract new clarity-coin ``` -------------------------------- ### Implement SIP010 Get Name Function Source: https://github.com/clarity-lang/book/blob/main/src/ch10-04-creating-a-sip010-ft.md Implement the read-only `get-name` function to return a human-readable name for the fungible token. ```Clarity (define-read-only (get-name) (ok "Clarity Coin") ) ``` -------------------------------- ### Interactive Clarity Expression Source: https://github.com/clarity-lang/book/blob/main/src/ch01-02-clarity-basics.md An example of a Clarity expression that can be evaluated interactively. It includes metadata for expected output and a hint for conversion. ```Clarity ```Clarity,{"expected_output":"15","hint":"Convert the following calculation to Clarity code:\n(5 * 4) - 5"} ``` ``` -------------------------------- ### Get STX Balance of a Principal Source: https://github.com/clarity-lang/book/blob/main/src/ch02-01-primitive-types.md Retrieves the current STX balance for a given principal. Pass the principal as an argument to the `stx-get-balance` function. ```Clarity (stx-get-balance 'ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE) ``` ```Clarity (stx-get-balance 'ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.my-contract) ``` -------------------------------- ### Asserts! Failing Example Source: https://github.com/clarity-lang/book/blob/main/src/ch06-01-asserts.md Illustrates a failed assertion where the boolean expression is false. The function returns the specified throw value and exits. ```Clarity (asserts! false (err "failed")) ``` -------------------------------- ### Sequential Expression Evaluation with `begin` Source: https://github.com/clarity-lang/book/blob/main/src/ch06-00-control-flow.md Illustrates the default left-to-right evaluation order of expressions within a `begin` block. Each expression is evaluated sequentially. ```Clarity (begin (print "First") (print "Second") (print "Third") ) ``` -------------------------------- ### Define Read-Only Get Vote Function in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch08-03-multi-signature-vault.md Retrieves a specific member's vote for a recipient. Defaults to false if no vote is recorded. ```Clarity (define-read-only (get-vote (member principal) (recipient principal)) (default-to false (get decision (map-get? votes {member: member, recipient: recipient}))) ) ``` -------------------------------- ### Manage Data Variables in Clarity Source: https://github.com/clarity-lang/book/blob/main/src/ch04-02-variables.md Demonstrates defining, reading, and updating a data variable. Use `var-get` to retrieve the current value and `var-set` to change it. ```Clarity ;; Define an unsigned integer data var with an initial value of u0. (define-data-var my-number uint u0) ;; Print the initial value. (print (var-get my-number)) ;; Change the value. (var-set my-number u5000) ;; Print the new value. (print (var-get my-number)) ``` -------------------------------- ### Manual Cost Check in Clarinet Console (Bash) Source: https://context7.com/clarity-lang/book/llms.txt Demonstrates how to manually check Clarity function costs using the `::get_costs` function in the Clarinet console. This helps in understanding the resource consumption of different operations. ```bash # Manual cost check in clarinet console >> ::get_costs (not false) # Runtime: 186 units >> ::get_costs (contract-call? .counter count-up) # Runtime: 6692 | Read count: 5 | Write count: 1 ``` -------------------------------- ### Checkout Latest Stable Branch for Clarinet Source: https://github.com/clarity-lang/book/blob/main/src/ch01-01-installing-tools.md Switch from the development branch to the main branch to get the latest stable version of Clarinet if you are not contributing to the code. ```bash git checkout main ``` -------------------------------- ### Configure Bogus NFT Contract in Clarinet.toml Source: https://github.com/clarity-lang/book/blob/main/src/ch11-04-unit-tests.md Instantiate the same contract file under a different name in Clarinet.toml to test listings against different assets. ```toml [contracts.sip009-nft] path = "contracts/sip009-nft.clar" [contracts.bogus-nft] path = "contracts/sip009-nft.clar" ``` -------------------------------- ### Analyze cost of 'not' function Source: https://github.com/clarity-lang/book/blob/main/src/ch12-00-runtime-cost-analysis.md Use `::get_costs` to display the runtime analysis of a Clarity expression. This example shows the cost of negating a boolean value. ```clarity >> ::get_costs (not false) +----------------------+----------+------------+ | | Consumed | Limit | +----------------------+----------+------------+ | Runtime | 186 | 5000000000 | +----------------------+----------+------------+ | Read count | 0 | 15000 | +----------------------+----------+------------+ | Read length (bytes) | 0 | 100000000 | +----------------------+----------+------------+ | Write count | 0 | 15000 | +----------------------+----------+------------+ | Write length (bytes) | 0 | 15000000 | +----------------------+----------+------------+ true ``` -------------------------------- ### Test withdraw function success Source: https://github.com/clarity-lang/book/blob/main/src/ch08-03-multi-signature-vault.md Tests if a principal meeting the vote threshold can successfully withdraw the vault balance. Assumes prior setup and deposits. ```typescript describe("Testing withdraw", () => { test("Principal that meets the vote threshold can withdraw the vault balance", () => { simnet.callPublicFn( "multisig-vault", "start", [members, Cl.uint(votesRequired)], deployer ); simnet.callPublicFn( "multisig-vault", "deposit", [Cl.uint(stxVaultAmount)], deployer ); simnet.callPublicFn( "multisig-vault", "vote", [Cl.principal(wallet1), Cl.bool(true)], deployer ); simnet.callPublicFn( "multisig-vault", "vote", [Cl.principal(wallet1), Cl.bool(true)], wallet2 ); const withdrawResponse = simnet.callPublicFn( "multisig-vault", "withdraw", [], wallet1 ); expect(withdrawResponse.result).toBeOk(Cl.uint(2)); }); ``` -------------------------------- ### Define and Use Maps in Clarity Source: https://context7.com/clarity-lang/book/llms.txt Maps provide key-value storage similar to hash tables. Use `define-map`, `map-get?`, `map-set`, `map-insert`, and `map-delete`. Keys must be specified for lookups. ```clarity ;; Principal → uint balance map (define-map balances principal uint) ``` ```clarity (map-set balances tx-sender u500) ``` ```clarity (print (map-get? balances tx-sender)) ;; => (some u500) ``` ```clarity ;; Tuple key, tuple value (define-map orders uint {maker: principal, amount: uint}) ``` ```clarity (map-set orders u0 {maker: tx-sender, amount: u50}) ``` ```clarity (map-set orders u1 {maker: tx-sender, amount: u120}) ``` ```clarity (print (map-get? orders u1)) ;; => (some {maker: ..., amount: u120}) ``` ```clarity ;; map-insert: does nothing if key already exists (returns false) (define-map scores principal uint) ``` ```clarity (map-insert scores tx-sender u100) ``` ```clarity (map-insert scores tx-sender u200) ;; no-op ``` ```clarity (print (map-get? scores tx-sender)) ;; => (some u100) ``` ```clarity ;; map-delete (map-delete scores tx-sender) ``` ```clarity (print (map-get? scores tx-sender)) ;; => none ``` ```clarity ;; Unwrap a map value (define-map names (string-ascii 34) principal) ``` ```clarity (map-set names "Clarity" tx-sender) ``` ```clarity (print (unwrap-panic (map-get? names "Clarity"))) ;; => the principal ``` ```clarity (print (map-get? names "bogus")) ;; => none ``` -------------------------------- ### Define a Public 'hello [name]' Function Source: https://github.com/clarity-lang/book/blob/main/src/ch05-00-functions.md Defines a public function 'hello' that takes a single string parameter 'name' and returns a greeting string. This illustrates using string parameters and the 'concat' function. ```Clarity (define-public (hello (name (string-ascii 30))) (ok (concat "Hello " name)) ) (print (hello "Clarity")) ```