From 448f597b4ed4dd11dbc26a469757e1029c063fa4 Mon Sep 17 00:00:00 2001 From: Ryan Waits Date: Sun, 11 Aug 2024 01:16:59 -0500 Subject: [PATCH] some cleanup --- .../clarity/functions/define-constant.mdx | 20 ++++---- .../clarity/functions/define-data-var.mdx | 13 +++-- .../functions/define-fungible-token.mdx | 25 ++++----- .../stacks/clarity/functions/define-map.mdx | 27 +++++----- .../functions/define-non-fungible-token.mdx | 42 ++++++++------- .../clarity/functions/define-private.mdx | 14 +++-- .../clarity/functions/define-public.mdx | 51 ++++++++++++++----- .../clarity/functions/define-read-only.mdx | 9 ++-- .../stacks/clarity/functions/define-trait.mdx | 3 +- .../docs/stacks/clarity/functions/divide.mdx | 40 +++++++++------ .../stacks/clarity/functions/element-at.mdx | 30 ++++++----- content/docs/stacks/clarity/functions/err.mdx | 23 ++++++--- .../docs/stacks/clarity/functions/filter.mdx | 7 +-- .../docs/stacks/clarity/functions/fold.mdx | 3 +- .../clarity/functions/from-consensus-buff.mdx | 12 +++-- .../docs/stacks/clarity/functions/ft-burn.mdx | 16 +++--- .../clarity/functions/ft-get-balance.mdx | 26 ++++++---- .../clarity/functions/ft-get-supply.mdx | 28 ++++++---- .../docs/stacks/clarity/functions/ft-mint.mdx | 12 +++-- .../stacks/clarity/functions/ft-transfer.mdx | 16 ++++-- .../clarity/functions/get-block-info.mdx | 13 +++-- .../clarity/functions/get-burn-block-info.mdx | 10 ++-- content/docs/stacks/clarity/functions/get.mdx | 25 ++++----- .../functions/greater-than-or-equal.mdx | 37 +++++++++----- .../stacks/clarity/functions/greater-than.mdx | 22 ++++---- .../docs/stacks/clarity/functions/hash160.mdx | 3 +- content/docs/stacks/clarity/functions/if.mdx | 8 +-- .../clarity/functions/to-consensus-buff.mdx | 7 ++- 28 files changed, 322 insertions(+), 220 deletions(-) diff --git a/content/docs/stacks/clarity/functions/define-constant.mdx b/content/docs/stacks/clarity/functions/define-constant.mdx index e60004e3..4e983ada 100644 --- a/content/docs/stacks/clarity/functions/define-constant.mdx +++ b/content/docs/stacks/clarity/functions/define-constant.mdx @@ -44,26 +44,28 @@ Use `define-constant` when you need to: Let's implement a simple token contract using constants for configuration: ```clarity -(define-constant TOKEN_NAME "MyToken") -(define-constant TOKEN_SYMBOL "MTK") +(define-constant TOKEN_NAME "DOG-GO-TO-THE-MOON") +(define-constant TOKEN_SYMBOL "DOG") (define-constant TOKEN_DECIMALS u6) (define-constant TOKEN_SUPPLY u1000000000000) ;; 1 million tokens with 6 decimals -(define-fungible-token my-token TOKEN_SUPPLY) +(define-fungible-token DOG-GO-TO-THE-MOON TOKEN_SUPPLY) (define-read-only (get-name) - TOKEN_NAME) + TOKEN_NAME +) (define-read-only (get-symbol) - TOKEN_SYMBOL) + TOKEN_SYMBOL +) (define-read-only (get-decimals) - TOKEN_DECIMALS) + TOKEN_DECIMALS +) (define-read-only (get-balance (account principal)) - (ok (ft-get-balance my-token account))) - -;; Other token functions... + (ok (ft-get-balance DOG-GO-TO-THE-MOON account)) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/define-data-var.mdx b/content/docs/stacks/clarity/functions/define-data-var.mdx index 16881b31..d049c4d1 100644 --- a/content/docs/stacks/clarity/functions/define-data-var.mdx +++ b/content/docs/stacks/clarity/functions/define-data-var.mdx @@ -50,20 +50,23 @@ Let's implement a basic counter using `define-data-var`: (define-public (increment) (begin (var-set counter (+ (var-get counter) u1)) - (ok (var-get counter)))) + (ok (var-get counter)) + ) +) (define-public (decrement) (begin (asserts! (> (var-get counter) u0) (err u"Counter cannot be negative")) (var-set counter (- (var-get counter) u1)) - (ok (var-get counter)))) + (ok (var-get counter)) + ) +) (define-read-only (get-counter) - (ok (var-get counter))) + (ok (var-get counter)) +) ``` - - This example demonstrates: 1. Using `define-data-var` to create a mutable counter. 2. Implementing functions to increment and decrement the counter. diff --git a/content/docs/stacks/clarity/functions/define-fungible-token.mdx b/content/docs/stacks/clarity/functions/define-fungible-token.mdx index e81d34fb..98454680 100644 --- a/content/docs/stacks/clarity/functions/define-fungible-token.mdx +++ b/content/docs/stacks/clarity/functions/define-fungible-token.mdx @@ -44,28 +44,29 @@ Use `define-fungible-token` when you need to: Let's implement a basic fungible token with a fixed supply: ```clarity -(define-fungible-token my-token u1000000) +(define-fungible-token DOG-GO-TO-THE-MOON u1000000) + +(define-data-var tokenAdmin principal tx-sender) (define-public (transfer (amount uint) (sender principal) (recipient principal)) (begin (asserts! (is-eq tx-sender sender) (err u1)) - (ft-transfer? my-token amount sender recipient))) + (ft-transfer? DOG-GO-TO-THE-MOON amount sender recipient) + ) +) (define-read-only (get-balance (account principal)) - (ok (ft-get-balance my-token account))) + (ok (ft-get-balance DOG-GO-TO-THE-MOON account)) +) (define-public (mint (amount uint) (recipient principal)) (begin - (asserts! (is-eq tx-sender (var-get token-admin)) (err u3)) - (ft-mint? my-token amount recipient))) - -;; Initialize admin -(define-data-var token-admin principal tx-sender) + (asserts! (is-eq tx-sender (var-get tokenAdmin)) (err u3)) + (ft-mint? DOG-GO-TO-THE-MOON amount recipient) + ) +) ``` - - - This example demonstrates: 1. Using `define-fungible-token` to create a new token with a fixed supply of 1,000,000. 2. Implementing basic token operations like transfer and balance checking. @@ -73,7 +74,7 @@ This example demonstrates: ## Common Pitfalls -1. Forgetting that omitting the total supply parameter allows unlimited minting. +1. Forgetting that omitting the total supply parameter allows unlimited minting, if not handled manually. 2. Not implementing proper access controls for sensitive operations like minting. 3. Overlooking the need for additional functionality like burning or pausing. diff --git a/content/docs/stacks/clarity/functions/define-map.mdx b/content/docs/stacks/clarity/functions/define-map.mdx index 9ffff70f..72d6b040 100644 --- a/content/docs/stacks/clarity/functions/define-map.mdx +++ b/content/docs/stacks/clarity/functions/define-map.mdx @@ -45,33 +45,29 @@ Use `define-map` when you need to: Let's implement a basic user profile system using `define-map`: ```clarity -(define-map user-profiles - principal - { name: (string-ascii 50), age: uint, is-active: bool }) +(define-map UserProfiles principal { name: (string-ascii 50), age: uint, isActive: bool }) (define-public (set-profile (name (string-ascii 50)) (age uint)) - (ok (map-set user-profiles tx-sender { name: name, age: age, is-active: true }))) + (ok (map-set UserProfiles tx-sender { name: name, age: age, isActive: true })) +) (define-read-only (get-profile (user principal)) - (default-to - { name: "", age: u0, is-active: false } - (map-get? user-profiles user))) + (default-to { name: "", age: u0, isActive: false } (map-get? UserProfiles user)) +) (define-public (deactivate-profile) - (match (map-get? user-profiles tx-sender) - profile (ok (map-set user-profiles tx-sender - (merge profile { is-active: false }))) - (err u404))) + (match (map-get? UserProfiles tx-sender) profile + (ok (map-set UserProfiles tx-sender (merge profile { isActive: false }))) + (err u404) + ) +) ;; Usage -(set-profile "Alice" u30) +(set-profile "Ryan" u38) (get-profile tx-sender) (deactivate-profile) ``` - - - This example demonstrates: 1. Using `define-map` to create a user profile storage system. 2. Implementing functions to set, get, and update profile data. @@ -91,6 +87,7 @@ This example demonstrates: - `map-set`: Used to set or update a value in a map. - `map-delete`: Used to remove a key-value pair from a map. - `map-insert`: Used to insert a new key-value pair only if the key doesn't already exist. +- `merge`: Used to merge two maps, combining their key-value pairs. ## Conclusion diff --git a/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx b/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx index 85ae76f0..1e941a25 100644 --- a/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx +++ b/content/docs/stacks/clarity/functions/define-non-fungible-token.mdx @@ -44,29 +44,33 @@ Use `define-non-fungible-token` when you need to: Let's implement a basic digital art NFT system: ```clarity -(define-non-fungible-token digital-art uint) - -(define-data-var art-index uint u0) - -(define-public (mint-artwork (artist principal) (artwork-uri (string-utf8 256))) - (let ((token-id (var-get art-index))) - (try! (nft-mint? digital-art token-id artist)) - (var-set art-index (+ token-id u1)) - (ok token-id))) - -(define-read-only (get-owner (token-id uint)) - (ok (nft-get-owner? digital-art token-id))) - -(define-public (transfer (token-id uint) (sender principal) (recipient principal)) +(define-non-fungible-token SharkoBarko uint) + +(define-data-var index uint u0) + +(define-public (mint (who principal) (artwork-uri (string-utf8 256))) + (let + ( + (tokenId (var-get index)) + ) + (try! (nft-mint? SharkoBarko tokenId who)) + (var-set index (+ tokenId u1)) + (ok tokenId) + ) +) + +(define-read-only (get-owner (tokenId uint)) + (ok (nft-get-owner? SharkoBarko tokenId)) +) + +(define-public (transfer (tokenId uint) (sender principal) (recipient principal)) (begin (asserts! (is-eq tx-sender sender) (err u403)) - (nft-transfer? digital-art token-id sender recipient))) + (nft-transfer? SharkoBarko tokenId sender recipient) + ) +) ``` - - - - This example demonstrates: 1. Using `define-non-fungible-token` to create a new NFT class for digital artwork. 2. Implementing basic NFT operations like minting, checking ownership, and transferring. diff --git a/content/docs/stacks/clarity/functions/define-private.mdx b/content/docs/stacks/clarity/functions/define-private.mdx index 8e9e9cc9..b8f74915 100644 --- a/content/docs/stacks/clarity/functions/define-private.mdx +++ b/content/docs/stacks/clarity/functions/define-private.mdx @@ -47,14 +47,18 @@ Let's implement a private function for input validation: ```clarity (define-private (validate-amount (amount uint)) - (and (> amount u0) (<= amount u1000000))) + (and (> amount u0) (<= amount u1000000)) +) (define-public (transfer (recipient principal) (amount uint)) (if (validate-amount amount) - (begin - ;; Perform transfer logic here - (ok true)) - (err u1))) + (begin + ;; Perform transfer logic here + (ok true) + ) + (err u1) + ) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/define-public.mdx b/content/docs/stacks/clarity/functions/define-public.mdx index d869df55..ba2580df 100644 --- a/content/docs/stacks/clarity/functions/define-public.mdx +++ b/content/docs/stacks/clarity/functions/define-public.mdx @@ -42,25 +42,50 @@ Use `define-public` when you need to: - Handle potential errors and edge cases within the function. - Consider gas costs when designing public functions. -## Practical Example: Token Transfer Function +## Practical Examples -Let's implement a public function for transferring tokens: +### Example 1: Simple Counter + +Let's implement a simple counter that can be incremented by users: + +```clarity +(define-data-var counter int 0) + +(define-public (increment-counter) + (begin + (var-set counter (+ (var-get counter) 1)) + (ok (var-get counter)) + ) +) +``` + +This example demonstrates: +1. Using `define-public` to create a function that can be called externally. +2. Incrementing a counter and returning the new value. +3. Returning a response type to indicate success. + +### Example 2: Setting a Value + +Let's implement a function that sets a value if it meets certain conditions: ```clarity -(define-public (transfer (amount uint) (recipient principal)) - (let ((sender tx-sender)) - (if (>= (get-balance sender) amount) - (begin - (as-contract (transfer-tokens amount sender recipient)) - (ok true)) - (err u1)))) +(define-data-var storedValue uint u0) + +(define-public (set-value (value uint)) + (if (> value u0) + (begin + (var-set storedValue value) + (ok value) + ) + (err u1) + ) +) ``` This example demonstrates: 1. Using `define-public` to create a function that can be called externally. -2. Taking parameters for the amount and recipient of the transfer. -3. Implementing basic balance checking logic. -4. Returning a response type to indicate success or failure. +2. Setting a value only if it meets a condition. +3. Returning a response type to indicate success or failure. ## Common Pitfalls @@ -77,4 +102,4 @@ This example demonstrates: ## Conclusion -The `define-public` function is a fundamental building block for creating interactive and composable smart contracts in Clarity. By defining public functions, developers can create contracts that users and other contracts can interact with, enabling complex decentralized applications. However, it's crucial to design these functions with security, efficiency, and usability in mind. +The `define-public` function is a fundamental building block for creating interactive and composable smart contracts in Clarity. By defining public functions, developers can create contracts that users and other contracts can interact with, enabling complex decentralized applications. However, it's crucial to design these functions with security, efficiency, and usability in mind. \ No newline at end of file diff --git a/content/docs/stacks/clarity/functions/define-read-only.mdx b/content/docs/stacks/clarity/functions/define-read-only.mdx index 7d4784cb..b5844bf8 100644 --- a/content/docs/stacks/clarity/functions/define-read-only.mdx +++ b/content/docs/stacks/clarity/functions/define-read-only.mdx @@ -46,19 +46,16 @@ Use `define-read-only` when you need to: Let's implement a read-only function for checking token balances: ```clarity -(define-map balances principal uint) +(define-map Balances principal uint) (define-read-only (get-balance (account principal)) - (default-to u0 (map-get? balances account))) - -(define-read-only (get-total-supply) - (fold + (map-values balances) u0)) + (default-to u0 (map-get? Balances account)) +) ``` This example demonstrates: 1. Using `define-read-only` to create functions for querying token balances. 2. Implementing a getter function for individual account balances. -3. Creating a function to calculate the total token supply without modifying state. ## Common Pitfalls diff --git a/content/docs/stacks/clarity/functions/define-trait.mdx b/content/docs/stacks/clarity/functions/define-trait.mdx index 8f8207b5..749037e4 100644 --- a/content/docs/stacks/clarity/functions/define-trait.mdx +++ b/content/docs/stacks/clarity/functions/define-trait.mdx @@ -51,7 +51,8 @@ Let's define a simple trait for a token contract: (transfer? (principal principal uint) (response bool uint)) (get-balance (principal) (response uint uint)) (get-token-uri () (response (optional (string-utf8 256)) uint)) - )) + ) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/divide.mdx b/content/docs/stacks/clarity/functions/divide.mdx index 4f46cd1a..802f5cbb 100644 --- a/content/docs/stacks/clarity/functions/divide.mdx +++ b/content/docs/stacks/clarity/functions/divide.mdx @@ -49,34 +49,42 @@ Let's implement a simple token distribution contract that uses division to alloc (define-constant DISTRIBUTION_ROUNDS u10) ;; Define data variables -(define-map participant-shares principal uint) -(define-data-var current-round uint u0) -(define-data-var participants-count uint u0) +(define-map ParticipantShares principal uint) +(define-data-var currentRound uint u0) +(define-data-var participantsCount uint u0) ;; Function to register as a participant (define-public (register-participant) - (let ((current-participants (var-get participants-count))) - (asserts! (< current-participants DISTRIBUTION_ROUNDS) (err u1)) - (map-set participant-shares tx-sender u0) - (var-set participants-count (+ current-participants u1)) - (ok true))) + (let + ( + (currentParticipants (var-get participantsCount)) + ) + (asserts! (< currentParticipants DISTRIBUTION_ROUNDS) (err u1)) + (map-set ParticipantShares tx-sender u0) + (var-set participantsCount (+ currentParticipants u1)) + (ok true) + ) +) ;; Function to distribute tokens (define-public (distribute-tokens) (let ( - (current-participants (var-get participants-count)) - (tokens-per-participant (/ TOTAL_TOKENS current-participants)) + (currentParticipants (var-get participantsCount)) + (tokensPerParticipant (/ TOTAL_TOKENS currentParticipants)) ) - (asserts! (> current-participants u0) (err u2)) - (asserts! (< (var-get current-round) DISTRIBUTION_ROUNDS) (err u3)) - (map-set participant-shares tx-sender tokens-per-participant) - (var-set current-round (+ (var-get current-round) u1)) - (ok tokens-per-participant))) + (asserts! (> currentParticipants u0) (err u2)) + (asserts! (< (var-get currentRound) DISTRIBUTION_ROUNDS) (err u3)) + (map-set ParticipantShares tx-sender tokensPerParticipant) + (var-set currentRound (+ (var-get currentRound) u1)) + (ok tokensPerParticipant) + ) +) ;; Function to check participant's share (define-read-only (get-participant-share (participant principal)) - (default-to u0 (map-get? participant-shares participant))) + (default-to u0 (map-get? ParticipantShares participant)) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/element-at.mdx b/content/docs/stacks/clarity/functions/element-at.mdx index 1fe5c8d7..f5980910 100644 --- a/content/docs/stacks/clarity/functions/element-at.mdx +++ b/content/docs/stacks/clarity/functions/element-at.mdx @@ -44,18 +44,27 @@ Use `element-at?` when you need to: Let's implement a function that retrieves an item from a todo list: ```clarity -(define-data-var todo-list (list 10 (string-ascii 50)) (list)) +(define-data-var todoList (list 10 (string-ascii 50)) (list)) (define-public (add-todo (item (string-ascii 50))) - (let ((current-list (var-get todo-list))) - (if (< (len current-list) u10) - (ok (var-set todo-list (append current-list item))) - (err u1)))) + (let + ( + (currentList (var-get todoList)) + (newList (as-max-len? (append currentList item) u10)) + ) + (match newList + newListValue (ok (var-set todoList newListValue)) + (err u1) + ) + ) +) (define-read-only (get-todo (index uint)) - (match (element-at? (var-get todo-list) index) - item (ok item) - (err u404))) + (match (element-at? (var-get todoList) index) item + (ok item) + (err u404) + ) +) ;; Usage (add-todo "Buy milk") @@ -64,9 +73,6 @@ Let's implement a function that retrieves an item from a todo list: (get-todo u5) ;; Returns (err u404) ``` - - - This example demonstrates: 1. Using `element-at?` to retrieve an item from a list stored in a data variable. 2. Handling the optional return value with `match` to provide meaningful responses. @@ -101,4 +107,4 @@ When migrating from Clarity 1 to newer versions, replace `element-at` with `elem ## Conclusion -The `element-at?` function is a safer and more flexible way to access list elements in Clarity smart contracts compared to its predecessor. By returning an optional value, it allows developers to handle out-of-bounds access gracefully, leading to more robust and error-resistant code. When working with lists in Clarity, `element-at?` is an essential tool for accessing specific elements while maintaining the integrity and safety of your contract operations. +The `element-at?` function is a safer and more flexible way to access list elements in Clarity smart contracts compared to its predecessor. By returning an optional value, it allows developers to handle out-of-bounds access gracefully, leading to more robust and error-resistant code. When working with lists in Clarity, `element-at?` is an essential tool for accessing specific elements while maintaining the integrity and safety of your contract operations. \ No newline at end of file diff --git a/content/docs/stacks/clarity/functions/err.mdx b/content/docs/stacks/clarity/functions/err.mdx index b4c4e8d9..7ac2220f 100644 --- a/content/docs/stacks/clarity/functions/err.mdx +++ b/content/docs/stacks/clarity/functions/err.mdx @@ -42,16 +42,23 @@ Use `err` when you need to: Let's implement a simple token transfer function with error handling: ```clarity -(define-map balances principal uint) +(define-map Balances principal uint) (define-public (transfer (amount uint) (recipient principal)) - (let ((sender-balance (default-to u0 (map-get? balances tx-sender)))) - (if (>= sender-balance amount) - (begin - (map-set balances tx-sender (- sender-balance amount)) - (map-set balances recipient (+ (default-to u0 (map-get? balances recipient)) amount)) - (ok true)) - (err u1)))) ;; Error code 1 for insufficient balance + (let + ( + (senderBalance (default-to u0 (map-get? Balances tx-sender))) + ) + (if (>= senderBalance amount) + (begin + (map-set Balances tx-sender (- senderBalance amount)) + (map-set Balances recipient (+ (default-to u0 (map-get? Balances recipient)) amount)) + (ok true) + ) + (err u1) + ) + ) +) ;; Usage (transfer u100 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) ;; Returns (err u1) if balance is insufficient diff --git a/content/docs/stacks/clarity/functions/filter.mdx b/content/docs/stacks/clarity/functions/filter.mdx index db1347a3..070681c1 100644 --- a/content/docs/stacks/clarity/functions/filter.mdx +++ b/content/docs/stacks/clarity/functions/filter.mdx @@ -45,16 +45,17 @@ Let's implement a function that filters even numbers from a list: ```clarity (define-private (is-even (num int)) - (is-eq (mod num 2) 0)) + (is-eq (mod num 2) 0) +) (define-read-only (get-even-numbers (numbers (list 10 int))) - (filter is-even numbers)) + (filter is-even numbers) +) ;; Usage (get-even-numbers (list 1 2 3 4 5 6 7 8 9 10)) ;; Returns (2 4 6 8 10) ``` - This example demonstrates: 1. Defining a private helper function `is-even` to check if a number is even. 2. Using `filter` with the `is-even` function to create a new list of even numbers. diff --git a/content/docs/stacks/clarity/functions/fold.mdx b/content/docs/stacks/clarity/functions/fold.mdx index e8c0cbd3..28eb679e 100644 --- a/content/docs/stacks/clarity/functions/fold.mdx +++ b/content/docs/stacks/clarity/functions/fold.mdx @@ -46,7 +46,8 @@ Let's implement a function that sums all numbers in a list: ```clarity (define-read-only (sum-list (numbers (list 10 uint))) - (fold + numbers u0)) + (fold + numbers u0) +) ;; Usage (sum-list (list u1 u2 u3 u4 u5)) ;; Returns u15 diff --git a/content/docs/stacks/clarity/functions/from-consensus-buff.mdx b/content/docs/stacks/clarity/functions/from-consensus-buff.mdx index 53ac852a..cf6809ba 100644 --- a/content/docs/stacks/clarity/functions/from-consensus-buff.mdx +++ b/content/docs/stacks/clarity/functions/from-consensus-buff.mdx @@ -44,14 +44,16 @@ Use `from-consensus-buff?` when you need to: Let's implement a function that deserializes a buffer into a tuple: ```clarity -(define-read-only (deserialize-user-data (serialized-data (buff 128))) - (match (from-consensus-buff? { name: (string-ascii 50), age: uint } serialized-data) +(define-read-only (deserialize-user-data (serializedData (buff 128))) + (match (from-consensus-buff? { name: (string-ascii 50), age: uint } serializedData) success success - failure (err u1))) + (err u1) + ) +) ;; Usage -(deserialize-user-data 0x0c00000002046e616d65110000003248656c6c6f20576f726c64000000000000000000000000000000000000000000000000000000000000000000036167650100000000000000000000000000000018) -;; Returns (ok (tuple (name "Hello World") (age u24))) +(deserialize-user-data 0x0c00000002036167650100000000000000000000000000000005046e616d650d0000000a48617270657220446f67) +;; Returns (ok (tuple (name "Harper Dog") (age u5))) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/ft-burn.mdx b/content/docs/stacks/clarity/functions/ft-burn.mdx index ab26c572..1f943f80 100644 --- a/content/docs/stacks/clarity/functions/ft-burn.mdx +++ b/content/docs/stacks/clarity/functions/ft-burn.mdx @@ -45,18 +45,20 @@ Use `ft-burn?` when you need to: Let's implement a simple token burning function: ```clarity -(define-fungible-token my-token) +(define-fungible-token cBtc) + +(define-data-var tokenAdmin principal tx-sender) (define-public (burn-tokens (amount uint)) - (ft-burn? my-token amount tx-sender)) + (ft-burn? cBtc amount tx-sender) +) (define-public (burn-tokens-from (amount uint) (owner principal)) (begin - (asserts! (is-eq tx-sender (var-get token-admin)) (err u3)) - (ft-burn? my-token amount owner))) - -;; Initialize admin -(define-data-var token-admin principal tx-sender) + (asserts! (is-eq tx-sender (var-get tokenAdmin)) (err u3)) + (ft-burn? cBtc amount owner) + ) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/ft-get-balance.mdx b/content/docs/stacks/clarity/functions/ft-get-balance.mdx index 7df38f77..b396a8ee 100644 --- a/content/docs/stacks/clarity/functions/ft-get-balance.mdx +++ b/content/docs/stacks/clarity/functions/ft-get-balance.mdx @@ -44,18 +44,24 @@ Use `ft-get-balance` when you need to: Let's implement a function that checks balance before transferring tokens: ```clarity -(define-fungible-token my-token) - -(define-public (transfer-if-sufficient (amount uint) (recipient principal)) - (let ((sender-balance (ft-get-balance my-token tx-sender))) - (if (>= sender-balance amount) - (ft-transfer? my-token amount tx-sender recipient) - (err u1)))) +(define-fungible-token cBtc) + +(define-public (transfer (amount uint) (recipient principal)) + (let + ( + (senderBalance (ft-get-balance cBtc tx-sender)) + ) + (if (>= senderBalance amount) + (ft-transfer? cBtc amount tx-sender recipient) + (err u1) + ) + ) +) ;; Usage -(ft-mint? my-token u100 tx-sender) -(transfer-if-sufficient u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) -(ft-get-balance my-token tx-sender) ;; Returns u50 +(ft-mint? cBtc u100 tx-sender) +(transfer u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) +(ft-get-balance cBtc tx-sender) ;; Returns u50 ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/ft-get-supply.mdx b/content/docs/stacks/clarity/functions/ft-get-supply.mdx index a52ee77d..6c134e69 100644 --- a/content/docs/stacks/clarity/functions/ft-get-supply.mdx +++ b/content/docs/stacks/clarity/functions/ft-get-supply.mdx @@ -43,19 +43,25 @@ Use `ft-get-supply` when you need to: Let's implement a function that mints tokens only if it doesn't exceed a certain supply cap: ```clarity -(define-fungible-token my-token) -(define-constant max-supply u1000000) - -(define-public (mint-if-under-cap (amount uint) (recipient principal)) - (let ((current-supply (ft-get-supply my-token))) - (if (<= (+ current-supply amount) max-supply) - (ft-mint? my-token amount recipient) - (err u1)))) +(define-fungible-token cBtc) +(define-constant MAX_SUPPLY u1000000) + +(define-public (mint (amount uint) (recipient principal)) + (let + ( + (currentSupply (ft-get-supply cBtc)) + ) + (if (<= (+ currentSupply amount) MAX_SUPPLY) + (ft-mint? cBtc amount recipient) + (err u1) + ) + ) +) ;; Usage -(mint-if-under-cap u500000 tx-sender) ;; Returns (ok true) -(ft-get-supply my-token) ;; Returns u500000 -(mint-if-under-cap u600000 tx-sender) ;; Returns (err u1) +(mint u500000 tx-sender) ;; Returns (ok true) +(ft-get-supply cBtc) ;; Returns u500000 +(mint u600000 tx-sender) ;; Returns (err u1) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/ft-mint.mdx b/content/docs/stacks/clarity/functions/ft-mint.mdx index 2702a070..3b081674 100644 --- a/content/docs/stacks/clarity/functions/ft-mint.mdx +++ b/content/docs/stacks/clarity/functions/ft-mint.mdx @@ -45,17 +45,19 @@ Use `ft-mint?` when you need to: Let's implement a simple reward system that mints tokens: ```clarity -(define-fungible-token reward-token) +(define-fungible-token RewardToken) -(define-constant contract-owner tx-sender) +(define-constant CONTRACT_OWNER tx-sender) (define-public (mint-reward (amount uint) (recipient principal)) (begin - (asserts! (is-eq tx-sender contract-owner) (err u403)) - (ft-mint? reward-token amount recipient))) + (asserts! (is-eq tx-sender CONTRACT_OWNER) (err u403)) + (ft-mint? RewardToken amount recipient) + ) +) ;; Usage -(mint-reward u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) if called by contract-owner +(mint-reward u100 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) if called by CONTRACT_OWNER ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/ft-transfer.mdx b/content/docs/stacks/clarity/functions/ft-transfer.mdx index d7f76f8c..b039d9da 100644 --- a/content/docs/stacks/clarity/functions/ft-transfer.mdx +++ b/content/docs/stacks/clarity/functions/ft-transfer.mdx @@ -47,18 +47,24 @@ Use `ft-transfer?` when you need to: Let's implement a public function for transferring tokens with some basic checks: ```clarity -(define-fungible-token my-token) +(define-fungible-token cBtc) (define-public (transfer-tokens (amount uint) (recipient principal)) - (let ((sender tx-sender)) + (let + ( + (sender tx-sender) + ) (asserts! (not (is-eq sender recipient)) (err u2)) (asserts! (> amount u0) (err u3)) - (match (ft-transfer? my-token amount sender recipient) + (match (ft-transfer? cBtc amount sender recipient) success (ok success) - error (err error)))) + error (err error) + ) + ) +) ;; Usage -(ft-mint? my-token u100 tx-sender) +(ft-mint? cBtc u100 tx-sender) (transfer-tokens u50 'SPAXYA5XS51713FDTQ8H94EJ4V579CXMTRNBZKSF) ;; Returns (ok true) ``` diff --git a/content/docs/stacks/clarity/functions/get-block-info.mdx b/content/docs/stacks/clarity/functions/get-block-info.mdx index a3c67436..0b88d41c 100644 --- a/content/docs/stacks/clarity/functions/get-block-info.mdx +++ b/content/docs/stacks/clarity/functions/get-block-info.mdx @@ -44,18 +44,17 @@ Use `get-block-info?` when you need to: Let's implement a function that checks if a given block was mined after a certain time: ```clarity -(define-read-only (block-after-time? (block-height uint) (target-time uint)) - (match (get-block-info? time block-height) - time (> time target-time) - false)) +(define-read-only (block-after-time? (blockHeight uint) (targetTime uint)) + (match (get-block-info? time blockHeight) time + (> time targetTime) + false + ) +) ;; Usage (block-after-time? u100 u1600000000) ;; Returns true if block 100 was mined after Unix timestamp 1600000000 ``` - - - This example demonstrates: 1. Using `get-block-info?` to retrieve the `time` property of a block. 2. Handling the optional return value with `match`. diff --git a/content/docs/stacks/clarity/functions/get-burn-block-info.mdx b/content/docs/stacks/clarity/functions/get-burn-block-info.mdx index 063720ab..cd92f677 100644 --- a/content/docs/stacks/clarity/functions/get-burn-block-info.mdx +++ b/content/docs/stacks/clarity/functions/get-burn-block-info.mdx @@ -44,10 +44,12 @@ Use `get-burn-block-info?` when you need to: Let's implement a function that verifies if a given Bitcoin block hash matches a specific height: ```clarity -(define-read-only (verify-btc-block-hash (height uint) (expected-hash (buff 32))) - (match (get-burn-block-info? header-hash height) - hash (is-eq hash expected-hash) - false)) +(define-read-only (verify-btc-block-hash (height uint) (expectedHash (buff 32))) + (match (get-burn-block-info? header-hash height) hash + (is-eq hash expectedHash) + false + ) +) ;; Usage (verify-btc-block-hash u700000 0x00000000000000000009a11b3972c8e532e964e262c196556bd958b7fd0c55c3) diff --git a/content/docs/stacks/clarity/functions/get.mdx b/content/docs/stacks/clarity/functions/get.mdx index 9db1e683..a7e82fbf 100644 --- a/content/docs/stacks/clarity/functions/get.mdx +++ b/content/docs/stacks/clarity/functions/get.mdx @@ -44,20 +44,25 @@ Use `get` when you need to: Let's implement a simple user profile system using tuples and the `get` function: ```clarity -(define-map user-profiles principal { name: (string-ascii 50), age: uint }) +(define-map UserProfiles { userId: principal } { name: (string-ascii 50), age: uint }) (define-public (set-profile (name (string-ascii 50)) (age uint)) - (ok (map-set user-profiles tx-sender { name: name, age: age }))) + (ok (map-set UserProfiles { userId: tx-sender } { name: name, age: age })) +) (define-read-only (get-profile-name (user principal)) - (match (map-get? user-profiles user) - profile (ok (get name profile)) - (err u404))) + (match (map-get? UserProfiles { userId: user }) profile + (ok (get name profile)) + (err u404) + ) +) (define-read-only (get-profile-age (user principal)) - (match (map-get? user-profiles user) - profile (ok (get age profile)) - (err u404))) + (match (map-get? UserProfiles { userId: user }) profile + (ok (get age profile)) + (err u404) + ) +) ;; Usage (set-profile "Alice" u30) @@ -65,10 +70,6 @@ Let's implement a simple user profile system using tuples and the `get` function (get-profile-age tx-sender) ;; Returns (ok u30) ``` - - - - This example demonstrates: 1. Using `get` to retrieve specific fields from a tuple stored in a map. 2. Implementing getter functions that use `get` to access tuple data. diff --git a/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx b/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx index 39f427e1..d797c9dd 100644 --- a/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx +++ b/content/docs/stacks/clarity/functions/greater-than-or-equal.mdx @@ -52,36 +52,45 @@ Let's implement a simple token unlock schedule that uses the greater than or equ (define-constant TOTAL_UNLOCKS u10) ;; 10 total unlocks ;; Define data variables -(define-data-var start-block uint u0) -(define-data-var unlocks-claimed uint u0) +(define-data-var startBlock uint u0) +(define-data-var unlocksClaimed uint u0) ;; Function to start the unlock schedule (define-public (start-unlock-schedule) (begin - (asserts! (is-eq (var-get start-block) u0) (err u1)) - (var-set start-block block-height) - (ok true))) + (asserts! (is-eq (var-get startBlock) u0) (err u1)) + (var-set startBlock block-height) + (ok true) + ) +) ;; Function to calculate claimable tokens (define-read-only (get-claimable-tokens) (let ( - (elapsed-blocks (- block-height (var-get start-block))) - (unlocks-due (/ elapsed-blocks UNLOCK_INTERVAL)) + (elapsedBlocks (- block-height (var-get startBlock))) + (unlocksDue (/ elapsedBlocks UNLOCK_INTERVAL)) ) - (if (>= unlocks-due TOTAL_UNLOCKS) - (* UNLOCK_AMOUNT (- TOTAL_UNLOCKS (var-get unlocks-claimed))) - (* UNLOCK_AMOUNT (- unlocks-due (var-get unlocks-claimed)))))) + (if (>= unlocksDue TOTAL_UNLOCKS) + (* UNLOCK_AMOUNT (- TOTAL_UNLOCKS (var-get unlocksClaimed))) + (* UNLOCK_AMOUNT (- unlocksDue (var-get unlocksClaimed))) + ) + ) +) ;; Function to claim tokens (define-public (claim-tokens) (let - ((claimable-amount (get-claimable-tokens))) - (asserts! (> claimable-amount u0) (err u2)) - (var-set unlocks-claimed (+ (var-get unlocks-claimed) (/ claimable-amount UNLOCK_AMOUNT))) + ( + (claimableAmount (get-claimable-tokens)) + ) + (asserts! (> claimableAmount u0) (err u2)) + (var-set unlocksClaimed (+ (var-get unlocksClaimed) (/ claimableAmount UNLOCK_AMOUNT))) ;; Here you would typically transfer tokens ;; For simplicity, we're just returning the claimed amount - (ok claimable-amount))) + (ok claimableAmount) + ) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/greater-than.mdx b/content/docs/stacks/clarity/functions/greater-than.mdx index 7c762468..689c54b2 100644 --- a/content/docs/stacks/clarity/functions/greater-than.mdx +++ b/content/docs/stacks/clarity/functions/greater-than.mdx @@ -49,25 +49,29 @@ Let's implement a simple token sale contract that uses the greater than function (define-constant TOKEN_PRICE u50000) ;; 0.0005 STX per token ;; Define data variables -(define-data-var tokens-sold uint u0) +(define-data-var tokensSold uint u0) ;; Function to purchase tokens (define-public (purchase-tokens (amount uint)) - (let ( - (tokens-to-mint (/ amount TOKEN_PRICE)) - (payment amount) - ) + (let + ( + (tokensToMint (/ amount TOKEN_PRICE)) + (payment amount) + ) ;; Check if the purchase amount is greater than the minimum (asserts! (> payment MIN_PURCHASE) (err u1)) ;; Perform the token purchase (try! (stx-transfer? payment tx-sender (as-contract tx-sender))) - (var-set tokens-sold (+ (var-get tokens-sold) tokens-to-mint)) + (var-set tokensSold (+ (var-get tokensSold) tokensToMint)) ;; Here you would typically mint or transfer tokens to the buyer - (ok tokens-to-mint))) + (ok tokensToMint) + ) +) ;; Function to check total tokens sold -(define-read-only (get-tokens-sold) - (ok (var-get tokens-sold))) +(define-read-only (get-tokensSold) + (ok (var-get tokensSold)) +) ``` This example demonstrates: diff --git a/content/docs/stacks/clarity/functions/hash160.mdx b/content/docs/stacks/clarity/functions/hash160.mdx index 8707282b..ef3c7901 100644 --- a/content/docs/stacks/clarity/functions/hash160.mdx +++ b/content/docs/stacks/clarity/functions/hash160.mdx @@ -43,7 +43,8 @@ Let's implement a function that generates a simple hash-based identifier: ```clarity (define-read-only (generate-identifier (input (buff 32))) - (hash160 input)) + (hash160 input) +) ;; Usage (generate-identifier 0x000000000000000000000000000000000000000000000000000000000000000a) diff --git a/content/docs/stacks/clarity/functions/if.mdx b/content/docs/stacks/clarity/functions/if.mdx index 40e6fe5e..16dc1122 100644 --- a/content/docs/stacks/clarity/functions/if.mdx +++ b/content/docs/stacks/clarity/functions/if.mdx @@ -43,17 +43,17 @@ Use `if` when you need to: ## Practical Example: Conditional Token Transfer ```clarity -(define-map userBalances { userId: principal } { balance: uint }) +(define-map UserBalances { userId: principal } { balance: uint }) (define-public (transfer-tokens (amount uint) (recipient principal)) (let ( - (senderBalance (default-to u0 (map-get? userBalances { userId: tx-sender }))) + (senderBalance (default-to u0 (map-get? UserBalances { userId: tx-sender }))) ) (if (>= senderBalance amount) (begin - (map-set userBalances { userId: tx-sender } { balance: (- senderBalance amount) }) - (map-set userBalances { userId: recipient } { balance: (+ (default-to u0 (map-get? userBalances { userId: recipient })) amount) }) + (map-set UserBalances { userId: tx-sender } { balance: (- senderBalance amount) }) + (map-set UserBalances { userId: recipient } { balance: (+ (default-to u0 (map-get? UserBalances { userId: recipient })) amount) }) (ok true) ) (err u1) diff --git a/content/docs/stacks/clarity/functions/to-consensus-buff.mdx b/content/docs/stacks/clarity/functions/to-consensus-buff.mdx index c0afdb58..15dbaf46 100644 --- a/content/docs/stacks/clarity/functions/to-consensus-buff.mdx +++ b/content/docs/stacks/clarity/functions/to-consensus-buff.mdx @@ -42,13 +42,18 @@ Use `to-consensus-buff?` when you need to: Let's implement a function that serializes an integer value into a buffer: ```clarity -(define-public (serialize-int (input int)) +(define-read-only (serialize-int (input int)) + (to-consensus-buff? input) +) + +(define-read-only (serialize-tuple (input (tuple (name (string-ascii 50)) (age uint)))) (to-consensus-buff? input) ) ;; Usage (serialize-int 42) ;; Returns (some 0x000000000000000000000000000000000000000000000000000000000000002a) (serialize-int -1) ;; Returns none (since negative integers cannot be serialized) +(serialize-tuple (tuple (name "Harper Dog") (age u5))) ;; Returns (some 0x0c00000002036167650100000000000000000000000000000005046e616d650d0000000a48617270657220446f67) ``` This example demonstrates: