clarity-testing
Skill2 starsChanged 30 days agoMITView on GitHub
Test Clarity contracts with Clarigen and the Clarinet SDK (vitest, simnet): setup, typed calls, mining blocks, coverage, mainnet forks, attacker contracts. Use whenever adding or fixing tests in a Clarinet project.
- Reads credentials
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-scholarSkill
- clarity-securitySkill
- clarity-sip-complianceSkill
- clarity-stakingSkill
- clarity-startSkill
- clarity-system-integrationSkill
- clarity-upgradesSkill
- clarity-walletsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
23 rules. About 0 are common, 10 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
Use Clarigen by default for typed clients and tests (@clarigen/core, @clarigen/test, @clarigen/cli).
- Very specific: line 48
Keep generated Clarigen.toml and comments (output = "src/clarigen-types.ts", [docs] output = "docs").
- Very specific: line 50
Keep the initializer's Clarinet settings in vitest.config.ts and add runner options such as testTimeout or silent alongside them.
- Distinctive: line 51
Keep initializer defaults.
- Distinctive: line 53
Read project setup for scripts, Vitest config, focused tests, snapshot filtering and tool limits (no epoch 4.1 / Clarity 7 in simnet).
- Very specific: line 70
Never raise clarity_version just to silence an analysis error in a contract that is already deployed: it changes semantics (versions).
- Very specific: line 110
Prefer .value after txOk/txErr.
- Very specific: line 115
Keep Vitest's simnet reset before every test (initBeforeEach).
- Very specific: line 116
Run semantic and cost regression tests with cost tracking and assert receipts contain costs (receipt.costs): the free tracker can hide …
- Distinctive: line 123
Read-only prints appear on stdout but are discarded from receipts, even when a public function calls the read-only function ([VM transaction
- Very specific: line 156
Read references/blocks-and-batches.md for the full rules and examples: clock boundaries, an advanceBurnTo helper, batch receipts, a …
- Very specific: line 160
Test through contracts, not only wallets: deploy a small caller/attacker contract to create the contract-caller/tx-sender context a router, …
- Distinctive: line 162
Read references/test-design.md before writing one: deploy order, sender contexts, lying trait implementations and an admin-to-bait fragment.
- Distinctive: line 170
Read references/test-design.md for the required contrasting cases and what to observe per surface (authority, trait, allowance, token, …
- Very specific: line 171
Use a version-matched simnet for contract semantics and devnet/replay for node/epoch/bridge behavior that simnet does not model.
- Very specific: line 189
Read references/mainnet-forks.md before configuring or debugging a fork (full rules, getSDK(), funding helpers).
- Very specific: line 202
Keep mock contracts (for example under contracts/mock/) out of integration manifests.
- Distinctive: line 203
Before pinning dependencies or building fixtures, read dependency rules and examples.
- Distinctive: line 208
Read coverage aggregation before reporting a percentage or generating HTML: merge per-test records, state which contracts count and collect …
- Distinctive: line 210
Read references/test-design.md before writing property or generated-input tests: bigint boundaries and rounding, seeded generators, …
- Very specific: line 212
Before deployment, follow the release runbook in clarity-deployment.
- Distinctive: line 218
Search the exact installed version and error before changing APIs or downgrading semantics.
- Distinctive: line 220
Read references/troubleshooting.md for print floods, bad trait argument errors, Windows manifest paths, a diagnostic record and numeric …
≈ “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 Testing
Use Clarigen by default for typed clients and tests (@clarigen/core, @clarigen/test, @clarigen/cli). Clarinet supplies the VM, manifest, simnet, devnet and deployment tooling. Preserve existing manifests, package managers, tests and explicit tooling choices; add only the needed Clarigen changes.
Key distinctions
- Clarigen does not replace the Clarinet execution engine or add unsupported epochs.
- Generated types prove neither authorization nor correct economic behavior.
- Direct wallet calls miss router/callback sender context. Private calls and patched storage do not prove public reachability.
- A source requirement does not import every live permission, balance or oracle setting.
- Separate simnet calls mine separate blocks; test same-block restrictions with an explicit batch. One block is not one atomic transaction.
- Raw simulated senders do not prove signature or mempool admission; use environment fidelity to choose simnet, devnet or a network check.
New project
clarinet new writes Clarinet.toml, settings/, package.json, vitest.config.ts, tsconfig.json and tests/; it does not run npm install. clarinet contract new (alias contracts new) adds contracts/vault.clar, tests/vault.test.ts and the manifest entry.
clarinet new my-protocol && cd my-protocol
clarinet contract new vault
# One copy of @stacks/transactions: Clarigen packages otherwise install 7.1/7.2 next to the SDK's 7.6.0
npm pkg set 'overrides.@stacks/transactions=$@stacks/transactions'
# npm 11 (Node 24+ ships it): the npm 10.9 bundled with Node 22 crashes on this scaffold (see below)
npx -y npm@11 install --save-dev --save-exact \
@clarigen/cli@4.1.7 @clarigen/core@4.1.7 @clarigen/test@4.1.7 \
@stacks/clarinet-sdk@3.26.0 @stacks/clarinet-sdk-wasm@3.26.0 @stacks/transactions@7.6.0 \
vitest@5.0.5 vitest-environment-clarinet@3.1.0
npm pkg set scripts.clarigen="clarigen && clarigen docs" scripts.pretest="npm run clarigen"
npx clarigen init # writes Clarigen.toml; refuses if it exists (--overwrite)
npx clarigen # generates src/clarigen-types.ts and the simnet deployment plan
npx vitest runnpm ls @stacks/transactionsmust show one7.6.0copy ordeduped: mixed copies compare Clarity values badly. The override follows the direct dependency; a literal override can causeEOVERRIDE.- With npm, use npm 11 for every install; npm 10.9.8 fails on the initializer's Vitest 4 peers. For either install error, read setup diagnostics.
@clarigen/testdeclares Clarinet SDK/WASM peers^3.9.2; keep both at the same version and commit the lockfile.- Stay on Clarinet and the SDK 3.26.0: SDK 4 (Clarinet 4.0) removed
simnet.runSnippet, so Clarigen 4.1.7 fails withsimnet.runSnippet is not a function. A project created by Clarinet 4 works once the install above pins the 3.26.0 packages. - Keep generated
Clarigen.tomland comments (output = "src/clarigen-types.ts",[docs] output = "docs"). Fromtests/, import../src/clarigen-types; these examples instead set output totests/clarigen-types.tsand import./clarigen-types. - Regenerate after ABI, deployment or requirement changes (
npx clarigen, or--watch). Never fix a stale ABI by editing generated types.TestProvider, Deno-only,clarigen.config.jsonand[esm]guides are obsolete. - Keep the initializer's Clarinet settings in
vitest.config.tsand add runner options such astestTimeoutorsilentalongside them; flags after--(for example-- --coverage --costs) are read bygetClarinetVitestsArgv(). ThetransformModewarning (environment 3.1.0 on Vitest 5) is harmless. - Keep initializer defaults; apply formatting and function comments to authored production contracts (mock comments optional).
- On Windows, read Windows manifest paths before generation.
- Read project setup for scripts, Vitest config, focused tests, snapshot filtering and tool limits (no epoch 4.1 / Clarity 7 in simnet).
Manifest settings
# Clarinet.toml (fragment)
[contracts.vault]
path = "contracts/vault.clar"
clarity_version = 6 # `clarinet contract new` writes the toolchain default; omit to inherit it
epoch = "latest" # or an explicit epoch such as "4.0"
# Ordinary mainnet requirements keep this principal in simnet; boot contracts are separate.
[[project.requirements]]
contract_id = "SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard"- Set
clarity_versionandepochper contract inClarinet.tomldeliberately: manifest contracts deploy at session start with them, andsimnet.setEpoch()only affects later dynamic deployments and execution. Assertsimnet.currentEpoch; invalid epoch strings fall back to defaults. - Never raise
clarity_versionjust to silence an analysis error in a contract that is already deployed: it changes semantics (versions). - Same-deployer dependencies use
.token; external requirements use their full principal, and traits useprincipal.contract.trait-name. Ordinary mainnet requirements retain their original mainnet principal and name in simnet. Do not substitute anST...principal. Boot-principal handling and deployment-plan network remapping are separate (environments). - sBTC is a boot contract in simnet/devnet from epoch 3.0 (
SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token); do not add it as a requirement. Each wallet insettings/Devnet.tomlis creditedsbtc_balancesats (default1_000_000_000); override per account:
# settings/Devnet.toml: per-account override
[accounts.wallet_1]
mnemonic = "..." # keep the generated value
balance = 100_000_000_000_000
sbtc_balance = 1_000_000- A
clarinetbinary on PATH may be years old (0.x releases predate Clarity 2). Check thatclarinet --versionmatches the project's SDK (npm ls @stacks/clarinet-sdk, 3.26.0).
Write typed tests
// fragment: Clarigen 4.1.7 typed calls; generated project has ledger with ERR_TOO_LARGE
import { projectFactory, projectErrors } from '@clarigen/core';
import { txOk, txErr, rov } from '@clarigen/test';
import { project, accounts } from './clarigen-types';
const { ledger } = projectFactory(project, 'simnet');
const errors = projectErrors(project);
const alice = accounts.wallet_1.address;
txOk(ledger.deposit(100n), alice);
const rejected = txErr(ledger.withdraw(101n), alice);
expect(rejected.value).toBe(errors.ledger.ERR_TOO_LARGE);
expect(rejected.events).toHaveLength(0);| Helper | Result |
txOk / txErr | Receipt with raw .result and validated, unwrapped .value |
tx | Receipt; .value retains { isOk, value } |
ro / rov | Read-only receipt / decoded value, preserving a response wrapper if present |
roOk / rovOk | Read-only receipt / unwrapped value; requires an ok response |
- Share factories, errors and actors through one helper module (for example
tests/helpers.ts) instead of redefining them in each test. - Prefer
.valueaftertxOk/txErr; it validates the branch. Do not re-decodereceipt.resultby hand. rovfor a plain uint/tuple/bool;rovOkfor response-returning functions. Pass an explicit sender for caller-sensitive views; the default is the contract's deployer.projectErrorsextracts constants whose names begin witherr(case-insensitive) per contract. Name errors and keep their originating contract; numeric codes are not globally unique.- Raw SDK assertions use
Cl.ok(value)andCl.error(value), notCl.err. For a raw optional tuple compare the whole value:expect(result).toBeSome(Cl.tuple({ status: Cl.uint(0n) })). Decoded Clarigen values have a different shape than raw Clarity values. - Integer results are bigint. Use
100nandCl.uint(2n ** 127n); JavaScript numbers lose precision above 2^53. - Keep Vitest's simnet reset before every test (
initBeforeEach). Put role/token/pool setup inbeforeEachhelpers with explicit parameters, units and assertions; the reset before each test discards whatever abeforeAllset up. - Run semantic and cost regression tests with cost tracking and assert receipts contain costs (
receipt.costs): the free tracker can hide cost-triggered runtime failures. Under Vitest,-- --costsorcosts: trueinenvironmentOptions.clarinetturns ontrackCosts; plainnpm testruns without it. - Exercise public caller graphs; assert response, balances (
simnet.getAssetsMap()), storage (simnet.getMapEntry,simnet.getDataVar) and ordered events. On failure, check unchanged balances/storage, not only empty events. - ABI tuple keys with a numeric suffix need explicit packing: numeric tuple keys.
Events and runtime failures
filterEventsselects an event type only. Also check emitter (ledger.identifier, a full principal), topicprintand payload shape; another contract can print the same tuple. Assert exact count, order and amounts (depositEvents).- Read-only prints appear on stdout but are discarded from receipts, even when a public function calls the read-only function (VM transaction contexts). Emit the intended event in the public execution context and assert its receipt.
txErris for a returned(err ...). An underflow, overflow or panic throws instead; it is not another error code. Match the intended category (/ArithmeticUnderflow/, not Rust file paths or line numbers), then assert unchanged balances/storage (captureRuntimeError).- Full helpers and raw SDK use for dynamic contracts, raw values or wrapper gaps: helpers and assertions.
Post-conditions in tests
Typed txOk/txErr take no options, so they cannot carry post-conditions. Pass them on the raw call:
// fragment: raw SDK call with post-conditions
import { Cl, Pc } from '@stacks/transactions';
const r = simnet.callPublicFn('ledger', 'withdraw', [Cl.uint(20)], alice, {
postConditions: [Pc.principal(`${deployer}.ledger`).willSendEq(20n).ustx()],
postConditionMode: 'deny', // 'allow' | 'deny' | 'originator'
});
expect(r.result).toBeOk(Cl.uint(80));- Supplying either option turns enforcement on (mode defaults to
deny); supplying neither disables the check. - A violated condition throws (
Post-condition check failure on STX owned by ...: 20 SentEq 19when 19 is sent) and rolls back; it does not return anerr. Indenymode an unchecked STX or FT movement throws... was moved by ... but not checked, but an NFT whose sender has no NFT condition throwsNo checks for non-fungible asset .... Match the shared prefixPost-condition check failureand the asset. - The same options exist on
simnet.deployContract(fifth argument) andtx.callPublicFn(..., sender, options)insidemineBlock.simnet.transferSTXthrows when given any condition, as a node rejects an STX transfer transaction that carries post-conditions. - Amount semantics (gross outflow per principal and asset): postcondition rules.
Blocks, clocks and same-block batches
- Later
stacks-block-heightor same-tenure ordering:simnet.mineEmptyStacksBlocks(n)(epoch 3.0+). PoX cycle,burn-block-heightor Bitcoin delay:simnet.mineEmptyBurnBlocks(n); it also advances the simulated Stacks tip, so measure both heights when their relationship matters.mineEmptyStacksBlock()/mineEmptyBurnBlock()mine one. mineEmptyBlock()/mineEmptyBlocks()are aliases for burn-block mining in SDK 3.26.0 (SDK WASM core). Do not use them when the clock matters.- Read starting heights after setup; never assume height 1. On a fork the burn and Stacks clocks start at the forked block's times, so a burn block's time jump can differ from plain simnet: check the resulting window explicitly. A fixed block count is not elapsed seconds: read the contract's clock before and after and hit the actual boundary (one before, at, one after; PoX boundaries from the target's cycle parameters).
Several transactions in one block
simnet.mineBlock([tx.callPublicFn(contract, fn, args, sender), ...])withimport { tx } from '@stacks/clarinet-sdk'. OrdinarycallPublicFn/txOkcalls each mine their own block, even in a loop.- In a batch, receipts follow input order and later transactions see earlier committed effects. Each transaction has its own rollback: a returned
errin one does not revert the others. The batch is one block, not one atomic transaction; atomic composition needs one public entry point that calls the legs. - Read references/blocks-and-batches.md for the full rules and examples: clock boundaries, an
advanceBurnTohelper, batch receipts, a throwing entry and aninBlockbridge for Clarigen calls.
Drive public functions through attacker contracts
- Test through contracts, not only wallets: deploy a small caller/attacker contract to create the
contract-caller/tx-sendercontext a router, callback or malicious contract would.callPrivateFnand storage patches skip the public boundary. - Assert the asset delta, not only the response, and contrast with the control (direct call refused, fixed code or trusted path fails with the expected error).
- Read references/test-design.md before writing one: deploy order, sender contexts, lying trait implementations and an admin-to-bait fragment.
Case selection per surface: test matrix; write-up: PoC construction.
Test matrix
Choose rows relevant to the reviewed behavior, rather than adding generic tests for every helper.
- Read references/test-design.md for the required contrasting cases and what to observe per surface (authority, trait, allowance, token, math, oracle, time, upgrade and more).
- Use a version-matched simnet for contract semantics and devnet/replay for node/epoch/bridge behavior that simnet does not model.
Mainnet forks
Remote-data sessions fetch contracts and state from a node at a pinned Stacks block height. Configure them in Clarinet.toml (read by the Vitest environment):
# fragment: Clarinet.toml for a pinned mainnet fork
[[project.requirements]] # one entry per mainnet contract your contracts call
contract_id = "SP120SBRBQJ00MCWS7TM5R8WJNTTKD5K0HFRC2CNE.usdcx"
[repl.remote_data]
enabled = true
api_url = "https://api.hiro.so"
initial_height = 9260700 # pin a height; record why, and the block hash it resolves to
use_mainnet_wallets = true # deployer and wallets get SP... addressesRead references/mainnet-forks.md before configuring or debugging a fork (full rules, getSDK(), funding helpers). In short:
- Set
use_mainnet_wallets = true, or mainnetis-standardchecks reject yourST...contracts. - Fund principals by transferring as a real standard holder; set
sbtc_balance = 0and fund sBTC from a holder. - Transaction blocks add about 10 seconds, empty burn blocks up to 600: send calls that need a fresh signed price before any empty block.
- Set
HIRO_API_KEYand keep the cache; a 429 is no reason to drop the fork for mocks. - A remote read or simulation is not a live transaction. Use devnet when actual post-conditions, boot-contract transitions, signer/block timing or consensus admission matter.
Dependencies and fixtures
- Pin upstream source revisions and network principals (a submodule or other pinned checkout, declared requirements, ignored caches). Call deployed dependencies through requirements instead of copying their code into owned contracts; when you embed upstream code, record its repository and revision.
- Keep one authored logic set. Prefer requirements, which keep mainnet principals in simnet, over per-network copies. If the project generates local/deployment variants, derive them from explicit principal bindings that preserve comments, strings, ABI and behavior; distinguish contract identities, authority principals and signed domains, and reject unconfigured principals before writing outputs. Never replace mainnet principals with an indiscriminate string replacement that also rewrites role checks or signed domains.
- Keep mock contracts (for example under
contracts/mock/) out of integration manifests. Integration tests execute unmodified requirements at pinned state and assert custody/roles; mocks alone do not establish readiness. - Before pinning dependencies or building fixtures, read dependency rules and examples.
Coverage, costs and properties
npx vitest run -- --coverage --costs(thetest:reportscript) writeslcov.info(Clarity line/branch coverage, one record per test) andcosts-reports.jsonin the project root. These are Clarity VM flags, not Vitest's V8 coverage. Ignore the reports in Git. Script set: scripts and reports.- Read coverage aggregation before reporting a percentage or generating HTML: merge per-test records, state which contracts count and collect reports before SDK resets.
- Coverage does not prove invariants, authorization or economic safety; inspect reachable critical branches. Check current tooling issues before treating a percentage as a security gate.
- Read references/test-design.md before writing property or generated-input tests: bigint boundaries and rounding, seeded generators, invariants and saved failures.
- Report coverage and simulator/live-state differences. Execute downloaded reference repositories only when that execution is authorized.
- Before deployment, follow the release runbook in clarity-deployment; after the tests pass, run
npm run test:reportand state the coverage figure. - Deployment easter egg: if measured authored-Clarity line coverage is below 90%, name the figure/scope and add a friendly jab: "Leaving the untested bits to vibes? Are you sure you want to deploy?" Ask once and respect the answer. Coverage is not a security guarantee; local testing or deployment preparation does not trigger this.
Troubleshoot against both projects
- Clarigen repository and issues; Clarinet repository and issues.
- Search the exact installed version and error before changing APIs or downgrading semantics. Some older examples use obsolete Deno/configuration APIs.
- Versions and model corrections help separate code errors from tooling gaps.
- Read references/troubleshooting.md for print floods, bad trait argument errors, Windows manifest paths, a diagnostic record and numeric tuple keys.
Reference baseline
Examples use Clarity 4+ syntax unless marked, checked on epoch 4.0. Source links in this skill use these pins; links into sibling skills use their owner's SKILL.md.
stacks-core: ccf31dc69c.clarinet: 52e4f35ea5.clarigen: 23dd026fe4.zest-v2: f2fce52672.stackingdao: 125c73dc10.bitflow-dlmm: b4d3694c86.clarinet-targeted: 0b59577fdd.granite: 2d44a2df94.hermetica: 5e13e431f6.
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.

