git:20260211.d4c307e to git:20260314.f7d9a57

105 added, 324 removed. Audit A to A.

What this update changes in the checks

No check changed: every fixed check gives the same answer before and after this update.

A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.

---
name: cairo-testing
- description: Use when writing tests for Cairo smart contracts — snforge test structure, contract deployment in tests, cheatcodes, event testing, fuzzing, fork testing.
+ description: Cairo smart-contract testing with snforge. Trigger on "write tests", "add unit tests", "fuzz test", "integration test", "test this contract", "regression test". Guides test strategy, cheatcode usage, and coverage.
license: Apache-2.0
- metadata: {"author":"starknet-agentic","version":"1.0.0","org":"keep-starknet-strange"}
- keywords: [cairo, testing, snforge, starknet-foundry, fuzzing, cheatcodes, integration-tests, unit-tests]
+ metadata: {"author":"starknet-agentic","version":"0.2.0","org":"keep-starknet-strange","source":"starknet-skills"}
+ keywords: [cairo, testing, snforge, starknet-foundry, fuzzing, integration]
allowed-tools: [Bash, Read, Write, Glob, Grep, Task]
user-invocable: true
---
# Cairo Testing
- Reference for testing Cairo smart contracts with Starknet Foundry (snforge).
+ You are a Cairo testing assistant. Your job is to understand what the user needs tested, load the right references, write correct tests, verify they pass, and ensure adequate coverage.
## When to Use
- - Writing unit tests for Cairo contract functions
- - Writing integration tests that deploy and interact with contracts
- - Using cheatcodes to manipulate block state, caller, timestamps
- - Testing events are emitted correctly
- - Fuzzing contract inputs
- - Fork-testing against live Starknet state
-
- **Not for:** Contract structure (use cairo-contracts), optimization (use cairo-optimization), deployment (use cairo-deploy)
-
- ## Setup
-
- ### Scarb.toml
-
- ```toml
- [dev-dependencies]
- snforge_std = "0.56.0"
-
- [[target.starknet-contract]]
- sierra = true
- casm = true
- ```
-
- > **Note:** snforge 0.56.0 requires Scarb >= 2.12.0. Check [scarbs.dev/packages/snforge_std](https://scarbs.dev/packages/snforge_std) for the latest version.
-
- ### Running Tests
-
- ```bash
- # Run all tests
- snforge test
-
- # Run specific test by name
- snforge test test_transfer
-
- # Run tests matching a pattern
- snforge test test_erc20
-
- # Filter to a single test function (exact match)
- snforge test --exact test_erc20_transfer
-
- # Run with gas reporting
- snforge test --detailed-resources
- ```
-
- > **Tip:** Use `snforge test --filter <pattern>` or `snforge test <pattern>` to run a subset of tests during development. `--exact` matches the full test name when you need precision.
-
- ## Basic Test Structure
-
- ```cairo
- #[cfg(test)]
- mod tests {
- use super::MyContract;
- use starknet::ContractAddress;
- use starknet::contract_address_const;
-
- fn OWNER() -> ContractAddress {
- contract_address_const::<'OWNER'>()
- }
-
- fn USER() -> ContractAddress {
- contract_address_const::<'USER'>()
- }
-
- #[test]
- fn test_constructor() {
- let mut state = MyContract::contract_state_for_testing();
- MyContract::constructor(ref state, OWNER());
- assert(state.get_owner() == OWNER(), 'wrong owner');
- }
- }
- ```
-
- ## Contract Deployment in Tests
-
- For integration tests that need actual contract deployment:
-
- ```cairo
- use snforge_std::{declare, ContractClassTrait, DeclareResultTrait};
-
- fn deploy_contract() -> ContractAddress {
- let contract = declare("MyContract").unwrap().contract_class();
- let constructor_calldata = array![OWNER().into()];
- let (contract_address, _) = contract.deploy(@constructor_calldata).unwrap();
- contract_address
- }
-
- #[test]
- fn test_deployed_contract() {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
- assert(dispatcher.get_balance() == 0, 'initial balance should be 0');
- }
- ```
-
- ## Cheatcodes
-
- ### Caller Address
-
- ```cairo
- use snforge_std::{start_cheat_caller_address, stop_cheat_caller_address};
-
- #[test]
- fn test_only_owner() {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
-
- // Impersonate OWNER
- start_cheat_caller_address(contract_address, OWNER());
- dispatcher.owner_only_function(); // should succeed
- stop_cheat_caller_address(contract_address);
-
- // Impersonate USER — should fail
- start_cheat_caller_address(contract_address, USER());
- // This should panic
- }
- ```
-
- ### Block Timestamp
-
- ```cairo
- use snforge_std::{start_cheat_block_timestamp, stop_cheat_block_timestamp};
-
- #[test]
- fn test_time_locked() {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
-
- // Set block timestamp to future
- start_cheat_block_timestamp(contract_address, 1000000);
- dispatcher.time_sensitive_function();
- stop_cheat_block_timestamp(contract_address);
- }
- ```
-
- ### Block Number
-
- ```cairo
- use snforge_std::{start_cheat_block_number, stop_cheat_block_number};
-
- start_cheat_block_number(contract_address, 500);
- // ... test logic
- stop_cheat_block_number(contract_address);
- ```
-
- ### Sequencer Address
-
- ```cairo
- use snforge_std::{start_cheat_sequencer_address, stop_cheat_sequencer_address};
-
- start_cheat_sequencer_address(contract_address, sequencer);
- // ... test logic
- stop_cheat_sequencer_address(contract_address);
- ```
-
- ## Expected Failures
-
- ### Expected Panic
-
- ```cairo
- #[test]
- #[should_panic(expected: 'Caller is not the owner')]
- fn test_unauthorized_access() {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
-
- start_cheat_caller_address(contract_address, USER());
- dispatcher.owner_only_function(); // should panic
- }
- ```
-
- ### Expected Failure (any panic)
-
- ```cairo
- #[test]
- #[should_panic]
- fn test_overflow() {
- let dispatcher = IMyContractDispatcher { contract_address: deploy_contract() };
- dispatcher.function_that_overflows();
- }
- ```
-
- ## Event Testing
-
- ```cairo
- use snforge_std::{spy_events, EventSpyAssertionsTrait, EventSpyTrait};
+ - Writing unit, integration, fuzz, or fork tests for Cairo contracts.
+ - Designing regression tests for known findings.
+ - Validating event emission, failure semantics, or access control.
+ - Improving test coverage on an existing contract.
- #[test]
- fn test_transfer_emits_event() {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
+ ## When NOT to Use
- let mut spy = spy_events();
+ - Contract architecture decisions (`cairo-contract-authoring`).
+ - Performance tuning (`cairo-optimization`).
+ - Deployment operations (`cairo-deploy`).
+ - Security audit of existing code (`cairo-auditor`).
- start_cheat_caller_address(contract_address, OWNER());
- dispatcher.transfer(USER(), 100);
+ ## Quick Start
- spy.assert_emitted(@array![
- (
- contract_address,
- MyContract::Event::Transfer(
- MyContract::Transfer {
- from: OWNER(),
- to: USER(),
- amount: 100,
- }
- )
- )
- ]);
- }
- ```
+ 1. Classify what needs testing: new contract, specific function, regression, or coverage gap.
+ 2. Load references based on test type — see the table in [Orchestration](#orchestration).
+ 3. Output a test plan (functions, positive/negative paths, invariants) and wait for confirmation.
+ 4. Implement tests following snforge patterns, then run `snforge test`.
+ 5. Verify coverage: every external tested? auth paths? negative cases? events?
+ 6. Emit a handoff block using `../references/skill-handoff.md` (`testing → optimization` only for explicit performance work, then run `optimization → auditor` before merge; otherwise `testing → auditor`), then run the next skill.
- ### Checking Event Count
+ ## Rationalizations to Reject
- ```cairo
- #[test]
- fn test_event_count() {
- let mut spy = spy_events();
+ - "We only need happy-path tests."
+ - "Access control tests are unnecessary — the contract handles it."
+ - "Fuzz tests are overkill for this contract."
+ - "We'll add regression tests after the next audit."
- // ... trigger events
+ ## Mode Selection
- let events = spy.get_events();
- assert(events.events.len() == 2, 'expected 2 events');
- }
- ```
+ - **unit**: Test individual functions using `contract_state_for_testing()`. No deployment needed.
+ - **integration**: Test deployed contracts via dispatchers. Multi-contract interactions.
+ - **fuzz**: Property-based tests with `#[fuzzer]` for arithmetic, bounds, invariants.
+ - **fork**: Test against live Starknet state with `#[fork]`.
+ - **regression**: Turn a known finding into a failing-before/fixed-after test pair.
- ## Fuzzing
+ ## Orchestration
- ```cairo
- #[test]
- #[fuzzer(runs: 256, seed: 12345)]
- fn test_deposit_any_amount(amount: u256) {
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
+ **Turn 1 — Understand.** Classify the request:
- // Fund the user first (if needed)
- start_cheat_caller_address(contract_address, USER());
- dispatcher.deposit(amount);
+ (a) Determine mode: `unit`, `integration`, `fuzz`, `fork`, or `regression`.
- assert(dispatcher.get_balance(USER()) == amount, 'balance mismatch');
- }
- ```
+ (b) Read the contract under test. Use Glob to find `.cairo` files, then Read to inspect them. Identify:
+ - All storage-mutating `#[abi(embed_v0)]` impl functions and `#[external(v0)]` functions (these must be tested).
+ - Storage fields and their types.
+ - Events that should be emitted.
+ - Access control patterns (owner checks, role checks).
- ### Bounded Fuzzing
+ (c) Check for existing tests. Use Glob to find `tests/` directories and test files.
- Use `assume` to constrain fuzz inputs:
+ (d) Load references based on what's needed:
- ```cairo
- #[test]
- #[fuzzer(runs: 100)]
- fn test_transfer_bounded(amount: u256) {
- // Skip values that would overflow
- if amount == 0 || amount > 1000000 {
- return;
- }
+ | Request involves | Load reference |
+ |-----------------|---------------|
+ | Basic test structure, deployment, assertions | `{skill_dir}/references/legacy-full.md` (Basic Test Structure, Contract Deployment) |
+ | Cheatcodes (caller, timestamp, block number) | `{skill_dir}/references/legacy-full.md` (Cheatcodes section) |
+ | Event testing, spy_events | `{skill_dir}/references/legacy-full.md` (Event Testing section) |
+ | Fuzz / property tests | `{skill_dir}/references/legacy-full.md` (Fuzzing section) |
+ | Fork testing against mainnet | `{skill_dir}/references/legacy-full.md` (Fork Testing section) |
+ | Security regression recipes | `../../datasets/distilled/test-recipes/` |
- let contract_address = deploy_contract();
- let dispatcher = IMyContractDispatcher { contract_address };
+ Where `{skill_dir}` is the directory containing this SKILL.md. Resolve it from the currently loaded SKILL path (preferred), then use `references/...` relative paths from that directory.
- start_cheat_caller_address(contract_address, OWNER());
- dispatcher.transfer(USER(), amount);
- }
- ```
+ **Turn 2 — Plan.** Before writing any test code, output a brief plan:
- ## Fork Testing
+ 1. **Functions to test** — list each external function and whether it gets a positive test, negative test, or both.
+ 2. **Access control tests** — for each guarded function, test: authorized caller succeeds, unauthorized caller reverts.
+ 3. **Event tests** — list events that should be verified with `spy_events`.
+ 4. **Edge cases** — zero values, max values, duplicate calls, reentrancy attempts.
+ 5. **Fuzz targets** — identify functions with numeric inputs that should get `#[fuzzer]` tests.
+ 6. **Regression tests** — if fixing a known finding, describe the failing-before scenario.
- Test against live Starknet state:
+ Keep the plan under 30 lines. Wait for user confirmation before implementing.
- ```cairo
- use snforge_std::BlockTag;
+ **Turn 3 — Implement.** Write tests following these rules:
- #[test]
- #[fork(url: "https://starknet-mainnet.g.alchemy.com/v2/YOUR_KEY", block_tag: latest)]
- fn test_against_mainnet() {
- let usdc_address = contract_address_const::<0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8>();
- let dispatcher = IERC20Dispatcher { contract_address: usdc_address };
+ *Structure rules:*
+ - Use `#[cfg(test)] mod tests { ... }` for unit tests in the same file, or separate `tests/` directory for integration tests.
+ - Create a shared `helpers` module for `deploy_contract()`, address constants (`OWNER()`, `USER()`, `ZERO()`).
+ - Name tests descriptively: `test_<function>_<scenario>` (e.g., `test_transfer_non_owner_rejected`).
- let supply = dispatcher.total_supply();
- assert(supply > 0, 'USDC should have supply');
- }
- ```
+ *Coverage rules (mandatory):*
+ - Every storage-mutating `#[abi(embed_v0)]` impl function and `#[external(v0)]` function MUST have both a success test and a revert test.
+ - Every access-controlled function MUST be tested with: (1) authorized caller succeeds, (2) unauthorized caller panics with expected message.
+ - Constructor MUST be tested: correct initial state, zero-address rejection.
+ - Every event-emitting function MUST verify the event with `spy_events` + `assert_emitted`.
- ### Fork with Specific Block
+ *Cheatcode rules:*
+ - Use `start_cheat_caller_address` / `stop_cheat_caller_address` to impersonate callers.
+ - Use `start_cheat_block_timestamp` for timelock tests — never hardcode timestamps.
+ - Always call the matching `stop_cheat_*` after assertions to avoid leaking state.
- ```cairo
- #[test]
- #[fork(url: "https://starknet-mainnet.g.alchemy.com/v2/YOUR_KEY", block_number: 500000)]
- fn test_at_specific_block() {
- // ... test against historical state
- }
- ```
+ *Fuzz rules:*
+ - Use `#[fuzzer(runs: 256, seed: 12345)]` with a fixed seed for reproducibility.
+ - Constrain inputs with guard clauses or bounded types, not by ignoring invalid inputs.
- ## Multi-Contract Tests
+ After writing tests, run `snforge test` to verify they pass. If any fail, fix and re-run.
- ```cairo
- fn setup() -> (ContractAddress, ContractAddress) {
- // Deploy token
- let token_class = declare("ERC20Token").unwrap().contract_class();
- let (token_addr, _) = token_class.deploy(@array![
- 'MyToken'.into(), 'MTK'.into(), OWNER().into()
- ]).unwrap();
+ **Turn 4 — Verify.** After tests pass:
- // Deploy AMM that uses the token
- let amm_class = declare("AMM").unwrap().contract_class();
- let (amm_addr, _) = amm_class.deploy(@array![token_addr.into()]).unwrap();
+ (a) Coverage checklist — mentally walk through every external function:
+ - Has a success-path test?
+ - Has a failure-path test (wrong caller, bad input, overflow)?
+ - Emits correct events?
+ - Fuzz target if numeric inputs?
- (token_addr, amm_addr)
- }
+ (b) Report any untested functions or missing edge cases to the user.
- #[test]
- fn test_amm_swap() {
- let (token_addr, amm_addr) = setup();
- let token = IERC20Dispatcher { contract_address: token_addr };
- let amm = IAMMDispatcher { contract_address: amm_addr };
+ (c) If the user's project uses `cairo-auditor`, suggest running it to find additional test targets.
- // Approve AMM to spend tokens
- start_cheat_caller_address(token_addr, OWNER());
- token.approve(amm_addr, 1000);
+ (d) Suggest next steps:
+ - "Run `cairo-auditor` for a security review — it may surface additional test cases."
+ - "Consider adding fork tests if this contract interacts with deployed protocols."
- // Execute swap
- start_cheat_caller_address(amm_addr, OWNER());
- amm.swap(token_addr, 100);
- }
- ```
+ ## Security-Critical Rules
- ## Test Organization
+ These are non-negotiable. Every test suite you write must satisfy all of them:
- ```
- tests/
- test_unit.cairo # unit tests (contract_state_for_testing)
- test_integration.cairo # integration tests (deploy + dispatch)
- test_fuzz.cairo # fuzz tests
- helpers.cairo # shared setup, deploy helpers, constants
- ```
+ 1. Every storage-mutating external function has both a positive and negative test.
+ 2. Every access-controlled function is tested with authorized and unauthorized callers.
+ 3. Expected panic messages are asserted with `#[should_panic(expected: '...')]` — not bare `#[should_panic]`.
+ 4. Event assertions use `spy_events` + `assert_emitted` with full event data — not just event count.
+ 5. Fuzz tests use fixed seeds for reproducibility.
- ### Shared Helpers Module
+ ## References
- ```cairo
- // tests/helpers.cairo
- use starknet::ContractAddress;
- use starknet::contract_address_const;
+ - Testing patterns and snforge API: [legacy-full.md](references/legacy-full.md)
+ - Cross-skill handoff format: `../references/skill-handoff.md`
+ - Module index: [references/README.md](references/README.md)
+ - Security regression recipes: `../../datasets/distilled/test-recipes/`
- fn OWNER() -> ContractAddress { contract_address_const::<'OWNER'>() }
- fn USER() -> ContractAddress { contract_address_const::<'USER'>() }
- fn ZERO() -> ContractAddress { contract_address_const::<0>() }
+ ## Workflow
- fn deploy_my_contract() -> ContractAddress {
- let contract = declare("MyContract").unwrap().contract_class();
- let (addr, _) = contract.deploy(@array![OWNER().into()]).unwrap();
- addr
- }
- ```
+ - Main testing flow: [default workflow](workflows/default.md)
- ## Gas Reporting
+ ## Eval Gate
- ```bash
- # Show gas usage per test
- snforge test --detailed-resources
+ When testing/security rules in this skill or its references change, update at least one case in:
- # Compare gas between runs (save output, diff manually)
- snforge test --detailed-resources > gas-report.txt
- ```
+ - `evals/cases/contract_skill_benchmark.jsonl`
+ - `evals/cases/contract_skill_generation_eval.jsonl`