clarity-scholar
Skill2 starsChanged 31 days agoMITView on GitHub
Write, build or refactor Clarity (.clar) contracts: syntax, types, responses, errors, traits, loops and layout. Use before writing or editing Clarity code, fixing compile errors, or answering how Clarity code behaves: what an expression returns, what aborts or rolls back, what the VM checks.
In this repository24 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- clarity-apisSkill
- clarity-assetsSkill
- clarity-auditorSkill
- clarity-bitcoin-proofsSkill
- clarity-deploymentSkill
- clarity-ecosystemSkill
- clarity-environmentsSkill
- clarity-epochsSkill
- clarity-fuzzingSkill
- clarity-governanceSkill
- clarity-optimizerSkill
- clarity-oraclesSkill
- clarity-protocolsSkill
- clarity-securitySkill
- clarity-sip-complianceSkill
- clarity-stakingSkill
- clarity-startSkill
- clarity-system-integrationSkill
- clarity-testingSkill
- clarity-upgradesSkill
- clarity-walletsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
20 rules. About 0 are common, 9 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈9
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 30
Follow contract layout; run clarinet check until clean.
- Very specific: line 32
Add Clarigen/Vitest tests for every public function and error path.
- Distinctive: line 36
Check language, epoch and tool support.
- Distinctive: line 40
Add a persistent lock only for a reachable callback that can break an invariant (criteria).
- Distinctive: line 49
Read syntax tables and a complete contract for literals, definitions, control flow and trait syntax.
- Very specific: line 79
Use kebab-case for functions, parameters and storage names.
- Very specific: line 82
Put units in names: amount-ustx, price-e8, rate-bps, expires-at (seconds), unlock-burn-height.
- Very specific: line 85
Default privileged roles to data vars initialized with tx-sender, with authenticated setters and events naming actor, previous and new …
- Very specific: line 86
Remove redundant single-expression begin, nested let and match branches that only rebuild the original response.
- Distinctive: line 107
Put authorization, range and denominator checks before dependent arithmetic, writes or external calls.
- Very specific: line 123
No recursion, no while, no built-in every.
- Very specific: line 150
Never grow an unbounded list in a data var (append + as-max-len?
- Very specific: line 154
Read references/authority.md before writing privileged functions, as-contract?
- Very specific: line 190
Read additive range checks when guarding a cap: prefer amount + used <= cap once operands are bounded.
- Distinctive: line 197
Read time detail when writing deadlines, PoX schedules or a configurable period length.
- Distinctive: line 210
Keep names and fields stable.
- Distinctive: line 218
Use upgrades for scope, timelocks, state/token migrations and overlapping versions.
- Very specific: line 229
Run python3 <scholar>/scripts/lookup_function.py 'as-contract?' (<scholar> is this skill's directory.
- Distinctive: line 230
Before using an unfamiliar form, check its signature and example this way.
- Distinctive: line 231
Read references/lookup.md for known VM-doc discrepancies and sources to cross-check, and to study deployed contracts.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Clarity Scholar
Make authority, units and failure paths explicit while preserving the requested behavior.
Writing or changing contract code: also load clarity-security, and finish with the build checklist.
Key distinctions
is-standardchecks network compatibility, not account versus contract. Unwrapprincipal-destruct?for the current network: itsnameissomefor a contract principal andnonefor a standard account.contract-oftakes a trait value and returns a principal, not an optional or a principal-kind check; see authority checks.- Current time is
stacks-block-timein Clarity 4+; previous-block timestamps lag execution. - No
as-contract?body expression may be response-typed. Handle its outer response and capture actors before switching context. beginrejects unchecked intermediate responses, butletbindings and response lists can hide errors.- A fitting quotient does not prevent an intermediate uint128 multiplication from overflowing.
- Epoch changes can affect old contracts; retaining a language version does not preserve every historical feature.
Write or refactor
clarinet contract new NAME(orcontracts new) creates the contract and manifest entry. Clarinet 3.26.0 defaults to Clarity 6 / epoch 4.0; use an older version only for interoperability. Unscheduled epoch 4.1 rejects version-pinned deployments (versions).- Follow contract layout; run
clarinet checkuntil clean. - Format with the project's formatter if it has one; otherwise
clarinet format --in-place --file contracts/NAME.clar, thenclarinet format --checkon the same files. - Add Clarigen/Vitest tests for every public function and error path; run
npm test. Clarigen is the default typed client; Clarinet remains the execution layer.
For changes to existing code:
- Check language, epoch and tool support. Preserve intended ABI, errors, assets, roles, invariants, dependencies and storage compatibility.
- For future logic replacement, prefer separate token ledgers and stable custody/accounting (upgrade architecture).
- Choose failure behavior deliberately; propagate atomic-batch errors, define rounding and bound intermediates.
- Preserve tuple snapshots, cache validity and registry invariants; locals do not refresh after writes.
- Add a persistent lock only for a reachable callback that can break an invariant (criteria).
- Wallets constrain aggregate sends; contracts enforce intended receipts (postconditions).
- Apply native pitfalls and recall corrections to their stated targets. Standards require the normative SIP and deployed trait, not invented ERC-20 approvals or vault APIs.
- Separate style from behavior changes; test observable behavior. Shorter expressions are not necessarily cheaper: measure all five cost dimensions.
Syntax
Examples in this skill run on Clarity 4–6 at epoch 4.0 unless marked. Omit their ;; id: labels in project code. Check version-specific behavior before porting; look up exact signatures with the lookup script.
Read syntax tables and a complete contract for literals, definitions, control flow and trait syntax. Keep these distinctions:
u42isuint,42isint; keywords such astx-sendertake no().- Definitions are top-level; a function has one body expression; public functions return a response.
- Optional
matchtakes four arguments, responsematchfive;foldreducers take element, then accumulator.
Unlike general Lisp
(function arg ...)calls; atoms stand alone. Parentheses do not merely group values.- No
eval, macros, lambdas, first-class functions, recursion or unbounded loops.map/filter/foldrequire literal function names. - Parameters/storage declare types; expression/return types are inferred before deploy. Branch types must agree, lists are homogeneous and sequences are bounded. Integers are 128-bit, and overflow aborts.
'introduces a principal;;;starts a comment. No//, quote/backquote code forms, JavaScript property access, mutation operators,returnor semicolon separators.- Conditions must be booleans, not
none, responses or integers.ifneeds both branches;letsupports several body expressions. Tuple labels and definition names are literal identifiers, not strings.
Names that no longer exist
A name outside its version range fails analysis on deploy.
as-contract(Clarity 1–3): useas-contract?with explicit allowances (Clarity 4+);current-contractfor the contract's own principal.block-height(Clarity 1–2):stacks-block-height(every Stacks block) ortenure-height(Clarity 3+);burn-block-heightfor Bitcoin.get-block-info?(Clarity 1–2):get-stacks-block-info?,get-tenure-info?(Clarity 3+);stacks-block-timefor the current block (Clarity 4+).at-block(Clarity 1–4): nothing equivalent; existing callers throw from epoch 3.4.with-stacking(Clarity 4–5):with-staking(Clarity 6+). Clarity 6 also addswith-pox, with no amount, for position-changing PoX calls such asunstake; it does not cover locking.
Layout and style
For new files or restyling, read style and layout: trait-only contracts, mocks in contracts/mock/, declaration order and the withdraw example. Use the project formatter (else clarinet format on owned files), a ;; summary above each function, brace tuples for values/types, and nested if dispatch ending in an explicit error.
Names, units, errors
- Use kebab-case for functions, parameters and storage names; new constants use
SCREAMING_SNAKE_CASE, including errors and address aliases; in an existing project, keep its constant style. Current Clarinet's constant-case lint flags hyphens (a style note by default). - Parameters and
letbindings cannot shadow contract-level variables/constants. Use distinct names; unrelated functions may reuse parameter names. - Natives whose names end in
?return an optional or response (map-get?,stx-transfer?), exceptcontract-call?, which returns what the callee returns. Follow that convention for your own helpers, and useget-.../is-...for getters and booleans. - Put units in names:
amount-ustx,price-e8,rate-bps,expires-at(seconds),unlock-burn-height.uinthas no implicit scale. - Define a commented
ERR_...constant per distinct failure, so callers and tests can tell failures apart (for example missing versus unauthorized). Prefer a higher local range such asu1000–u1099to avoid native/boot collisions. Ranges are not globally reserved: document module prefixes, distinguish forwarded errors, preserve public ABIs and standard conventions (SIP-010 transfer codesu1–u4). A forwarded(err u1)can originate in any callee. - Public functions must return a response. Keep each response branch type compatible across paths; the analyzer must infer a common type. Trait return bounds are maxima, not exact lengths; see compatible return types.
- Default privileged roles to data vars initialized with
tx-sender, with authenticated setters and events naming actor, previous and new authority. Use reachable ownership handoff; immutable administration requires an explicit design choice. - Remove redundant single-expression
begin, nestedletandmatchbranches that only rebuild the original response. The book's style suggestions explain these; measure cost claims against current tooling.
Responses: choose the failure behavior
| Need | Use |
| Propagate a response-returning callee's error unchanged | (try! (contract-call? ...)) |
| Replace a missing value / error with a local error | (unwrap! (map-get? m k) ERR_NOT_FOUND) |
| Guard a precondition | (asserts! cond ERR_...) |
| Act differently on success and failure | (match resp v (...) e (...)) |
| A value whose absence is a bug you have proved impossible | unwrap-panic (aborts the whole transaction, no error code) |
- Bind a plain tuple/value returned by a read-only function directly;
try!requires a response or optional. Check the ABI before unwrapping. try!,unwrap!,asserts!return from the enclosing function. Inside afold/mapcallback that means the callback, not your public function.- A public function that returns
errrolls back all of its writes and events; one that catches a callee error and returnsokkeeps its own writes. - The analyzer rejects an unchecked response used as an intermediate
beginexpression, but not one bound inlet, returned inside a list frommap, or discarded viamatch. Do not rely on it to catch ignored failures.
Guard before computing
letevaluates bindings in order, before its body, so an assertion in the body is too late for later bindings. Bind the guard first, asremainingbelow does: failure returnsERR_INSUFFICIENTbefore the subtraction; computingleftfirst would abort on underflow, bypassing a later guard.- The guard binding is
trueon success; notry!is needed. Use descriptive placeholders ending in_, such asamount-check_orclaims-capacity-ok_, to mark intentionally unused results for the default linter. Avoid opaquep1/p2names. - Put authorization, range and denominator checks before dependent arithmetic, writes or external calls. Validate the guard's own arithmetic too.
- A guard in a
fold/mapcallback exits only that callback; propagate batch failures.
;; id: let-guard
(define-constant ERR_INSUFFICIENT (err u1100))
(define-read-only (remaining (balance uint) (amount uint))
(let ((amount-check_ (asserts! (<= amount balance) ERR_INSUFFICIENT)) (left (- balance amount)))
(ok left)))- Upstream example: Bitflow's bound check before a call.
Iteration without loops
- No recursion, no
while, no built-inevery. Use boundedfoldfor an all-items predicate. - Iterate over a bounded list with
map,filterorfold. To repeat N times, fold over a constant index list. - For filtering with per-call context, compare a pure context/output
foldwith a stored-helperfilter: fewer reads can cost much more runtime (cost tradeoff). - For atomic batches, thread a response through
fold; stop work after the first error:
;; id: atomic-batch
(define-constant ERR_DUPLICATE (err u1001))
(define-map seen uint bool)
(define-public (record-many (ids (list 100 uint)))
(fold record-one ids (ok true)))
(define-private (record-one (id uint) (prior (response bool uint)))
(begin
(try! prior)
(asserts! (map-insert seen id true) ERR_DUPLICATE)
(ok true)))- A late duplicate returns
err, so the public function rolls back the earlier insertions. foldstill visits every element (it never breaks early): thetry! priormakes later visits cheap no-ops.- In contrast,
(ok (map do-thing items))returnsokeven when some items failed: it is a partial-success API, and the caller gets a list of responses. map-insertreturnsfalse(not an error) if the key exists;map-setsilently overwrites. Usemap-insertwith an assert for create-once records (claims, nonces, IDs).var-setandmap-setreturn write-successtrue, even when storingfalse; they do not return the stored value.- Bound everything a user controls: list arguments (
(list 20 ...)), buffers ((buff 34)), strings. - Never grow an unbounded list in a data var (
append+as-max-len?caps it, and each read costs the whole list). Use a map keyed by an incrementing index instead.
Authority, traits and dependencies
Read references/authority.md before writing privileged functions, as-contract? custody, trait calls or address constants:
- Authority and execution context: admin checks use
contract-caller(DAO-executed setters checktx-senderagainst the DAO); capture actors beforeas-contract?; list explicit allowances (with-ftnames contract and token) andtry!the result;current-contractis the contract's own principal. - Traits and dynamic calls: take traits as arguments; check
contract-ofagainst a stored principal per role;impl-traitchecks signatures only. - Trait checks have distinct stages (VM rules):
- Contract literals in source and
impl-trait: whole-trait check at deployment. - Node mempool: whole-trait check on transaction arguments (in any list, only the first element). Simnet has no mempool, so a partial mock that works there can still be rejected by a node.
- Runtime trait values, including transaction arguments and forwarded/nested values: check the invoked method at dispatch; no
impl-traitrequired. - A trait-typed parameter inside a router trait: nested trait identity matters at dispatch. A byte-identical local copy can deploy and pass
clarinet check, then fail withBadTraitImplementationon the real call. Use the protocol's trait or a static call.
- Contract literals in source and
- Fixed contract addresses: calls through address constants need epoch 3.4+, and fail at top level (simnet misses this) and in read-only paths.
Arithmetic
uint/intare 128-bit. Overflow, underflow and division by zero abort the transaction (no wrap, no error code).- Order operations for precision and bound the intermediate. Floor and ceil helpers, each guarding the denominator first; the ceil form avoids the
(n + d - 1)overflow at the top of the range:
;; id: mul-div
(define-constant ERR_ZERO_DENOMINATOR (err u1300))
;; floor(a*b/d): a*b must fit in 128 bits, or this aborts.
(define-read-only (mul-div-down (a uint) (b uint) (d uint))
(begin
(asserts! (> d u0) ERR_ZERO_DENOMINATOR)
(ok (/ (* a b) d))))
;; ceil(a*b/d) without the (n + d - 1) overflow at the top of the range.
(define-read-only (mul-div-up (a uint) (b uint) (d uint))
(let ((denominator-check_ (asserts! (> d u0) ERR_ZERO_DENOMINATOR)) (n (* a b)))
(ok (+ (/ n d) (if (> (mod n d) u0) u1 u0)))))- Choose rounding per operation to preserve solvency. Typical vaults floor deposit shares/redeem assets and ceil withdrawal shares/mint assets; verify debt conventions separately.
(/ (* a b) d)and(* (/ a d) b)differ: dividing first truncates.powoverflows quickly; prefer fixed-point helpers with documented bounds.- Clarity has no 256-bit type: a Solidity
mulDivdoes not port unchanged. - Read additive range checks when guarding a cap: prefer
amount + used <= caponce operands are bounded.
Time
- Clarity 4+:
stacks-block-timeis the current block's timestamp in seconds. (get-stacks-block-info? time (- stacks-block-height u1))is the previous block's time. Older versions have no current timestamp at all.- Handle zero elapsed time: calls within one Stacks block share its timestamp. Distinct Stacks blocks must have increasing timestamps.
- Read time detail when writing deadlines, PoX schedules or a configurable period length.
Strings, buffers, serialization
(buff 34)/(string-ascii 32)are maxima. Check exact lengths withlenbefore slicing or indexing.slice?,element-at?andas-max-len?return optionals.concattakes exactly two arguments before Clarity 6.as-max-len?is a checked cast, not truncation.buff-to-uint-be/-leandbuff-to-int-be/-leaccept at most 16 bytes. Short inputs are zero-padded, not sign-extended:(buff-to-int-be 0xffffffff)returns4294967295, not-1(conversion rules).to-consensus-buff?gives the canonical serialization for hashing and SIP-018 signing; apply signature validation and replay rules to the chosen scheme. Tuple fields serialize in sorted key order, not declaration order.int-to-ascii(C2+),to-ascii?(C4+) for display strings. Strings cost bytes on every read and write.
Events
printone tuple per state-changing action, after the change succeeds:{event: "withdraw", owner: ..., amount: ..., id: ...}.- Keep names and fields stable; indexers depend on them.
- Prints are discarded when their context rolls back: a transaction whose top-level result is
err, a public function that returnserr(even when its caller handles the error), a violatedas-contract?orrestrict-assets?scope and any read-only function, even one that a public function calls. Print from the public function or a private helper it calls. - Anyone can print an identical tuple from another contract, so consumers must filter by emitting contract.
Upgradability
- Code and literal dependency principals are immutable.
- Authorized registries/DAOs (
is-dao-or-extension) or trait arguments checked against stored role principals can select replaceable logic. State and custody do not move automatically. - Use upgrades for scope, timelocks, state/token migrations and overlapping versions.
Read-only functions
define-read-onlycannot write, can only call other read-only functions (including read-only functions of other contracts by literal principal), and cannot make dynamic trait calls.- Read-only code must name another contract by its literal principal. A call through a contract-principal constant fails analysis with "detected a writing operation", even when the target is read-only and even through a private helper. In Clarity 2+, public functions and the private helpers they call can use the constant from epoch 3.4.
- Off-chain calls via
/v2/contracts/call-readare free; on-chain they still consume budget. - A read-only getter of an external contract can still lie: it is code, not a proof.
Exact language lookup
- Run
python3 <scholar>/scripts/lookup_function.py 'as-contract?'(<scholar>is this skill's directory; exact name, quoted). It prints the matching rows of the version-specific behavior table before the quoted VM text; apply them first. Unknown names exit 2: search the index inreferences/functions.md. Avoid loading the whole catalog. - Before using an unfamiliar form, check its signature and example this way. Compile for the target version and fix diagnostics before claiming completion.
- Read references/lookup.md for known VM-doc discrepancies and sources to cross-check, and to study deployed contracts.
References
- Functions: generated VM catalog, indexed by name, version and signature. Prefer the lookup script; topic references are linked where needed above.
Reference baseline
Examples use Clarity 4+ syntax unless marked, checked on epoch 4.0. Source links in this skill and its references use these pins; links into sibling skills use their owner's SKILL.md.
stacks-core: ccf31dc69c.clarity-deployed-contracts: 45a7af6028.bitflow-dlmm: b4d3694c86.zest-v2: f2fce52672.granite: 2d44a2df94.hermetica: 5e13e431f6.sbtc: eb507946c6.clarinet: 52e4f35ea5.bips: 5aadddb511.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

