git:20260211.eda31a6 to git:20260314.f7d9a57

103 added, 399 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-optimization
- description: Use as an explicit post-test optimization pass — fixing slow loops, expensive arithmetic, integer splitting or limb assembly, modular reduction, storage slot packing, or BoundedInt type bounds. Invoke after implementation and tests pass.
+ description: Improves Cairo performance after correctness is established. Trigger on "optimize", "gas usage", "reduce steps", "profile", "BoundedInt", "storage packing", "benchmark". Guides profiling, arithmetic optimization, and bounded-int hardening.
license: Apache-2.0
- metadata: {"author":"feltroidprime","contributors":["starknet-agentic"],"version":"1.1.0","org":"keep-starknet-strange","upstream":"https://github.com/feltroidprime/cairo-skills/tree/main/skills/cairo-coding"}
- keywords: [cairo, optimization, gas, bounded-int, storage-packing, arithmetic, starknet, smart-contracts, performance, garaga]
+ metadata: {"author":"feltroidprime","contributors":["starknet-agentic"],"version":"1.3.0","org":"keep-starknet-strange","upstream":"https://github.com/feltroidprime/cairo-skills","upstream_commit":"7fde29f","sync_date":"2026-03-08","upstream_paths":["skills/cairo-coding","skills/benchmarking-cairo"],"permission_ref":"maintainer-confirmed-2026-03-08"}
+ keywords: [cairo, optimization, profiling, benchmarking, gas, bounded-int, storage-packing, arithmetic, starknet]
allowed-tools: [Bash, Read, Write, Glob, Grep, Task]
user-invocable: true
---
- # Coding Cairo
-
- Rules and patterns for writing efficient Cairo code. Sourced from audit findings and production profiling.
+ # Cairo Optimization
- > **Attribution:** Originally authored by [feltroidprime](https://github.com/feltroidprime) ([cairo-skills](https://github.com/feltroidprime/cairo-skills)). Integrated with permission into starknet-agentic.
+ You are a Cairo optimization assistant. Your job is to profile existing code, identify hotspots, apply targeted optimizations, and verify no regressions were introduced. Apply only after tests pass and behavior is locked.
## When to Use
- - Implementing arithmetic (modular, parity checks, quotient/remainder)
- - Optimizing loops (slow iteration, repeated `.len()` calls, index-based access)
- - Splitting or assembling integer limbs (u256 → u128, u32s → u128, felt252 → u96)
- - Packing struct fields into storage slots
- - Using `BoundedInt` for zero-overhead arithmetic with compile-time bounds
- - Choosing integer types (u128 vs u256, BoundedInt vs native types)
-
- **Not for:** Profiling/benchmarking (use benchmarking-cairo if available)
-
- ## Quick Reference — All Rules
-
- | # | Rule | Instead of | Use |
- |---|------|-----------|-----|
- | 1 | Combined quotient+remainder | `x / m` + `x % m` | `DivRem::div_rem(x, m)` |
- | 2 | Cheap loop conditions | `while i < n` | `while i != n` |
- | 3 | Constant powers of 2 | `2_u32.pow(k)` | `match`-based lookup table |
- | 4 | Pointer-based iteration | `*data.at(i)` in index loop | `pop_front` / `for` / `multi_pop_front` |
- | 5 | Cache array length | `.len()` in loop condition | `let n = data.len();` before loop |
- | 6 | Pointer-based slicing | Manual loop extraction | `span.slice(start, length)` |
- | 7 | Cheap parity/halving | `index & 1`, `index / 2` | `DivRem::div_rem(index, 2)` |
- | 8 | Smallest integer type | `u256` when range < 2^128 | `u128` (type encodes constraint) |
- | 9 | Storage slot packing | One slot per field | `StorePacking` trait |
- | 10 | BoundedInt for limbs | Bitwise ops / raw u128 math | `bounded_int::{div_rem, mul, add}` |
- | 11 | Fast 2-input Poseidon | `poseidon_hash_span([x,y])` | `hades_permutation(x, y, 2)` |
-
- ## Always / Never Rules
-
- ### 1. Always use `DivRem::div_rem` — never separate `%` and `/`
-
- Cairo computes quotient and remainder in a single operation. Using both `%` and `/` on the same value doubles the cost.
-
- ```cairo
- // BAD
- let q = x / m;
- let r = x % m;
-
- // GOOD
- let (q, r) = DivRem::div_rem(x, m);
- ```
-
- ### 2. Never use `<` or `>` in while loop conditions — use `!=`
-
- Equality checks are cheaper than comparisons in Cairo.
-
- ```cairo
- // BAD
- while i < n { ... i += 1; }
-
- // GOOD
- while i != n { ... i += 1; }
- ```
-
- ### 3. Never compute `2^k` with `pow()` — use a lookup table
-
- `u32::pow()` is expensive. Use a `match` lookup for known ranges.
-
- ```cairo
- // BAD
- let p = 2_u32.pow(depth.into());
-
- // GOOD — match-based lookup
- fn pow2(n: u32) -> u32 {
- match n {
- 0 => 1, 1 => 2, 2 => 4, 3 => 8, 4 => 16, 5 => 32,
- 6 => 64, 7 => 128, 8 => 256, 9 => 512, 10 => 1024,
- // extend as needed
- _ => core::panic_with_felt252('pow2 out of range'),
- }
- }
- ```
-
- ### 4. Always iterate arrays with `pop_front` / `for` / `multi_pop_front` — never index-loop
-
- Index-based access (`array.at(i)`) is more expensive than pointer-based iteration.
-
- ```cairo
- // BAD
- let mut i = 0;
- while i != data.len() {
- let val = *data.at(i);
- i += 1;
- }
-
- // GOOD — pop_front
- while let Option::Some(val) = data.pop_front() { ... }
-
- // GOOD — for loop (equivalent)
- for val in data { ... }
-
- // GOOD — batch iteration
- while let Option::Some(chunk) = data.multi_pop_front::<4>() { ... }
- ```
-
- ### 5. Never call `.len()` inside a loop condition — cache it
-
- `.len()` recomputes every iteration. Store it once.
-
- ```cairo
- // BAD
- while i != data.len() { ... i += 1; }
-
- // GOOD
- let n = data.len();
- while i != n { ... i += 1; }
- ```
-
- ### 6. Always use `span.slice()` instead of manual loop extraction
-
- `slice()` manipulates pointers directly — no element-by-element copying.
-
- ```cairo
- // BAD
- let mut result: Array = array![];
- let mut i = 0;
- while i != length {
- result.append(*data.at(start + i));
- i += 1;
- }
-
- // GOOD
- let result = data.slice(start, length);
- ```
-
- ### 7. Always use `DivRem` for parity checks — never use bitwise ops
-
- Bitwise AND is more expensive than `div_rem` in Cairo. Use `DivRem::div_rem(x, 2)` to get both the halved value and parity in one operation.
-
- ```cairo
- // BAD
- let is_odd = (index & 1) == 1;
- index = index / 2;
-
- // GOOD
- let (q, r) = DivRem::div_rem(index, 2);
- if r == 1 { /* odd branch */ }
- index = q;
- ```
-
- ### 8. Always use the smallest integer type that fits the value range
-
- `u128` instead of `u256` when the range is known. Adds clarity, prevents intermediate overflow.
-
- ```cairo
- // BAD — u256 for a value known to be < 2^128
- fn deposit(value: u256) { assert(value < MAX_U128, '...'); ... }
-
- // GOOD — type encodes the constraint
- fn deposit(value: u128) { ... }
- ```
-
- ### 9. Always use `StorePacking` to pack small fields into one storage slot
-
- Multiple small fields (basis points, flags, bounded amounts) can share a single `felt252` slot.
-
- ```cairo
- use starknet::storage_access::StorePacking;
-
- const POW_2_128: felt252 = 0x100000000000000000000000000000000;
-
- impl MyStorePacking of StorePacking<MyStruct, felt252> {
- fn pack(value: MyStruct) -> felt252 {
- value.amount.into() + value.fee_bps.into() * POW_2_128
- }
- fn unpack(value: felt252) -> MyStruct {
- let u256 { low, high } = value.into();
- MyStruct { amount: low, fee_bps: high.try_into().unwrap() }
- }
- }
- ```
-
- ### 10. Always use BoundedInt for byte cutting, limb assembly, and type conversions
-
- Never use bitwise ops (`&`, `|`, shifts) or raw `u128`/`u256` arithmetic for splitting or combining integer limbs. Use `bounded_int::div_rem` to extract parts and `bounded_int::mul` + `bounded_int::add` to assemble them. BoundedInt tracks bounds at compile time, eliminating overflow checks.
-
- **Assembling limbs** (e.g., 4 x u32 → u128):
-
- ```cairo
- // BAD — direct u128 arithmetic (28,340 gas)
- fn u32s_to_u128(d0: u32, d1: u32, d2: u32, d3: u32) -> u128 {
- d0.into() + d1.into() * POW_2_32 + d2.into() * POW_2_64 + d3.into() * POW_2_96
- }
-
- // GOOD — BoundedInt (13,840 gas, 2x faster)
- fn u32s_to_u128(d0: u32, d1: u32, d2: u32, d3: u32) -> u128 {
- let d0_bi: u32_bi = upcast(d0);
- let d1_bi: u32_bi = upcast(d1);
- let d2_bi: u32_bi = upcast(d2);
- let d3_bi: u32_bi = upcast(d3);
- let r: u128_bi = add(add(add(d0_bi, mul(d1_bi, POW_32_UI)), mul(d2_bi, POW_64_UI)), mul(d3_bi, POW_96_UI));
- upcast(r)
- }
- ```
-
- **Splitting values** (e.g., felt252 → two u96 limbs):
-
- ```cairo
- // GOOD — div_rem to split, mul+add to reassemble
- fn felt252_to_two_u96(value: felt252) -> (u96, u96) {
- match u128s_from_felt252(value) {
- U128sFromFelt252Result::Narrow(low) => {
- let (hi32, lo96) = bounded_int::div_rem(low, NZ_POW96_TYPED);
- (lo96, upcast(hi32))
- },
- U128sFromFelt252Result::Wide((high, low)) => {
- let (lo_hi32, lo96) = bounded_int::div_rem(low, NZ_POW96_TYPED);
- let hi64: BoundedInt<0, { POW64 - 1 }> = downcast(high).unwrap();
- (lo96, bounded_int::add(bounded_int::mul(hi64, POW32_TYPED), lo_hi32))
- },
- }
- }
- ```
-
- **Extracting bits** (e.g., building a 4-bit selector):
-
- ```cairo
- // GOOD — div_rem by 2 extracts LSB, quotient is right-shifted value
- let (qu1, bit0) = bounded_int::div_rem(u1, TWO_NZ); // bit0 in {0,1}
- let (qu2, bit1) = bounded_int::div_rem(u2, TWO_NZ);
- let selector = add(bit0, mul(bit1, TWO_UI)); // selector in {0..3}
- ```
-
- See [garaga/selectors.cairo](https://github.com/keep-starknet-strange/garaga/blob/main/src/src/ec/selectors.cairo) and [cairo-perfs-snippets](https://github.com/feltroidprime/cairo-perfs-snippets) for production examples.
-
- ### 11. Always use `hades_permutation` for 2-input Poseidon hashes
-
- `poseidon_hash_span` has overhead for span construction. For exactly two inputs, use the permutation directly.
-
- ```cairo
- // BAD
- let hash = poseidon_hash_span(array![x, y].span());
-
- // GOOD
- let (hash, _, _) = hades_permutation(x, y, 2);
- ```
-
- ## Code Quality
-
- - **DRY:** Extract repeated validation into helper functions. If two functions validate-then-write the same struct, extract a shared `_set_config()`.
- - **`scarb fmt`:** Run before every commit.
- - **`.tool-versions`:** Pin Scarb (2.15.1) and Starknet Foundry (0.56.0) versions with ASDF for reproducible builds.
- - **Keep dependencies updated:** Newer Scarb/Foundry versions include gas optimizations and compiler improvements.
-
- ---
-
- ## BoundedInt Optimization
-
- `BoundedInt<MIN, MAX>` encodes value constraints in the type system, eliminating runtime overflow checks. Use the CLI tool (`bounded_int_calc.py` in this skill directory) to compute bounds — do NOT calculate manually.
-
- ### Critical Architecture Decision: Avoid Downcast
-
- **The #1 optimization pitfall:** Converting between `u16`/`u32`/`u64` and `BoundedInt` at function boundaries.
-
- #### The Problem
-
- If your functions take `u16` and return `u16`, you must:
- 1. `downcast` input to `BoundedInt` (expensive — requires range check)
- 2. Do bounded arithmetic (cheap)
- 3. `upcast` result back to `u16` (cheap but wasteful)
+ - Reducing gas/steps in hot paths after correctness is established.
+ - Profiling Cairo functions to find bottlenecks.
+ - Rewriting expensive arithmetic, loops, or storage patterns.
+ - Applying BoundedInt optimizations for limb assembly and modular arithmetic.
+ - Packing storage fields to reduce slot usage.
- The `downcast` operation adds a range check that **dominates the savings** from bounded arithmetic. In profiling:
- - `downcast`: 161,280 steps (18.86%)
- - `bounded_int_div_rem`: 204,288 steps (23.89%)
- - Total bounded approach: worse than original!
+ ## When NOT to Use
- #### The Solution: BoundedInt Throughout
+ - Early feature prototyping without tests (write tests first with `cairo-testing`).
+ - Contract architecture decisions (`cairo-contract-authoring`).
+ - Security audit (`cairo-auditor`).
+ - Deployment operations (`cairo-deploy`).
- **Use `BoundedInt` types as function inputs AND outputs.** This eliminates downcast entirely.
+ ## Quick Start
- ```cairo
- // BAD: Converts at every call (downcast overhead kills performance)
- pub fn add_mod(a: u16, b: u16) -> u16 {
- let a: Zq = downcast(a).expect('overflow'); // EXPENSIVE
- let b: Zq = downcast(b).expect('overflow'); // EXPENSIVE
- let sum: ZqSum = add(a, b);
- let (_q, rem) = bounded_int_div_rem(sum, nz_q);
- upcast(rem)
- }
+ 1. Confirm tests pass with `snforge test`.
+ 2. Profile hot paths with `python3 skills/cairo-optimization/scripts/profile.py profile`.
+ 3. Load references based on optimization type — see the table in [Orchestration](#orchestration).
+ 4. Apply one optimization class at a time, re-test after each.
+ 5. Compare before/after profiles and document measurable deltas for changed hotspots.
+ 6. Encode stable optimization regressions in `../../evals/cases/contract_skill_benchmark.jsonl` to prevent benchmark drift.
+ 7. Emit a handoff block using `../references/skill-handoff.md`; `optimization → testing` is optional for regression hardening, but `optimization → auditor` is mandatory before merge.
- // GOOD: BoundedInt in, BoundedInt out (no downcast)
- pub fn add_mod(a: Zq, b: Zq) -> Zq {
- let sum: ZqSum = add(a, b);
- let (_q, rem) = bounded_int_div_rem(sum, nz_q);
- rem
- }
- ```
+ ## Rationalizations to Reject
- #### Refactoring Strategy
+ - "Let's optimize before we have tests."
+ - "We can skip re-profiling — the change is obviously better."
+ - "BoundedInt types are too complex — let's use raw u128 math."
+ - "We can calculate bounds by hand instead of using the CLI tool."
- When optimizing existing code:
- 1. **Identify the hot path** — profile to find which functions use modular arithmetic heavily
- 2. **Change signatures** — update function inputs/outputs to use `BoundedInt` types
- 3. **Propagate types outward** — callers must also use `BoundedInt`
- 4. **Downcast only at boundaries** — convert from u16/u32 only at system entry points (e.g., deserialization)
+ ## Mode Selection
- #### Type Conversion Rules
+ - **profile**: User wants to find bottlenecks. Run profiler, identify hotspots.
+ - **arithmetic**: User wants to optimize math (DivRem, loops, Poseidon). Apply rules from legacy-full.md.
+ - **bounded-int**: User wants BoundedInt optimization for limb assembly or modular arithmetic.
+ - **storage**: User wants to pack storage fields or reduce slot usage.
- | From | To | Operation | Cost |
- |------|-----|-----------|------|
- | `u16` | `BoundedInt<0, 65535>` | `upcast` | Free (superset) |
- | `u16` | `BoundedInt<0, 12288>` | `downcast` | **Expensive** (range check) |
- | `BoundedInt<0, 12288>` | `u16` | `upcast` | Free (subset) |
- | `BoundedInt<A, B>` | `BoundedInt<C, D>` where [A,B] ⊆ [C,D] | `upcast` | Free |
- | `BoundedInt<A, B>` | `BoundedInt<C, D>` where [A,B] ⊄ [C,D] | `downcast` | **Expensive** |
+ ## Orchestration
- **Key insight:** `upcast` only works when target range is a **superset** of source range. You cannot upcast `u32` to `BoundedInt<0, 150994944>` because `u32` max (4294967295) > 150994944.
+ **Turn 1 — Baseline.** Before optimizing anything:
- ### Prerequisites
+ (a) Determine mode: `profile`, `arithmetic`, `bounded-int`, or `storage`.
- ```toml
- # Scarb.toml
- [dependencies]
- corelib_imports = "0.1.2"
- ```
+ (b) Verify tests pass. Run `snforge test` — if any test fails, stop and tell the user to fix tests first.
- ```cairo
- // CORRECT imports — copy exactly
- use corelib_imports::bounded_int::{
- BoundedInt, upcast, downcast, bounded_int_div_rem,
- AddHelper, MulHelper, DivRemHelper, UnitInt,
- };
- use corelib_imports::bounded_int::bounded_int::{SubHelper, add, sub, mul};
- ```
+ (c) Read the target code. Use Glob to find `.cairo` files, then Read to inspect them. Identify:
+ - Hot-path functions (called frequently or with expensive operations).
+ - Current arithmetic patterns (division, modulus, loops, bitwise ops).
+ - Storage layout (field types, packing opportunities).
+ - BoundedInt usage or opportunities.
- ### Copy-Paste Template
+ (d) Profile the baseline. Run `python3 {skill_dir}/scripts/profile.py profile` with the appropriate arguments. Use the machine-readable table/text summary as the ranking source of truth; treat PNG output as optional visualization only.
- Working example for modular arithmetic mod 100:
+ (e) Load references based on the optimization type:
- ```cairo
- use corelib_imports::bounded_int::{
- BoundedInt, upcast, downcast, bounded_int_div_rem,
- AddHelper, MulHelper, DivRemHelper, UnitInt,
- };
- use corelib_imports::bounded_int::bounded_int::{SubHelper, add, sub, mul};
+ | Request involves | Load reference |
+ |-----------------|---------------|
+ | Arithmetic rules (DivRem, loops, Poseidon, integer types) | `{skill_dir}/references/legacy-full.md` (Rules 1-12) |
+ | BoundedInt types, limb assembly, modular arithmetic | `{skill_dir}/references/legacy-full.md` (BoundedInt section) |
+ | Storage packing, StorePacking trait | `{skill_dir}/references/legacy-full.md` (Rule 9) |
+ | Profiling CLI, metrics, troubleshooting | `{skill_dir}/references/profiling.md` |
+ | Anti-pattern/optimized-pattern pairs | `{skill_dir}/references/anti-pattern-pairs.md` |
- type Val = BoundedInt<0, 99>; // [0, 99]
- type ValSum = BoundedInt<0, 198>; // [0, 198]
- type ValConst = UnitInt<100>; // singleton {100}
+ Where `{skill_dir}` is the directory containing this SKILL.md. Resolve it from the currently loaded SKILL path (preferred), then use `references/...` and `scripts/...` relative paths from that directory.
- impl AddValImpl of AddHelper<Val, Val> {
- type Result = ValSum;
- }
+ **Turn 2 — Plan.** Before changing any code, output a brief plan:
- impl DivRemValImpl of DivRemHelper<ValSum, ValConst> {
- type DivT = BoundedInt<0, 1>;
- type RemT = Val;
- }
+ 1. **Hotspots** — list the top 3-5 functions by step cost from the profile.
+ 2. **Optimizations** — for each hotspot, identify which rule(s) apply (by number from legacy-full.md).
+ 3. **Anti-patterns found** — list any anti-pattern/optimized-pattern pairs detected in the code.
+ 4. **BoundedInt opportunities** — if applicable, list functions that would benefit from BoundedInt types.
+ 5. **Expected impact** — rough estimate of step reduction per optimization.
- fn add_mod_100(a: Val, b: Val) -> Val {
- let sum: ValSum = add(a, b);
- let nz_100: NonZero<ValConst> = 100;
- let (_q, rem) = bounded_int_div_rem(sum, nz_100);
- rem
- }
- ```
+ Keep the plan under 30 lines. Wait for user confirmation before implementing.
- ### CLI Tool
+ **Turn 3 — Optimize.** Apply changes following these rules:
- Use `bounded_int_calc.py` in this skill directory. **Always use CLI — never calculate manually.**
+ *Process rules:*
+ - Apply ONE optimization class per commit. Never mix arithmetic and storage optimizations.
+ - Run `snforge test` after each change — if any test fails, revert and investigate.
+ - Re-profile after each change to measure actual impact.
- ```bash
- # Addition: [a_lo, a_hi] + [b_lo, b_hi]
- python3 bounded_int_calc.py add 0 12288 0 12288
- # -> BoundedInt<0, 24576>
+ *Arithmetic rules (from legacy-full.md):*
+ - Use `DivRem::div_rem` instead of separate `/` and `%` (Rule 1).
+ - Use `!=` instead of `<` in loop conditions (Rule 2).
+ - Use match-based lookup tables instead of `pow()` (Rule 3).
+ - Use `pop_front` / `for` / `multi_pop_front` instead of index loops (Rule 4).
+ - Cache `.len()` before loops (Rule 5).
+ - Use `span.slice()` instead of manual loop extraction (Rule 6).
+ - Use `DivRem` for parity checks instead of bitwise ops (Rule 7).
+ - Use the smallest integer type that fits the range (Rule 8).
+ - Use `hades_permutation` for 2-input Poseidon hashes (Rule 11).
- # Subtraction: [a_lo, a_hi] - [b_lo, b_hi]
- python3 bounded_int_calc.py sub 0 12288 0 12288
- # -> BoundedInt<-12288, 12288>
+ *Storage rules:*
+ - Pack small fields into one slot with `StorePacking` trait (Rule 9).
- # Multiplication
- python3 bounded_int_calc.py mul 0 12288 0 12288
- # -> BoundedInt<0, 150994944>
+ *BoundedInt rules:*
+ - Use BoundedInt types as function inputs AND outputs — never downcast at every call (Rule 10).
+ - Use `u128s_from_felt252` + `upcast` for bulk felt252 → BoundedInt conversions (Rule 12).
+ - Always use `python3 {skill_dir}/scripts/bounded_int_calc.py` to compute bounds — never calculate manually.
+ - Use the SHIFT pattern for negative dividends in `bounded_int_div_rem`: `SHIFT = ceil(|min_possible_value| / modulus) * modulus`, then reduce `value + SHIFT`.
- # Division: quotient and remainder bounds
- python3 bounded_int_calc.py div 0 24576 12289 12289
- # -> DivT: BoundedInt<0, 1>, RemT: BoundedInt<0, 12288>
+ After each optimization, run `snforge test` and `python3 {skill_dir}/scripts/profile.py profile` to verify improvement.
- # Custom impl name
- python3 bounded_int_calc.py mul 0 12288 0 12288 --name MulZqImpl
- ```
+ **Turn 4 — Verify.** After all optimizations:
- ### BoundedInt Bounds Quick Reference
+ - Run full test suite: `snforge test` (all tests must pass).
+ - Summarize before/after hotspot metrics and include step deltas in the PR description.
+ - Suggest next steps: run `cairo-auditor` on touched files and update eval cases (`contract_skill_benchmark.jsonl`, `contract_skill_generation_eval.jsonl`) to lock gains.
- | Operation | Formula |
- |-----------|---------|
- | Add | `[a_lo + b_lo, a_hi + b_hi]` |
- | Sub | `[a_lo - b_hi, a_hi - b_lo]` |
- | Mul (unsigned) | `[a_lo * b_lo, a_hi * b_hi]` |
- | Div quotient | `[a_lo / b_hi, a_hi / b_lo]` |
- | Div remainder | `[0, b_hi - 1]` |
+ For the full execution checklist, use [workflows/default.md](workflows/default.md).
- ### Negative Dividends: SHIFT Pattern
+ ## Security-Critical Rules
- `bounded_int_div_rem` doesn't support negative lower bounds. When a subtraction produces a negative-bounded result that needs reduction, add a multiple of the modulus first:
+ These are non-negotiable. Every optimization you apply must satisfy all of them:
- ```cairo
- // sub_mod: (a - b) mod Q via SHIFT
- pub fn sub_mod(a: Zq, b: Zq) -> Zq {
- let a_plus_q: BoundedInt<12289, 24577> = add(a, Q_CONST); // shift by +Q
- let diff: BoundedInt<1, 24577> = sub(a_plus_q, b); // now non-negative
- let (_q, rem) = bounded_int_div_rem(diff, nz_q());
- rem
- }
+ 1. Tests pass before AND after every optimization. Never optimize untested code.
+ 2. One optimization class per commit. Never mix unrelated changes.
+ 3. BoundedInt bounds are computed with the CLI tool — never by hand.
+ 4. Re-profile after every change to confirm measurable improvement.
+ 5. Anti-pattern/optimized-pattern pairs are enforced — never write the anti-pattern.
- // fused_sub_mul_mod: a - (b*c) mod Q via large SHIFT
- // OFFSET = 12288 * Q = 151007232 (smallest multiple of Q >= max product)
- pub fn fused_sub_mul_mod(a: Zq, b: Zq, c: Zq) -> Zq {
- let prod: ZqProd = mul(b, c);
- let a_offset: BoundedInt<151007232, 151019520> = add(a, OFFSET_CONST);
- let diff: BoundedInt<12288, 151019520> = sub(a_offset, prod);
- let (_q, rem) = bounded_int_div_rem(diff, nz_q());
- rem
- }
- ```
+ ## References
- Rule: SHIFT = `ceil(|min_possible_value| / modulus) * modulus`. Adding SHIFT preserves the result mod Q (since SHIFT ≡ 0 mod Q) while making all values non-negative.
+ - Optimization rules and BoundedInt: [legacy-full.md](references/legacy-full.md)
+ - Profiling CLI and troubleshooting: [profiling.md](references/profiling.md)
+ - Optimization anti-pattern pairs: [anti-pattern-pairs.md](references/anti-pattern-pairs.md)
+ - Cross-skill handoff format: `../references/skill-handoff.md`
+ - Module index: [references/README.md](references/README.md)
- ### Common BoundedInt Mistakes
+ ## Workflow
- - **Downcast at every function call** — the biggest performance killer. Use `BoundedInt` types throughout, not just inside arithmetic functions.
- - **Trying to upcast to a narrower type** — `upcast(val: u32)` to `BoundedInt<0, 150994944>` fails because u32 max > 150994944.
- - **Wrong imports** — use exact imports from Prerequisites section above.
- - **Wrong subtraction bounds** — it's `[a_lo - b_hi, a_hi - b_lo]`, NOT `[a_lo - b_lo, a_hi - b_hi]`.
- - **Negative dividend in `bounded_int_div_rem`** — div_rem doesn't support negative lower bounds. Add a SHIFT (multiple of modulus) before reducing. See SHIFT pattern above.
- - **Missing intermediate types** — always annotate: `let sum: ZqSum = add(a, b);`
- - **Division quotient off-by-one** — integer division floors: `24576 / 12289 = 1`, not 2.
- - **Using `UnitInt` vs `BoundedInt` for constants** — use `UnitInt<N>` for singleton constants like divisors.
- - **Using `div_rem` vs `bounded_int_div_rem`** — the function is `bounded_int_div_rem`, not `div_rem`.
- - **Bounds exceed u128::max** — BoundedInt bounds are hard-capped at 2^128. Larger values crash the Sierra specializer: 'Provided generic argument is unsupported.'
+ - Main optimization flow: [default workflow](workflows/default.md)
+ - Mandatory pre-merge chain: `optimization → auditor` (with `optimization → testing` only as an optional regression-hardening pass before auditor).