agentleFS
cybasecuritycybasecurity/clarity-skills/skills/clarity-auditor/SKILL.md

clarity-auditor

Skill2 starsChanged 31 days agoMITView on GitHub

Audit or security-review Clarity contracts: threat model, Clarity-specific checks, simnet PoC exploits, severity and findings. Use for any request to review, audit or find issues in .clar code.

The file

We split this skill into the rules it gives an agent

11 rules. About 0 are common, 8 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every <trait> argument: is (contract-of t) compared to a stored or constant principal for that role?

    line 29
  2. Distinctive:

    Use the test matrix and the proof-of-concept steps.

    line 63
  3. Distinctive:

    Use a reachable transaction sequence to demonstrate runtime impact whenever the target can be simulated.

    line 81
  4. Distinctive:

    Run PoCs only in a project you are authorized to execute (the user's own repository or a scratch copy).

    line 83
  5. Distinctive:

    When tool behavior differs, check the current Clarigen and Clarinet issue trackers.

    line 85
  6. Distinctive:

    Contrast: run the same sequence against the fixed code (or the intended trusted path) and show it fails with the expected error.

    line 92
  7. Very specific:

    Use [[project.requirements]] to pull the real deployed contracts (SIP traits, a protocol's deployed contract.

    line 126
  8. Distinctive:

    When a dependency needs off-chain inputs (Pyth/Lazer signed payloads, Bitcoin proofs), use the protocol's own test fixtures and a test …

    line 127
  9. Distinctive:

    Keep the PoC minimal: one attacker contract and the fewest steps that show the impact.

    line 133
  10. Distinctive:

    Use the severity scale and report format the engagement specifies (contest rules, a bug-bounty table, the client's template).

    line 137
  11. Very specific:

    Never mechanically replace tx-sender, remove context scopes, ban traits or add is-standard everywhere.

    line 160

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Clarity Auditor

Establish reachable impact and affected versions; historical findings are hypotheses for the current target. Load only the relevant pattern families.

Key distinctions

  • Recursion protection tracks active functions; callbacks into another function of an active contract can execute.
  • Native FT/NFT primitives check assets and balances, not permission to act for the owner.
  • A trait argument proves only that the called method has the trait's signature. It proves no approved role or trusted code: check the role's allowlist and the deployed source.
  • Private err does not itself roll back writes. A caller handling a public callee's error can commit its own state.
  • Source submitted in a failed deployment is not the code deployed at that principal.

Clarity pass (run on every target; record file:line or "none")

Each line: what to look for -> pattern. Load clarity-security with this skill: each ID below links to its entry in the security patterns.

  1. tx-sender in authorization checks on privileged paths -> A01; contract roles compare contract-caller, except setters reached through an ExecutorDAO-style proposal, where tx-sender = the DAO is the intended check.
  2. as-contract, as-contract?, restrict-assets?, with-all-assets-unsafe, wildcard or oversized allowances around a caller-supplied <trait> call -> A03, A04.
  3. Every <trait> argument: is (contract-of t) compared to a stored or constant principal for that role? -> A02.
  4. Public paths reaching ft-transfer?, nft-transfer?, ft-burn?, nft-burn? (no sender check in the VM) -> owner check present? native assets.
  5. stx-transfer?/ft-transfer?/ft-mint? under try! where the amount can be 0 (fee rounding, last repayment) or sender equals recipient -> A27.
  6. let bindings with /, -, unwrap-panic or a contract call that precede an asserts!; values read before a state change -> A28.
  7. map, fold, filter over responses; asserts!/unwrap! thrown values of (ok ...) -> A18.
  8. (/ (* a b) d), pow, ceil division (/ (+ n (- d u1)) d), rounding direction -> A11. Share mint amount * supply / assets with a 1:1 empty-vault branch and a live-balance assets -> A29.
  9. get-balance, stx-get-balance, wSTX or sBTC balance used as liquidity -> A08, A09.
  10. block-height, burn-block-height, block time, at-block comparisons -> A10.
  11. print consumed off-chain or by a bridge -> A16. Forwarded (err uN) -> A17.
  12. PoX/staking calls and allowances -> A20, A21.
  13. Any approved deployed address -> A05. Network principals, initializers -> A06, A07.
  14. Worst-case list sizes, trait callback chains, exits at maximum state -> A19.
  15. Batch payouts, caches, packed registries -> A24, A25, A26.
  16. Receipt or wrapper tokens counted as collateral, balances read inside a flash-loan callback -> A12, A13.
  17. Oracle prices and timestamps, slice? and (buff N) parsing -> A14, A15.
  18. Withdrawal requests, Bitcoin txids and outpoints -> A22, A23.

Solidity reflexes that are not findings in Clarity

ReflexIn ClarityCheck instead
ReentrancyThe VM blocks active-function recursion; a missing lock is not a finding by itselfA different function reachable from a callback and the invariant it breaks (callback guards)
Integer overflow wrapsOverflow, underflow and / 0 abort the transactionIntermediates that make valid users abort (A11); guard order (A28)
Unchecked return valueThe analyzer rejects an unchecked response in beginResponses dropped by map/fold, (ok ...) thrown by asserts! (A18)
tx.origin is bad, msg.sender is goodtx-sender is the origin-like value and is the one that is forwardedtx-sender vs contract-caller per path (A01)
selfdestruct, proxies, delegatecallNone existRegistry or role swaps that replace code in effect (upgrades)
Uninitialized storageA var gets its initial value at definition; a missing map key reads as nonedefault-to hiding "never registered" (pitfalls)

Review

  • Record language version, executing epoch, tool support, deployment and source revision. Inventory public entry points, dynamic traits, privileged state, native assets and print consumers.
  • Trace authority, allowances, callbacks and transient balances to committed effects; check earlier aborts and the rollback boundary before claiming persistence. Call the target through an attacker contract or router, not only directly from a wallet.
  • Asset postconditions do not protect arbitrary state (listings, approvals, roles); assert state, events and balances. Mocks prove only modeled behavior.
  • Also review state/cache/registry invariants, position discovery and valuation for liquidators/indexers, and, for upgrades, cutover, legacy claims and timelock bypasses.
  • Use the test matrix and the proof-of-concept steps. Check exact SIP clauses separately; a security recommendation is not a normative requirement.
  • Separate confirmed issues, hypotheses, fixed history, accepted trust, style and recommendations. Reassess historical severity for this target.

Finding template (the default; follow a format the engagement requests):

### <ID>: <title>
Severity: <Likelihood x Impact per matrix> | Status: confirmed / hypothesis / fixed-history
Root cause: <file:line, commit/version, language version, epoch>
Preconditions: <who calls what, state required>
PoC: <test name, call sequence, observed delta>
Impact: <assets or state, who is hurt>
Fix: <change preserving the intended authority model>; regression test <name>
Assumptions: <unresolved>

Proof of concept

  • Use a reachable transaction sequence to demonstrate runtime impact whenever the target can be simulated. A static proof or compiler rejection can establish other findings; state that evidence and any simulation limitation.
  • Caller/trait/allowance findings often need a contract in the middle (an attacker contract, router, or malicious implementation), because a direct wallet call does not exercise the disputed boundary.
  • Run PoCs only in a project you are authorized to execute (the user's own repository or a scratch copy). Do not install or run dependencies of a repository downloaded only for reading.
  • Harness: default to Clarigen for the target protocol's generated calls and response assertions. To deploy attacker variants dynamically without regenerating types (or in projects without Clarigen), use the raw SDK: initSimnet('Clarinet.toml') (in a vitest-environment-clarinet project use the global simnet), simnet.setEpoch('4.0') for a scratch run (a project manifest normally pins it), an attacker account from simnet.getAccounts().get('wallet_2'), simnet.deployContract(name, source, { clarityVersion: 4 }, attacker). A standalone script runs as node poc.mjs next to a Clarinet.toml and a settings/Devnet.toml that defines the deployer and wallet accounts. It needs @stacks/clarinet-sdk and @stacks/transactions, prints a line on success and throws on any failed assertion.
  • When tool behavior differs, check the current Clarigen and Clarinet issue trackers.

Steps for every PoC:

  1. Arrange real state through public functions (deposits, borrows, oracle updates), not callPrivateFn or direct storage edits. Move clocks with mineEmptyStacksBlocks/mineEmptyBurnBlocks. Deploy the target before any contract whose analysis references it.
  2. Act through the contract graph the attacker can actually build: deploy the attacker/malicious-trait contract from the attacker's account, then have the right principal call it (victim, admin, keeper).
  3. Assert the impact in assets (getAssetsMap), storage (getMapEntry, getDataVar) and events. A wrong return value alone is not impact.
  4. Contrast: run the same sequence against the fixed code (or the intended trusted path) and show it fails with the expected error. Include a control showing the attacker cannot do it directly.
// fragment: A01 PoC. VAULT's withdraw-to checks (is-eq tx-sender ADMIN), then pays inside as-contract?.
const BAIT = `(define-public (claim-airdrop)
  (contract-call? '${admin}.vault withdraw-to u1000000 '${attacker}))`;
simnet.deployContract('vault', VAULT, { clarityVersion: 4 }, admin);
simnet.deployContract('bait', BAIT, { clarityVersion: 4 }, attacker); // after the vault, from the attacker
// Control (after the admin deposited): the attacker cannot withdraw directly.
assert.deepEqual(simnet.callPublicFn(`${admin}.vault`, 'withdraw-to',
  [Cl.uint(1_000_000), Cl.principal(attacker)], attacker).result, Cl.error(Cl.uint(100)));
// Act: the admin calls the untrusted contract. Assert the asset delta, not only the response.
const stx = (who) => simnet.getAssetsMap().get('STX').get(who);
const before = stx(attacker);
const r = simnet.callPublicFn(`${attacker}.bait`, 'claim-airdrop', [], admin);
assert.deepEqual(r.result, Cl.ok(Cl.bool(true)));
assert.equal(stx(attacker) - before, 1_000_000n);

Building blocks

NeedConstruct
Malicious trait implementationDeploy a contract with the trait's exact signatures that lies: get-balance returns a huge number, transfer returns (ok true) without moving anything, a callback re-enters a different function of the target.
Context switchClarity 4 attacker: (as-contract? ((with-all-assets-unsafe)) (try! (contract-call? ...))) makes the attacker contract itself the tx-sender. Legacy targets: deploy the attacker with clarityVersion: 3 and use as-contract.
Victim calls attackercallPublicFn('<attacker>.bait', ..., victim): the attacker contract now runs with tx-sender = victim.
Same-block conditionsSeveral callPublicFn calls without mining run in successive blocks in simnet; simnet.mineBlock([tx.callPublicFn(...), ...]) puts calls in one block.
TimemineEmptyStacksBlocks(n) advances Stacks height only (epoch 3.0+); mineEmptyBurnBlocks(n) advances burn height and the simulated Stacks tip. mineEmptyBlocks aliases burn-block mining in SDK 3.26.0.
Big numbersCl.uint(2n ** 127n); SDK 3.26.0 runtime failures can throw for both public and read-only calls. Capture the specific VM category and verify rollback; a node receipt represents the abort differently. See runtime assertions.
Event spoofingDeploy an unrelated contract that prints the same tuple shape and show the consumer cannot tell them apart without checking the emitter.
Costs / DoSinitSimnet(manifest, true, { trackCosts: true, trackCoverage: false }) and inspect receipt.costs.total against the active tenure budget (simnet's receipt.costs.limit shows older read limits) and the target miner's block policy (resource limits).

Real dependencies

  • Use [[project.requirements]] to pull the real deployed contracts (SIP traits, a protocol's deployed contract; sbtc-token is already a simnet boot contract) into simnet instead of hand-written mocks, so the authorization and asset semantics are the real ones. Seed protocol state through its public functions.
  • When a dependency needs off-chain inputs (Pyth/Lazer signed payloads, Bitcoin proofs), use the protocol's own test fixtures and a test signer, and say so in the report.
  • Mock PoCs establish only adapter behavior.

Writing it up

  • State the Clarity version and epoch of the run, the SDK version, the exact call sequence (who calls what, through which contract), the observed asset/state delta, and the contrasting failing run.
  • Keep the PoC minimal: one attacker contract and the fewest steps that show the impact.

Risk classification

Use the severity scale and report format the engagement specifies (contest rules, a bug-bounty table, the client's template). Without one, use this matrix and the template above.

  • Rate demonstrated impact and realistic likelihood separately; state the assumptions supporting each.
Likelihood / ImpactHighMediumLow
HighCriticalHighMedium
MediumHighMediumLow
LowMediumLowLow
  • Impact: High = significant asset loss or harm to a group of users; Medium = small funds loss or affected protocol functionality; Low = less critical unexpected behavior.
  • Likelihood: High = direct attack with low cost relative to damage; Medium = conditionally incentivized but reasonably likely; Low = many/unlikely assumptions or little/no incentive.
  • Actions: Critical/High must fix; Medium should fix; Low could fix.
  • Informational: style, operations, cost, documentation, standards or design recommendations with minimal functional/security impact. Review them, but classify any demonstrated vulnerability by the engagement's scale (this matrix by default).

Read when needed

  • Native behavior pitfalls: native assets, responses, serialization and cryptography.
  • Signed authorizations: high-S, recovery IDs, signer binding and replay; require reachable impact before classifying malleability as a vulnerability.
  • Bitcoin bridge boundaries: UTXO reservations, accepted script encodings, NFT identity and cross-chain rejection costs.
  • Versions: activation and historical bugs.
  • Recall corrections: common model errors.
  • python3 <skills>/clarity-scholar/scripts/lookup_function.py 'as-contract?' (<skills> is the directory holding the skill folders): retrieve one exact entry; cross-check current VM behavior.
  • Never mechanically replace tx-sender, remove context scopes, ban traits or add is-standard everywhere; preserve the intended authority model.
  • For requested stateful/property fuzzing, use Rendezvous guidance; require exercised checks and a reachable clean-state reproduction.

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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.