Functions reference

Complete reference for all Clarity functions organized by category, from arithmetic operations to token management.


Clarity provides a comprehensive set of built-in functions for smart contract development. These functions cover everything from basic arithmetic to complex token operations and blockchain interactions.

Arithmetic operations

+ (add)

+ performs addition on a variable number of integer inputs.

Signature

(+ i1 i2...)

Parameters

NameTypeDescription
i1, i2, ...int or uintTwo or more integers to add
(+ 1 2 3) ;; Returns 6
(+ u10 u20) ;; Returns u30
;; Counter example
(define-data-var counter int 0)
(define-public (increment (amount int))
(begin
(var-set counter (+ (var-get counter) amount))
(ok (var-get counter))))

- (subtract)

- performs subtraction on a variable number of integer inputs.

Signature

(- i1 i2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...int or uintTwo or more integers to subtract
(- 10 3) ;; Returns 7
(- 100 20 10) ;; Returns 70
(- u50 u30) ;; Returns u20
;; Decrease balance
(define-public (withdraw (amount uint))
(let ((balance (var-get user-balance)))
(asserts! (>= balance amount) (err u1))
(var-set user-balance (- balance amount))
(ok amount)))

* (multiply)

* performs multiplication on a variable number of integer inputs.

Signature

(* i1 i2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...int or uintTwo or more integers to multiply
(* 3 4) ;; Returns 12
(* 2 3 4) ;; Returns 24
(* u5 u10) ;; Returns u50
;; Calculate percentage
(define-read-only (calculate-fee (amount uint))
(/ (* amount u3) u100)) ;; 3% fee

/ (divide)

/ performs integer division on a variable number of integer inputs.

Signature

(/ i1 i2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...int or uintTwo or more integers to divide
(/ 10 2) ;; Returns 5
(/ 100 10 2) ;; Returns 5
(/ u60 u3) ;; Returns u20
;; Calculate average
(define-read-only (average (a uint) (b uint))
(/ (+ a b) u2))

mod

mod returns the remainder of integer division.

Signature

(mod i1 i2)

Parameters

NameTypeDescription
i1int or uintDividend
i2int or uintDivisor
(mod 10 3) ;; Returns 1
(mod u17 u5) ;; Returns u2
;; Check if even
(define-read-only (is-even (n uint))
(is-eq (mod n u2) u0))

pow

pow raises a number to a power.

Signature

(pow i1 i2)

Parameters

NameTypeDescription
i1int or uintBase
i2int or uintExponent
(pow 2 3) ;; Returns 8
(pow u10 u2) ;; Returns u100
;; Calculate compound interest
(define-read-only (compound-interest (principal uint) (rate uint) (periods uint))
(let ((rate-factor (+ u100 rate)))
(/ (* principal (pow rate-factor periods)) (pow u100 periods))))

sqrti

sqrti returns the integer square root of a number.

Signature

(sqrti n)

Parameters

NameTypeDescription
nint or uintNumber to find square root of
(sqrti u16) ;; Returns u4
(sqrti u100) ;; Returns u10
(sqrti 25) ;; Returns 5
;; Calculate distance (simplified)
(define-read-only (distance (x uint) (y uint))
(sqrti (+ (* x x) (* y y))))

log2

log2 returns the base-2 logarithm of a number.

Signature

(log2 n)

Parameters

NameTypeDescription
nint or uintNumber to find logarithm of
(log2 u8) ;; Returns u3
(log2 u256) ;; Returns u8
;; Calculate bit position
(define-read-only (highest-bit-position (n uint))
(if (> n u0)
(some (log2 n))
none))

< (less-than)

< returns true if the first argument is less than the second.

Signature

(< i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(< 5 10) ;; Returns true
(< u100 u50) ;; Returns false
;; Validate minimum
(define-public (deposit (amount uint))
(begin
(asserts! (< u0 amount) (err u1))
(ok amount)))

> (greater-than)

> returns true if the first argument is greater than the second.

Signature

(> i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(> 10 5) ;; Returns true
(> u50 u100) ;; Returns false
;; Check maximum
(define-read-only (exceeds-limit (value uint))
(> value u1000000))

<= (less-than-or-equal)

<= returns true if the first argument is less than or equal to the second.

Signature

(<= i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(<= 5 10) ;; Returns true
(<= 10 10) ;; Returns true
(<= u100 u50) ;; Returns false
;; Validate range
(define-read-only (is-valid-percentage (value uint))
(and (<= u0 value) (<= value u100)))

>= (greater-than-or-equal)

>= returns true if the first argument is greater than or equal to the second.

Signature

(>= i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(>= 10 5) ;; Returns true
(>= 10 10) ;; Returns true
(>= u50 u100) ;; Returns false
;; Check balance
(define-public (can-afford (price uint))
(ok (>= (stx-get-balance tx-sender) price)))

Logical operations

and

and returns true if all arguments are true.

Signature

(and b1 b2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...boolBoolean values to evaluate
(and true true) ;; Returns true
(and true false) ;; Returns false
(and true true true) ;; Returns true
;; Multiple conditions
(define-read-only (is-valid-transfer (amount uint) (recipient principal))
(and
(> amount u0)
(not (is-eq recipient tx-sender))
(<= amount (get-balance tx-sender))))

or

or returns true if at least one argument is true.

Signature

(or b1 b2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...boolBoolean values to evaluate
(or true false) ;; Returns true
(or false false) ;; Returns false
(or false false true) ;; Returns true
;; Check permissions
(define-read-only (can-access (user principal))
(or
(is-eq user contract-owner)
(default-to false (map-get? admins user))
(var-get public-access)))

not

not returns the logical negation of a boolean value.

Signature

(not b)

Parameters

NameTypeDescription
bboolBoolean value to negate
(not true) ;; Returns false
(not false) ;; Returns true
;; Check if not owner
(define-read-only (is-not-owner (user principal))
(not (is-eq user contract-owner)))

xor

xor returns true if exactly one of two arguments is true.

Signature

(xor b1 b2)

Parameters

NameTypeDescription
b1boolFirst boolean value
b2boolSecond boolean value
(xor true false) ;; Returns true
(xor true true) ;; Returns false
(xor false false) ;; Returns false
;; Exclusive access
(define-read-only (has-exclusive-role (is-admin bool) (is-moderator bool))
(xor is-admin is-moderator))

is-eq

is-eq returns true if all arguments are equal.

Signature

(is-eq v1 v2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...anyValues to compare for equality
(is-eq 5 5) ;; Returns true
(is-eq "hello" "hello") ;; Returns true
(is-eq u10 u20) ;; Returns false
(is-eq 1 1 1) ;; Returns true
;; Check owner
(define-public (admin-only)
(begin
(asserts! (is-eq tx-sender contract-owner) (err u401))
(ok true)))

Sequence & string operations

list

list constructs a list from provided values.

Signature

(list v1 v2...)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...anyValues to include in the list
(list 1 2 3) ;; Returns (1 2 3)
(list true false true) ;; Returns (true false true)
;; Create address list
(define-data-var admins (list 5 principal)
(list 'SP1234... 'SP5678...))

append

append adds an element to the end of a list.

Signature

(append list-expr element)

Parameters

NameTypeDescription
list-exprlistList to append to
elementanyElement to add
(append (list 1 2) 3) ;; Returns (1 2 3)
(append (list) u10) ;; Returns (u10)
;; Add to list
(define-public (add-member (member principal))
(let ((current-list (var-get members)))
(match (as-max-len? (append current-list member) u100)
new-list (begin
(var-set members new-list)
(ok true))
(err u1))))

concat

concat joins two sequences of the same type.

Signature

(concat sequence1 sequence2)

Parameters

NameTypeDescription
sequence1sequenceFirst sequence
sequence2sequenceSecond sequence
(concat "Hello " "World") ;; Returns "Hello World"
(concat 0x0102 0x0304) ;; Returns 0x01020304
(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4)
;; Combine strings
(define-read-only (format-message (prefix (string-ascii 10)) (msg (string-ascii 50)))
(concat prefix msg))

len

len returns the length of a sequence.

Signature

(len sequence)

Parameters

NameTypeDescription
sequencesequenceSequence to measure
(len "Hello") ;; Returns u5
(len (list 1 2 3)) ;; Returns u3
(len 0x0102) ;; Returns u2
;; Validate length
(define-public (set-name (name (string-ascii 50)))
(begin
(asserts! (> (len name) u0) (err u1))
(asserts! (<= (len name) u20) (err u2))
(ok name)))

element-at

element-at retrieves an element at a specific index.

Signature

(element-at sequence index)

Parameters

NameTypeDescription
sequencesequenceSequence to access
indexuintZero-based index
(element-at "Hello" u1) ;; Returns (some "e")
(element-at (list 10 20 30) u2) ;; Returns (some 30)
(element-at (list 1 2) u5) ;; Returns none
;; Get from list safely
(define-read-only (get-member-at (index uint))
(element-at (var-get members) index))

index-of

index-of finds the first occurrence of an element in a sequence.

Signature

(index-of sequence element)

Parameters

NameTypeDescription
sequencesequenceSequence to search
elementanyElement to find
(index-of "Hello" "l") ;; Returns (some u2)
(index-of (list 1 2 3 2) 2) ;; Returns (some u1)
(index-of (list 1 2 3) 5) ;; Returns none
;; Check membership
(define-read-only (is-member (user principal))
(is-some (index-of (var-get members) user)))

slice

slice extracts a subsequence from a sequence.

Signature

(slice sequence left-position right-position)

Parameters

NameTypeDescription
sequencesequenceSequence to slice
left-positionuintStarting index (inclusive)
right-positionuintEnding index (exclusive)
(slice "Hello World" u0 u5) ;; Returns (some "Hello")
(slice (list 1 2 3 4 5) u1 u4) ;; Returns (some (2 3 4))
;; Extract substring
(define-read-only (get-prefix (text (string-ascii 100)) (length uint))
(slice text u0 length))

replace-at

replace-at replaces an element at a specific index.

Signature

(replace-at sequence index new-element)

Parameters

NameTypeDescription
sequencesequenceSequence to modify
indexuintIndex to replace at
new-elementanyNew element
(replace-at "Hello" u1 "a") ;; Returns (some "Hallo")
(replace-at (list 1 2 3) u1 5) ;; Returns (some (1 5 3))
;; Update list element
(define-public (update-member (index uint) (new-member principal))
(match (replace-at (var-get members) index new-member)
new-list (begin
(var-set members new-list)
(ok true))
(err u404)))

map

map applies a function to each element of a list.

Signature

(map func list1 list2...)

Parameters

NameTypeDescription
funcfunctionFunction to apply
[object Object],, ,[object Object],, ...listLists to map over
(map + (list 1 2 3) (list 10 20 30)) ;; Returns (11 22 33)
;; Double all values
(define-private (double (x uint))
(* x u2))
(define-read-only (double-all (numbers (list 10 uint)))
(map double numbers))

filter

filter returns elements that satisfy a predicate.

Signature

(filter func list)

Parameters

NameTypeDescription
funcfunctionPredicate function
listlistList to filter
(define-private (is-even (x uint))
(is-eq (mod x u2) u0))
(filter is-even (list u1 u2 u3 u4)) ;; Returns (u2 u4)
;; Filter active users
(define-read-only (get-active-users)
(filter is-active (var-get all-users)))

fold

fold reduces a list to a single value.

Signature

(fold func list initial-value)

Parameters

NameTypeDescription
funcfunctionReducer function
listlistList to reduce
initial-valueanyStarting value
(fold + (list u1 u2 u3 u4) u0) ;; Returns u10
;; Sum balances
(define-private (add-balance (user principal) (total uint))
(+ total (default-to u0 (map-get? balances user))))
(define-read-only (get-total-balance)
(fold add-balance (var-get users) u0))

int-to-ascii

int-to-ascii converts an integer to its ASCII string representation.

Signature

(int-to-ascii value)

Parameters

NameTypeDescription
valueint or uintInteger to convert
(int-to-ascii 123) ;; Returns "123"
(int-to-ascii u456) ;; Returns "456"
;; Format ID
(define-read-only (format-id (id uint))
(concat "ID-" (int-to-ascii id)))

int-to-utf8

int-to-utf8 converts an integer to its UTF-8 string representation.

Signature

(int-to-utf8 value)

Parameters

NameTypeDescription
valueint or uintInteger to convert
(int-to-utf8 789) ;; Returns u"789"
(int-to-utf8 u100) ;; Returns u"100"
;; Create UTF-8 label
(define-read-only (create-label (num uint))
(concat u"Label #" (int-to-utf8 num)))

string-to-int

string-to-int converts a string to an optional integer.

Signature

(string-to-int string)

Parameters

NameTypeDescription
stringstring-ascii or string-utf8String to convert
(string-to-int "123") ;; Returns (some 123)
(string-to-int "-456") ;; Returns (some -456)
(string-to-int "abc") ;; Returns none
;; Parse user input
(define-public (set-value (input (string-ascii 10)))
(match (string-to-int input)
value (ok (var-set stored-value value))
(err u1)))

string-to-uint

string-to-uint converts a string to an optional unsigned integer.

Signature

(string-to-uint string)

Parameters

NameTypeDescription
stringstring-ascii or string-utf8String to convert
(string-to-uint "123") ;; Returns (some u123)
(string-to-uint "0") ;; Returns (some u0)
(string-to-uint "-123") ;; Returns none
;; Parse amount
(define-read-only (parse-amount (input (string-ascii 20)))
(string-to-uint input))

buff-to-int-be

buff-to-int-be converts a buffer to a signed integer (big-endian).

Signature

(buff-to-int-be buffer)

Parameters

NameTypeDescription
bufferbuffBuffer to convert
(buff-to-int-be 0x0001) ;; Returns 1
(buff-to-int-be 0x00ff) ;; Returns 255
(buff-to-int-be 0xffff) ;; Returns -1
;; Parse signed data
(define-read-only (parse-signed-data (data (buff 8)))
(buff-to-int-be data))

buff-to-int-le

buff-to-int-le converts a buffer to a signed integer (little-endian).

Signature

(buff-to-int-le buffer)

Parameters

NameTypeDescription
bufferbuffBuffer to convert
(buff-to-int-le 0x0100) ;; Returns 1
(buff-to-int-le 0xff00) ;; Returns 255
;; Parse little-endian data
(define-read-only (parse-le-data (data (buff 4)))
(buff-to-int-le data))

buff-to-uint-be

buff-to-uint-be converts a buffer to an unsigned integer (big-endian).

Signature

(buff-to-uint-be buffer)

Parameters

NameTypeDescription
bufferbuffBuffer to convert
(buff-to-uint-be 0x0001) ;; Returns u1
(buff-to-uint-be 0x0100) ;; Returns u256
;; Parse network data
(define-read-only (parse-network-uint (data (buff 8)))
(buff-to-uint-be data))

buff-to-uint-le

buff-to-uint-le converts a buffer to an unsigned integer (little-endian).

Signature

(buff-to-uint-le buffer)

Parameters

NameTypeDescription
bufferbuffBuffer to convert
(buff-to-uint-le 0x0100) ;; Returns u1
(buff-to-uint-le 0x0001) ;; Returns u256
;; Parse file data
(define-read-only (parse-file-size (data (buff 4)))
(buff-to-uint-le data))

Data storage & variables

define-constant

define-constant creates an immutable constant value.

Signature

(define-constant name value)

Parameters

NameTypeDescription
namesymbolName of the constant
valueanyValue of the constant
(define-constant contract-owner tx-sender)
(define-constant token-name "MyToken")
(define-constant max-supply u1000000)
;; Use in functions
(define-read-only (get-owner)
contract-owner)

define-data-var

define-data-var creates a mutable data variable.

Signature

(define-data-var name type value)

Parameters

NameTypeDescription
namesymbolName of the variable
typetypeType of the variable
valueanyInitial value
(define-data-var counter uint u0)
(define-data-var is-paused bool false)
(define-data-var admin principal tx-sender)
;; Update variable
(define-public (increment)
(begin
(var-set counter (+ (var-get counter) u1))
(ok (var-get counter))))

var-get

var-get retrieves the value of a data variable.

Signature

(var-get name)

Parameters

NameTypeDescription
namesymbolName of the variable
(define-data-var balance uint u100)
(define-read-only (get-balance)
(var-get balance))
;; Use in calculations
(define-public (double-balance)
(let ((current (var-get balance)))
(var-set balance (* current u2))
(ok (var-get balance))))

var-set

var-set updates the value of a data variable.

Signature

(var-set name value)

Parameters

NameTypeDescription
namesymbolName of the variable
valueanyNew value
(define-data-var counter uint u0)
(define-public (set-counter (value uint))
(begin
(var-set counter value)
(ok true)))
;; Conditional update
(define-public (update-if-higher (value uint))
(if (> value (var-get counter))
(begin
(var-set counter value)
(ok true))
(err u1)))

define-map

define-map creates a new data map.

Signature

(define-map name key-type value-type)

Parameters

NameTypeDescription
namesymbolName of the map
key-typetypeType of the keys
value-typetypeType of the values
(define-map balances principal uint)
(define-map user-profiles
principal
{
name: (string-ascii 50),
age: uint,
active: bool
})
;; Composite key
(define-map allowances
{ owner: principal, spender: principal }
uint)

map-get?

map-get? retrieves a value from a map.

Signature

(map-get? map-name key)

Parameters

NameTypeDescription
map-namesymbolName of the map
keyanyKey to look up
(define-map balances principal uint)
(define-read-only (get-balance (user principal))
(default-to u0 (map-get? balances user)))
;; Pattern matching
(define-read-only (get-profile-name (user principal))
(match (map-get? user-profiles user)
profile (get name profile)
"Unknown"))

map-set

map-set sets or updates a value in a map.

Signature

(map-set map-name key value)

Parameters

NameTypeDescription
map-namesymbolName of the map
keyanyKey to set
valueanyValue to store
(define-map balances principal uint)
(define-public (set-balance (user principal) (amount uint))
(begin
(map-set balances user amount)
(ok true)))
;; Update profile
(define-public (update-profile (name (string-ascii 50)) (age uint))
(begin
(map-set user-profiles tx-sender {
name: name,
age: age,
active: true
})
(ok true)))

map-insert

map-insert inserts a value only if the key doesn't exist.

Signature

(map-insert map-name key value)

Parameters

NameTypeDescription
map-namesymbolName of the map
keyanyKey to insert
valueanyValue to store
(define-map users principal { joined: uint })
(define-public (register)
(if (map-insert users tx-sender { joined: block-height })
(ok "Registered successfully")
(err u409))) ;; Already exists
;; One-time initialization
(define-public (initialize-user (user principal))
(begin
(asserts! (map-insert balances user u1000) (err u1))
(ok true)))

map-delete

map-delete removes a key-value pair from a map.

Signature

(map-delete map-name key)

Parameters

NameTypeDescription
map-namesymbolName of the map
keyanyKey to delete
(define-map users principal { data: uint })
(define-public (remove-user (user principal))
(begin
(asserts! (is-eq tx-sender contract-owner) (err u401))
(map-delete users user)
(ok true)))
;; Clear data
(define-public (clear-balance)
(begin
(map-delete balances tx-sender)
(ok true)))

define-private

define-private creates a private function only callable within the contract.

Signature

(define-private (function-name (arg-name arg-type)...) body)

Parameters

NameTypeDescription
function-namesymbolName of the function
arg-namesymbolArgument names
arg-typetypeArgument types
bodyexpressionFunction body
(define-private (calculate-fee (amount uint))
(/ (* amount u3) u100)) ;; 3% fee
(define-public (transfer-with-fee (recipient principal) (amount uint))
(let ((fee (calculate-fee amount)))
(try! (stx-transfer? (- amount fee) tx-sender recipient))
(try! (stx-transfer? fee tx-sender contract-owner))
(ok true)))
;; Helper functions
(define-private (is-valid-amount (amount uint))
(and (> amount u0) (<= amount u1000000)))

define-public

define-public creates a public function callable from outside the contract.

Signature

(define-public (function-name (arg-name arg-type)...) body)

Parameters

NameTypeDescription
function-namesymbolName of the function
arg-namesymbolArgument names
arg-typetypeArgument types
bodyexpressionFunction body (must return response)
(define-public (transfer (recipient principal) (amount uint))
(begin
(asserts! (not (is-eq tx-sender recipient)) (err u1))
(asserts! (> amount u0) (err u2))
(try! (ft-transfer? my-token amount tx-sender recipient))
(ok true)))
;; State-changing function
(define-public (set-name (new-name (string-ascii 50)))
(begin
(map-set user-names tx-sender new-name)
(ok new-name)))

define-read-only

define-read-only creates a public read-only function.

Signature

(define-read-only (function-name (arg-name arg-type)...) body)

Parameters

NameTypeDescription
function-namesymbolName of the function
arg-namesymbolArgument names
arg-typetypeArgument types
bodyexpressionFunction body
(define-read-only (get-balance (user principal))
(default-to u0 (map-get? balances user)))
(define-read-only (calculate-reward (staked uint) (days uint))
(/ (* staked days u5) u36500)) ;; ~5% APY
;; Complex query
(define-read-only (get-user-info (user principal))
{
balance: (get-balance user),
profile: (map-get? user-profiles user),
is-admin: (is-eq user contract-owner)
})

Control flow

if

if evaluates a condition and returns one of two values.

Signature

(if condition true-branch false-branch)

Parameters

NameTypeDescription
conditionboolCondition to evaluate
true-branchanyValue if true
false-branchanyValue if false
(if (> u10 u5)
"Greater"
"Not greater") ;; Returns "Greater"
;; Conditional logic
(define-public (withdraw (amount uint))
(let ((balance (get-balance tx-sender)))
(if (>= balance amount)
(begin
(map-set balances tx-sender (- balance amount))
(ok amount))
(err u1))))

match

match performs pattern matching on optional and response types.

Signature

(match value
some-name some-branch
none-branch)

Parameters

NameTypeDescription
valueoptional/responseValue to match
some-namesymbolBinding for some value
some-branchexpressionExpression if some
none-branchexpressionExpression if none
(match (map-get? balances tx-sender)
balance (ok balance)
(err u404))
;; Response matching
(match (ft-transfer? token u100 tx-sender recipient)
success (ok "Transfer successful")
error (err error))
;; Nested matching
(define-read-only (get-user-name (user principal))
(match (map-get? user-profiles user)
profile (match (get name profile)
name (ok name)
(err u1))
(err u404)))

begin

begin executes multiple expressions in sequence.

Signature

(begin expr1 expr2... last-expr)

Parameters

NameTypeDescription
[object Object],, ,[object Object],, ...anyExpressions to execute
last-expranyFinal expression (return value)
(begin
(print "Starting")
(var-set counter u1)
(ok true))
;; Multiple operations
(define-public (initialize)
(begin
(asserts! (is-eq tx-sender contract-owner) (err u401))
(var-set is-initialized true)
(map-set admins tx-sender true)
(print { event: "initialized", by: tx-sender })
(ok true)))

let

let creates local bindings for use in an expression.

Signature

(let ((name1 value1) (name2 value2)...) body)

Parameters

NameTypeDescription
namesymbolBinding name
valueanyValue to bind
bodyexpressionExpression using bindings
(let ((x 10) (y 20))
(+ x y)) ;; Returns 30
;; Complex calculations
(define-public (calculate-reward (days uint))
(let (
(balance (get-balance tx-sender))
(rate u5) ;; 5% annual
(reward (/ (* balance rate days) u36500)))
(begin
(map-set rewards tx-sender reward)
(ok reward))))

asserts!

asserts! checks a condition and exits with an error if false.

Signature

(asserts! condition thrown-value)

Parameters

NameTypeDescription
conditionboolCondition to check
thrown-valueanyValue to return if false
(define-public (transfer (amount uint) (recipient principal))
(begin
(asserts! (> amount u0) (err u1))
(asserts! (not (is-eq tx-sender recipient)) (err u2))
(asserts! (<= amount (get-balance tx-sender)) (err u3))
(ok true)))
;; Guard functions
(define-public (admin-only-function)
(begin
(asserts! (is-eq tx-sender contract-owner) (err u401))
;; Admin logic here
(ok true)))

Optional & response types

ok

ok constructs a successful response value.

Signature

(ok value)

Parameters

NameTypeDescription
valueanySuccess value
(ok u42) ;; Returns (ok u42)
(ok { status: "success", value: u100 })
;; Success response
(define-public (deposit (amount uint))
(begin
(map-set balances tx-sender
(+ (get-balance tx-sender) amount))
(ok amount)))

err

err constructs an error response value.

Signature

(err value)

Parameters

NameTypeDescription
valueanyError value
(err u404) ;; Returns (err u404)
(err { code: u500, message: "Internal error" })
;; Error responses
(define-public (withdraw (amount uint))
(let ((balance (get-balance tx-sender)))
(if (>= balance amount)
(ok amount)
(err u1)))) ;; Insufficient balance

some

some constructs an optional value that contains a value.

Signature

(some value)

Parameters

NameTypeDescription
valueanyValue to wrap
(some u42) ;; Returns (some u42)
(some "Hello") ;; Returns (some "Hello")
;; Return optional
(define-read-only (find-user (id uint))
(if (map-get? users id)
(some (map-get? users id))
none))

unwrap!

unwrap! extracts the inner value from an optional or ok response.

Signature

(unwrap! optional-or-response thrown-value)

Parameters

NameTypeDescription
optional-or-responseoptional/responseValue to unwrap
thrown-valueanyValue if none/err
(unwrap! (some u42) (err u1)) ;; Returns u42
(unwrap! none (err u404)) ;; Throws (err u404)
;; Safe access
(define-public (transfer-from-map (recipient principal))
(let ((amount (unwrap! (map-get? pending-transfers tx-sender) (err u404))))
(try! (ft-transfer? token amount tx-sender recipient))
(map-delete pending-transfers tx-sender)
(ok amount)))

unwrap-err!

unwrap-err! extracts the error value from an err response.

Signature

(unwrap-err! response thrown-value)

Parameters

NameTypeDescription
responseresponseResponse to unwrap
thrown-valueanyValue if ok
(unwrap-err! (err u404) u0) ;; Returns u404
(unwrap-err! (ok u42) u0) ;; Returns u0
;; Error handling
(define-public (handle-error)
(let ((error-code (unwrap-err! (process-action) u0)))
(print { error: error-code })
(ok error-code)))

unwrap-panic

unwrap-panic extracts a value or causes a runtime panic.

Signature

(unwrap-panic optional-or-response)

Parameters

NameTypeDescription
optional-or-responseoptional/responseValue to unwrap
(unwrap-panic (some u42)) ;; Returns u42
(unwrap-panic none) ;; Runtime panic
;; Critical unwrap
(define-read-only (get-critical-value)
(unwrap-panic (map-get? critical-config "version")))

unwrap-err-panic

unwrap-err-panic extracts an error value or causes a runtime panic.

Signature

(unwrap-err-panic response)

Parameters

NameTypeDescription
responseresponseResponse to unwrap
(unwrap-err-panic (err u404)) ;; Returns u404
(unwrap-err-panic (ok u42)) ;; Runtime panic
;; Force error
(define-read-only (get-error-code)
(unwrap-err-panic (always-fails)))

is-ok

is-ok checks if a response is ok.

Signature

(is-ok response)

Parameters

NameTypeDescription
responseresponseResponse to check
(is-ok (ok u42)) ;; Returns true
(is-ok (err u1)) ;; Returns false
;; Check success
(define-read-only (was-successful (tx-id uint))
(is-ok (map-get? transaction-results tx-id)))

is-err

is-err checks if a response is err.

Signature

(is-err response)

Parameters

NameTypeDescription
responseresponseResponse to check
(is-err (err u404)) ;; Returns true
(is-err (ok u42)) ;; Returns false
;; Check failure
(define-read-only (has-error (result (response uint uint)))
(is-err result))

is-some

is-some checks if an optional contains a value.

Signature

(is-some optional)

Parameters

NameTypeDescription
optionaloptionalOptional to check
(is-some (some u42)) ;; Returns true
(is-some none) ;; Returns false
;; Check existence
(define-read-only (user-exists (user principal))
(is-some (map-get? users user)))

is-none

is-none checks if an optional is none.

Signature

(is-none optional)

Parameters

NameTypeDescription
optionaloptionalOptional to check
(is-none none) ;; Returns true
(is-none (some u42)) ;; Returns false
;; Check absence
(define-read-only (is-available (name (string-ascii 50)))
(is-none (map-get? reserved-names name)))

try!

try! attempts to unwrap a response, propagating any error.

Signature

(try! response)

Parameters

NameTypeDescription
responseresponseResponse to try
(try! (ok u42)) ;; Returns u42
(try! (err u404)) ;; Propagates (err u404)
;; Chain operations
(define-public (complex-operation (amount uint))
(begin
(try! (check-preconditions amount))
(try! (process-payment amount))
(try! (update-records))
(ok true)))

default-to

default-to returns a default value for none.

Signature

(default-to default optional)

Parameters

NameTypeDescription
defaultanyDefault value
optionaloptionalOptional value
(default-to u0 (some u42)) ;; Returns u42
(default-to u0 none) ;; Returns u0
;; Safe defaults
(define-read-only (get-balance-safe (user principal))
(default-to u0 (map-get? balances user)))

Fungible tokens

define-fungible-token

define-fungible-token creates a new fungible token.

Signature

(define-fungible-token token-name [total-supply])

Parameters

NameTypeDescription
token-namesymbolName of the token
total-supplyuint (optional)Maximum supply
(define-fungible-token my-token)
(define-fungible-token limited-token u1000000)
;; With helper functions
(define-public (get-balance (user principal))
(ok (ft-get-balance my-token user)))

ft-mint?

ft-mint? creates new tokens for a recipient.

Signature

(ft-mint? token amount recipient)

Parameters

NameTypeDescription
tokentoken-nameToken to mint
amountuintAmount to mint
recipientprincipalRecipient of tokens
(ft-mint? my-token u100 tx-sender)
;; Mint with checks
(define-public (mint-tokens (amount uint) (recipient principal))
(begin
(asserts! (is-eq tx-sender contract-owner) (err u401))
(ft-mint? my-token amount recipient)))

ft-burn?

ft-burn? destroys tokens from an owner.

Signature

(ft-burn? token amount owner)

Parameters

NameTypeDescription
tokentoken-nameToken to burn
amountuintAmount to burn
ownerprincipalOwner of tokens
(ft-burn? my-token u50 tx-sender)
;; Burn own tokens
(define-public (burn (amount uint))
(ft-burn? my-token amount tx-sender))

ft-transfer?

ft-transfer? transfers tokens between principals.

Signature

(ft-transfer? token amount sender recipient)

Parameters

NameTypeDescription
tokentoken-nameToken to transfer
amountuintAmount to transfer
senderprincipalSender
recipientprincipalRecipient
(ft-transfer? my-token u50 tx-sender recipient)
;; Transfer with memo
(define-public (transfer-memo (amount uint) (recipient principal) (memo (buff 32)))
(begin
(print { action: "transfer", amount: amount, memo: memo })
(ft-transfer? my-token amount tx-sender recipient)))

ft-get-balance

ft-get-balance returns the token balance of a principal.

Signature

(ft-get-balance token principal)

Parameters

NameTypeDescription
tokentoken-nameToken to query
principalprincipalAccount to check
(ft-get-balance my-token tx-sender) ;; Returns uint
;; Balance check
(define-read-only (has-sufficient-balance (user principal) (required uint))
(>= (ft-get-balance my-token user) required))

ft-get-supply

ft-get-supply returns the current token supply.

Signature

(ft-get-supply token)

Parameters

NameTypeDescription
tokentoken-nameToken to query
(ft-get-supply my-token) ;; Returns uint
;; Supply metrics
(define-read-only (get-supply-info)
{
current: (ft-get-supply my-token),
max: u1000000,
remaining: (- u1000000 (ft-get-supply my-token))
})

Non-fungible tokens

define-non-fungible-token

define-non-fungible-token creates a new non-fungible token.

Signature

(define-non-fungible-token token-name identifier-type)

Parameters

NameTypeDescription
token-namesymbolName of the NFT
identifier-typetypeType of the identifier
(define-non-fungible-token my-nft uint)
(define-non-fungible-token complex-nft { id: uint, serial: (buff 20) })
;; NFT with metadata
(define-map nft-metadata uint {
name: (string-ascii 50),
uri: (string-ascii 200)
})

nft-mint?

nft-mint? creates a new NFT for a recipient.

Signature

(nft-mint? token identifier recipient)

Parameters

NameTypeDescription
tokentoken-nameNFT to mint
identifieranyUnique identifier
recipientprincipalRecipient
(nft-mint? my-nft u1 tx-sender)
;; Mint with metadata
(define-public (mint-with-metadata (id uint) (name (string-ascii 50)) (uri (string-ascii 200)))
(begin
(try! (nft-mint? my-nft id tx-sender))
(map-set nft-metadata id { name: name, uri: uri })
(ok id)))

nft-burn?

nft-burn? destroys an NFT.

Signature

(nft-burn? token identifier owner)

Parameters

NameTypeDescription
tokentoken-nameNFT to burn
identifieranyNFT identifier
ownerprincipalCurrent owner
(nft-burn? my-nft u1 tx-sender)
;; Burn with ownership check
(define-public (burn-nft (id uint))
(let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
(asserts! (is-eq owner tx-sender) (err u403))
(nft-burn? my-nft id tx-sender)))

nft-transfer?

nft-transfer? transfers an NFT between principals.

Signature

(nft-transfer? token identifier sender recipient)

Parameters

NameTypeDescription
tokentoken-nameNFT to transfer
identifieranyNFT identifier
senderprincipalCurrent owner
recipientprincipalNew owner
(nft-transfer? my-nft u1 tx-sender recipient)
;; Safe transfer
(define-public (transfer (id uint) (recipient principal))
(let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
(asserts! (is-eq owner tx-sender) (err u403))
(nft-transfer? my-nft id tx-sender recipient)))

nft-get-owner?

nft-get-owner? returns the owner of an NFT.

Signature

(nft-get-owner? token identifier)

Parameters

NameTypeDescription
tokentoken-nameNFT to query
identifieranyNFT identifier
(nft-get-owner? my-nft u1) ;; Returns (optional principal)
;; Ownership check
(define-read-only (is-owner (id uint) (user principal))
(match (nft-get-owner? my-nft id)
owner (is-eq owner user)
false))

STX operations

stx-transfer?

stx-transfer? transfers STX between addresses.

Signature

(stx-transfer? amount sender recipient)

Parameters

NameTypeDescription
amountuintAmount in microSTX
senderprincipalSender address
recipientprincipalRecipient address
(stx-transfer? u1000000 tx-sender recipient) ;; Transfer 1 STX
;; Payment function
(define-public (pay (amount uint) (recipient principal))
(begin
(asserts! (> amount u0) (err u1))
(stx-transfer? amount tx-sender recipient)))

stx-transfer-memo?

stx-transfer-memo? transfers STX with a memo.

Signature

(stx-transfer-memo? amount sender recipient memo)

Parameters

NameTypeDescription
amountuintAmount in microSTX
senderprincipalSender address
recipientprincipalRecipient address
memo(buff 34)Transfer memo
(stx-transfer-memo? u1000000 tx-sender recipient 0x12345678)
;; Payment with reference
(define-public (pay-invoice (amount uint) (recipient principal) (invoice-id (buff 16)))
(stx-transfer-memo? amount tx-sender recipient
(concat 0x494e56 invoice-id))) ;; "INV" prefix

stx-burn?

stx-burn? burns STX by sending to a burn address.

Signature

(stx-burn? amount sender)

Parameters

NameTypeDescription
amountuintAmount to burn
senderprincipalAddress burning STX
(stx-burn? u1000000 tx-sender)
;; Burn mechanism
(define-public (burn-stx (amount uint))
(begin
(asserts! (> amount u0) (err u1))
(stx-burn? amount tx-sender)))

stx-get-balance

stx-get-balance returns the STX balance of an address.

Signature

(stx-get-balance principal)

Parameters

NameTypeDescription
principalprincipalAddress to check
(stx-get-balance tx-sender) ;; Returns uint
;; Balance check
(define-read-only (can-afford-fee (user principal) (fee uint))
(>= (stx-get-balance user) fee))

stx-account

stx-account returns detailed account information.

Signature

(stx-account principal)

Parameters

NameTypeDescription
principalprincipalAddress to query
(stx-account tx-sender)
;; Returns { locked: uint, unlock-height: uint, unlocked: uint }
;; Get available balance
(define-read-only (get-available-balance (user principal))
(get unlocked (stx-account user)))

Cryptographic functions

sha256

sha256 computes the SHA-256 hash of input data.

Signature

(sha256 data)

Parameters

NameTypeDescription
datasequenceData to hash
(sha256 0x616263) ;; Returns SHA-256 of "abc"
(sha256 "Hello") ;; Hash string
;; Create hash commitment
(define-public (commit-hash (data (buff 32)))
(let ((hash (sha256 data)))
(map-set commitments tx-sender hash)
(ok hash)))

sha512

sha512 computes the SHA-512 hash of input data.

Signature

(sha512 data)

Parameters

NameTypeDescription
datasequenceData to hash
(sha512 0x616263) ;; Returns SHA-512 hash
(sha512 "data") ;; Hash string
;; High security hash
(define-read-only (secure-hash (input (buff 1024)))
(sha512 input))

sha512/256

sha512/256 computes the SHA-512/256 hash of input data.

Signature

(sha512/256 data)

Parameters

NameTypeDescription
datasequenceData to hash
(sha512/256 0x616263) ;; Returns 256-bit hash
(sha512/256 "secure") ;; Hash string
;; Merkle tree node
(define-private (hash-pair (left (buff 32)) (right (buff 32)))
(sha512/256 (concat left right)))

keccak256

keccak256 computes the Keccak-256 hash of input data.

Signature

(keccak256 data)

Parameters

NameTypeDescription
datasequenceData to hash
(keccak256 0x616263) ;; Returns Keccak-256 hash
(keccak256 "ethereum") ;; Hash string
;; Ethereum compatibility
(define-read-only (eth-compatible-hash (data (buff 256)))
(keccak256 data))

hash160

hash160 computes RIPEMD160(SHA256(data)).

Signature

(hash160 data)

Parameters

NameTypeDescription
datasequenceData to hash
(hash160 0x616263) ;; Returns 160-bit hash
(hash160 "address") ;; Hash string
;; Bitcoin-style address
(define-read-only (create-hash160-id (data (buff 32)))
(hash160 data))

secp256k1-verify

secp256k1-verify verifies a signature against a message hash.

Signature

(secp256k1-verify hash signature public-key)

Parameters

NameTypeDescription
hash(buff 32)Message hash
signature(buff 65)Signature
public-key(buff 33)Public key
(secp256k1-verify
0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
signature
public-key) ;; Returns bool
;; Signature verification
(define-public (verify-signature (hash (buff 32)) (sig (buff 65)) (pubkey (buff 33)))
(ok (secp256k1-verify hash sig pubkey)))

secp256k1-recover?

secp256k1-recover? recovers a public key from a signature.

Signature

(secp256k1-recover? hash signature)

Parameters

NameTypeDescription
hash(buff 32)Message hash
signature(buff 65)Signature
(secp256k1-recover? message-hash signature)
;; Returns (optional (buff 33))
;; Recover signer
(define-read-only (recover-signer (hash (buff 32)) (sig (buff 65)))
(secp256k1-recover? hash sig))

Blockchain data

get-block-info?

get-block-info? retrieves information about a block.

Signature

(get-block-info? property block)

Parameters

NameTypeDescription
propertyPropertyNameProperty to retrieve
blockuintBlock height

Properties: header-hash, burnchain-header-hash, time, miner-address, block-reward, miner-spend-total, miner-spend-winner

(get-block-info? time u100) ;; Returns (optional uint)
(get-block-info? miner-address u200) ;; Returns (optional principal)
;; Get block time
(define-read-only (get-block-timestamp (height uint))
(get-block-info? time height))

get-burn-block-info?

get-burn-block-info? retrieves Bitcoin block information.

Signature

(get-burn-block-info? property block)

Parameters

NameTypeDescription
propertyPropertyNameProperty to retrieve
blockuintBurn block height

Properties: header-hash, pox-addrs

(get-burn-block-info? header-hash u100) ;; Returns (optional (buff 32))
;; Get burn block hash
(define-read-only (get-btc-header-hash (height uint))
(get-burn-block-info? header-hash height))

get-stacks-block-info?

get-stacks-block-info? retrieves Stacks block information.

Signature

(get-stacks-block-info? property block)

Parameters

NameTypeDescription
propertyPropertyNameProperty to retrieve
blockuintStacks block height

Properties: header-hash, block-hash, miner-address, block-reward

(get-stacks-block-info? block-hash u100) ;; Returns (optional (buff 32))
;; Get stacks block data
(define-read-only (get-stacks-block-hash (height uint))
(get-stacks-block-info? block-hash height))

get-tenure-info?

get-tenure-info? retrieves tenure information.

Signature

(get-tenure-info? property block)

Parameters

NameTypeDescription
propertyPropertyNameProperty to retrieve
blockuintTenure block

Properties: burnchain-header-hash, miner-address, time, vrf-seed

(get-tenure-info? vrf-seed u100) ;; Returns (optional (buff 32))
;; Get tenure VRF seed
(define-read-only (get-vrf-seed (tenure uint))
(get-tenure-info? vrf-seed tenure))

at-block

at-block evaluates an expression at a specific block context.

Signature

(at-block block-hash expr)

Parameters

NameTypeDescription
block-hash(buff 32)Block hash
exprexpressionExpression to evaluate
(at-block 0x1234... (var-get counter)) ;; Get historical value
;; Historical balance
(define-read-only (get-balance-at-block (user principal) (block-hash (buff 32)))
(at-block block-hash (ft-get-balance my-token user)))

Principal & contract operations

principal-construct?

principal-construct? creates a principal from address components.

Signature

(principal-construct? version-byte hash)

Parameters

NameTypeDescription
version-byte(buff 1)Version byte
hash(buff 20)Address hash
(principal-construct? 0x16 0x1234567890abcdef1234567890abcdef12345678)
;; Returns (optional principal)
;; Construct address
(define-read-only (make-principal (version (buff 1)) (hash (buff 20)))
(principal-construct? version hash))

principal-destruct?

principal-destruct? decomposes a principal into components.

Signature

(principal-destruct? principal)

Parameters

NameTypeDescription
principalprincipalPrincipal to decompose
(principal-destruct? tx-sender)
;; Returns (optional { version: (buff 1), hash: (buff 20) })
;; Get address components
(define-read-only (get-principal-parts (user principal))
(principal-destruct? user))

principal-of?

principal-of? returns the principal from a public key.

Signature

(principal-of? public-key)

Parameters

NameTypeDescription
public-key(buff 33)Public key
(principal-of? 0x0234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12)
;; Returns (optional principal)
;; Derive address
(define-read-only (pubkey-to-principal (pubkey (buff 33)))
(principal-of? pubkey))

contract-call?

contract-call? calls a public function in another contract.

Signature

(contract-call? contract function-name args...)

Parameters

NameTypeDescription
contractprincipalContract to call
function-namesymbolFunction name
argsanyFunction arguments
(contract-call? .other-contract transfer u100 tx-sender recipient)
;; Cross-contract call
(define-public (forward-call (amount uint))
(contract-call? .token-contract transfer amount tx-sender contract-owner))

as-contract

as-contract executes an expression with the contract as tx-sender.

Signature

(as-contract expr)

Parameters

NameTypeDescription
exprexpressionExpression to execute
(as-contract (stx-transfer? u1000 tx-sender recipient))
;; Contract-owned transfers
(define-public (withdraw-fees (recipient principal))
(let ((balance (stx-get-balance (as-contract tx-sender))))
(as-contract (stx-transfer? balance tx-sender recipient))))

contract-of

contract-of returns the principal of a trait reference.

Signature

(contract-of trait-ref)

Parameters

NameTypeDescription
trait-reftraitTrait reference
(contract-of token-trait) ;; Returns principal
;; Get implementation
(define-read-only (get-token-contract)
(contract-of deployed-token))

is-standard

is-standard checks if a principal matches the current network type and can spend tokens.

Signature

(is-standard standard-or-contract-principal)

Parameters

NameTypeDescription
standard-or-contract-principalprincipalPrincipal to check
;; On testnet
(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns true
(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.foo) ;; Returns true
(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns false
;; On mainnet
(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns true
(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY.foo) ;; Returns true
(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns false
;; Invalid principal format (returns false on both networks)
(is-standard 'SZ2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR) ;; Returns false

Key points:

  • Tests if a principal can spend tokens on the current network
  • Mainnet: Only SP and SM addresses can spend
  • Testnet: Only ST and SN addresses can spend
  • All addresses can receive tokens, but only matching network types can spend
  • Available starting with Stacks 2.1
;; Network-aware validation
(define-read-only (can-spend-on-network (address principal))
(is-standard address))
;; Check if address matches network before allowing spending
(define-public (network-aware-transfer (recipient principal) (amount uint))
(begin
(asserts! (is-standard tx-sender) (err u401))
(asserts! (is-standard recipient) (err u402))
;; Transfer logic
(ok true)))

Traits

define-trait

define-trait creates a new trait definition.

Signature

(define-trait trait-name ((function-name (args...) response-type)...))

Parameters

NameTypeDescription
trait-namesymbolName of the trait
function-namesymbolFunction signatures
(define-trait fungible-token (
(transfer (uint principal principal) (response bool uint))
(get-balance (principal) (response uint uint))
))
;; NFT trait
(define-trait nft-trait (
(transfer (uint principal principal) (response bool uint))
(get-owner (uint) (response (optional principal) uint))
))

impl-trait

impl-trait declares that a contract implements a trait.

Signature

(impl-trait trait-identifier)

Parameters

NameTypeDescription
trait-identifiertraitTrait to implement
(impl-trait .token-trait.fungible-token)
;; Multiple traits
(impl-trait .dao-traits.proposal-trait)
(impl-trait .dao-traits.voting-trait)

use-trait

use-trait creates a trait alias for use in functions.

Signature

(use-trait alias trait-identifier)

Parameters

NameTypeDescription
aliassymbolLocal alias
trait-identifiertraitTrait to alias
(use-trait token-trait .token-trait.fungible-token)
(define-public (swap (token <token-trait>) (amount uint))
(contract-call? token transfer amount tx-sender .pool))

Type conversions

to-int

to-int converts an unsigned integer to a signed integer.

Signature

(to-int uint)

Parameters

NameTypeDescription
uintuintUnsigned integer
(to-int u100) ;; Returns 100
(to-int u0) ;; Returns 0
;; Convert for calculations
(define-read-only (calculate-delta (a uint) (b uint))
(- (to-int a) (to-int b)))

to-uint

to-uint converts a signed integer to an unsigned integer.

Signature

(to-uint int)

Parameters

NameTypeDescription
intintSigned integer
(to-uint 100) ;; Returns u100
(to-uint -50) ;; Causes runtime error
;; Safe conversion
(define-read-only (safe-to-uint (value int))
(if (>= value 0)
(some (to-uint value))
none))

to-consensus-buff?

to-consensus-buff? serializes a value to consensus format.

Signature

(to-consensus-buff? value)

Parameters

NameTypeDescription
valueanyValue to serialize
(to-consensus-buff? u100) ;; Returns (optional (buff 3))
(to-consensus-buff? { a: u1, b: u2 }) ;; Serializes tuple
;; Create hash of data
(define-read-only (hash-value (data uint))
(match (to-consensus-buff? data)
buff (sha256 buff)
0x00))

from-consensus-buff?

from-consensus-buff? deserializes from consensus format.

Signature

(from-consensus-buff? type buffer)

Parameters

NameTypeDescription
typetype-signatureExpected type
bufferbuffBuffer to deserialize
(from-consensus-buff? uint 0x0100) ;; Returns (optional u1)
(from-consensus-buff? { a: uint, b: uint } buff) ;; Deserialize tuple
;; Parse stored data
(define-read-only (decode-data (data (buff 128)))
(from-consensus-buff? { value: uint, timestamp: uint } data))

Bit operations

bit-and

bit-and performs bitwise AND operation.

Signature

(bit-and i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(bit-and u12 u10) ;; Returns u8 (1100 & 1010 = 1000)
(bit-and 0xFF 0x0F) ;; Returns 0x0F
;; Check flags
(define-read-only (has-permission (flags uint) (permission uint))
(> (bit-and flags permission) u0))

bit-or

bit-or performs bitwise OR operation.

Signature

(bit-or i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(bit-or u12 u10) ;; Returns u14 (1100 | 1010 = 1110)
(bit-or 0xF0 0x0F) ;; Returns 0xFF
;; Set flags
(define-public (add-permission (current uint) (new-permission uint))
(ok (bit-or current new-permission)))

bit-xor

bit-xor performs bitwise XOR operation.

Signature

(bit-xor i1 i2)

Parameters

NameTypeDescription
i1int or uintFirst value
i2int or uintSecond value
(bit-xor u12 u10) ;; Returns u6 (1100 ^ 1010 = 0110)
(bit-xor 0xFF 0xFF) ;; Returns 0x00
;; Toggle flags
(define-public (toggle-flag (flags uint) (flag uint))
(ok (bit-xor flags flag)))

bit-not

bit-not performs bitwise NOT operation.

Signature

(bit-not i)

Parameters

NameTypeDescription
iint or uintValue to invert
(bit-not u0) ;; Returns maximum uint
(bit-not 0xFF) ;; Returns -256
;; Invert permissions
(define-read-only (get-inverse-permissions (permissions uint))
(bit-not permissions))

bit-shift-left

bit-shift-left shifts bits to the left.

Signature

(bit-shift-left i positions)

Parameters

NameTypeDescription
iint or uintValue to shift
positionsuintPositions to shift
(bit-shift-left u1 u3) ;; Returns u8 (1 << 3)
(bit-shift-left u5 u2) ;; Returns u20
;; Calculate power of 2
(define-read-only (pow2 (exponent uint))
(bit-shift-left u1 exponent))

bit-shift-right

bit-shift-right shifts bits to the right.

Signature

(bit-shift-right i positions)

Parameters

NameTypeDescription
iint or uintValue to shift
positionsuintPositions to shift
(bit-shift-right u8 u3) ;; Returns u1 (8 >> 3)
(bit-shift-right u20 u2) ;; Returns u5
;; Fast division by power of 2
(define-read-only (div-pow2 (value uint) (exponent uint))
(bit-shift-right value exponent))

Utility functions

print

print outputs a value and returns it.

Signature

(print value)

Parameters

NameTypeDescription
valueanyValue to print
(print "Debug message") ;; Prints and returns "Debug message"
(print { event: "transfer", amount: u100 })
;; Debug function
(define-public (debug-transfer (amount uint))
(begin
(print { function: "transfer", amount: amount, sender: tx-sender })
(ok true)))

as-max-len?

as-max-len? checks if a sequence fits within a maximum length.

Signature

(as-max-len? sequence max-length)

Parameters

NameTypeDescription
sequencesequenceSequence to check
max-lengthuintMaximum allowed length
(as-max-len? (list 1 2 3) u5) ;; Returns (some (1 2 3))
(as-max-len? "Hello" u3) ;; Returns none
;; Safe append
(define-public (add-to-list (item uint))
(match (as-max-len? (append (var-get items) item) u100)
new-list (begin
(var-set items new-list)
(ok true))
(err u1)))

merge

merge combines two tuples, with the second overriding the first.

Signature

(merge tuple1 tuple2)

Parameters

NameTypeDescription
tuple1tupleBase tuple
tuple2tupleOverride tuple
(merge { a: u1, b: u2 } { b: u3, c: u4 })
;; Returns { a: u1, b: u3, c: u4 }
;; Update record
(define-public (update-profile (updates { name: (optional (string-ascii 50)), age: (optional uint) }))
(let ((current (default-to { name: "", age: u0 } (map-get? profiles tx-sender))))
(map-set profiles tx-sender (merge current updates))
(ok true)))

get

get extracts a value from a tuple by key.

Signature

(get key tuple)

Parameters

NameTypeDescription
keysymbolKey to extract
tupletupleTuple to access
(get balance { balance: u100, locked: u50 }) ;; Returns u100
;; Access nested data
(define-read-only (get-user-balance (user principal))
(match (map-get? accounts user)
account (get balance account)
u0))

On this page