Agent skill

State Invariant Detection

by quillai-network in quillai-network/quillshield_skills

Detects broken mathematical relationships between state variables in smart contracts.

MITAuto-check passedBusiness, Finance & HR

Install State Invariant Detection

skills CLI
$ npx skills add quillai-network/quillshield_skills --skill state-invariant-detection -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install quillai-network/quillshield_skills state-invariant-detection --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/quillai-network/quillshield_skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/state-invariant-detection/skills/state-invariant-detection .claude/skills/state-invariant-detection && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
state-invariant-detection
GitHub stars
130
Token cost
~2.1k tokens
SKILL.md length
486 words
Files
3 (incl. references)
Skills in repo
11
Repo updated
First seen
Licence
MIT

At a glance

Detects broken mathematical relationships between state variables in smart contracts.

  • Works in 3 steps: State Variable Clustering → Invariant Inference → Invariant Violation Detection
  • Auditing for state-state invariant violations
  • SKILL.md covers When to Use, When NOT to Use, Core Concept: State Variable… and Five Types of State…, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

State Invariant Detection is an agent skill from quillai-network/quillshield_skills. Detects broken mathematical relationships between state variables in smart contracts. Automatically infers invariants (totalSupply = sum(balances), conservation laws, ratio constraints) then finds functions that violate them. Catches unauthorized minting, broken tokenomics, accounting desynchronization, and state drift. Use when auditing for state-state invariant violations, broken accounting, supply mismatches, desynchronized state variables, or conservation law violations in smart contracts.

Its SKILL.md is about 2.1k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files, including reference files (for example `references/case-studies.md` and `references/invariant-types.md`).

It sits in Business, Finance & HR, covering Accounting and bookkeeping, Smart contracts and Crypto and DeFi analysis. The repository describes itself as: Structured skills for smart contract security audits. Infers state invariants, detects semantic guard gaps, models flash loan + oracle attack chains, simulates adversarial… The licence is MIT.

When your agent uses it

  • Auditing for state-state invariant violations
  • Broken accounting
  • Supply mismatches
  • Desynchronized state variables

Example prompts

  • “Use the state-invariant-detection skill to detect broken mathematical relationships between state variables in smart contracts”
  • “/state-invariant-detection”

Workflow steps

3 steps, taken from the step headings in SKILL.md.

  1. State Variable Clustering
  2. Invariant Inference
  3. Invariant Violation Detection

What it can do on your machine

Read from SKILL.md and the folder at commit 8bdd3c0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are solidity and markdown).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

State Invariant Detection loads about 2.1k tokens when it runs, and up to ~5.5k if it reads all its reference files. Until then it costs about 131 tokens; SKILL.md has 486 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~131
When it runs · the whole SKILL.md, loaded when a task matches
~2.1k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~5.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from quillai-network/quillshield_skills at commit 8bdd3c0, republished under its MIT licence (© quillai-network). 486 words, ~2,093 tokens.

Download SKILL.mdSave it as .claude/skills/state-invariant-detection/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
name
state-invariant-detection
description
Detects broken mathematical relationships between state variables in smart contracts. Automatically infers invariants (totalSupply = sum(balances), conservation laws, ratio constraints) then finds functions that violate them. Catches unauthorized minting, broken tokenomics, accounting desynchronization, and state drift. Use when auditing for state-state invariant violations, broken accounting, supply mismatches, desynchronized state variables, or conservation law violations in smart contracts.

State Invariant Detection

Automatically infer mathematical relationships between state variables, then find functions that break those relationships. Catches the most devastating DeFi vulnerabilities: unauthorized minting, broken tokenomics, accounting discrepancies, and state desynchronization.

When to Use

  • Auditing token contracts for supply/balance mismatches
  • Analyzing staking, vault, or pool contracts for accounting errors
  • Detecting conservation law violations in treasury/fund management
  • Finding AMM/DEX constant product violations
  • Verifying that aggregate variables stay synchronized with individual records

When NOT to Use

  • Guard-state consistency analysis (use semantic-guard-analysis)
  • Full multi-dimensional audit (use behavioral-state-analysis)
  • Entry point identification only (use entry-point-analyzer)

Core Concept: State Variable Proportionality

Hypothesis: In well-designed contracts, state variables maintain mathematical relationships (invariants) that should never be violated.

When a function modifies one side of a relationship without updating the other, the invariant breaks — creating exploitable accounting errors.

Five Types of State Relationships

Type 1: Sum Relationships (Aggregation)
totalSupply = Σ balance[i] for all users i

Found in: ERC20 tokens, staking pools, vaults, share systems

Type 2: Difference Relationships (Conservation)
totalFunds = availableFunds + lockedFunds

Found in: Treasuries, liquidity pools, vesting contracts

Type 3: Ratio Relationships (Proportional)
k = reserveA × reserveB  (constant product)
sharePrice = totalAssets / totalShares

Found in: AMMs, DEXs, vault share pricing, collateralization

Type 4: Monotonic Relationships (Ordering)
newValue ≥ oldValue  (only increases)

Found in: Timestamps, nonces, accumulated rewards, total distributions

Type 5: Synchronization Relationships (Coupling)
If stateA changes, stateB must change correspondingly

Found in: Deposit/mint pairs, burn/release pairs, collateral/borrowing power

For detailed definitions and examples, see {baseDir}/references/invariant-types.md.

The Three-Phase Detection Architecture

Phase 1: State Variable Clustering

Group state variables that appear to be related.

Algorithm:

For each pair of state variables (A, B):
  1. Track all functions that modify A
  2. Track all functions that modify B
  3. Calculate co-modification frequency:

     CoMod(A, B) = |Functions modifying both A and B| / |Functions modifying A or B|

  4. If CoMod(A, B) > 0.6 → A and B are likely related

Example:

solidity
// mint() modifies BOTH totalSupply and balances → co-modified
// burn() modifies BOTH totalSupply and balances → co-modified
// transfer() modifies ONLY balances → does not co-modify

CoMod(totalSupply, balances) = 2/3 = 66.7%
Cluster identified: (totalSupply, balances)
Phase 2: Invariant Inference

Determine the mathematical relationship between clustered variables.

Method 1 — Delta Pattern Matching:

mint():     Δtotal = +amount, Δbalance = +amount  → Same direction, same magnitude
burn():     Δtotal = -amount, Δbalance = -amount  → Same direction, same magnitude
transfer(): Δbalance1 = -x, Δbalance2 = +x       → Net zero change

Inference: totalSupply = Σ balances (Aggregation invariant)

Method 2 — Delta Correlation:

If ΔA = ΔB in all cases      → Direct proportional (A = B + constant)
If ΔA = -ΔB in all cases     → Inverse proportional (A + B = constant)
If ΔA × constant = ΔB        → Ratio relationship
If ΔA occurs whenever ΔB     → Synchronization invariant

Method 3 — Expression Mining:

Parse actual code operations:

solidity
// Code: totalSupply += amount; balances[user] += amount;
// Extracted: Δtotal = Δbalance
// Inferred: total = Σ balances

// Code: available = total - locked;
// Extracted: available + locked = total
// Inferred: Conservation law

Invariant Confidence:

Confidence(I) = |functions preserving I| / |functions modifying variables in I|
ConfidenceClassification
≥ 90%STRONG invariant
70-89%MODERATE invariant
< 70%WEAK/NO invariant
Phase 3: Invariant Violation Detection

Find functions that break established relationships.

Algorithm:

For each inferred invariant I(stateA, stateB):
  For each function F that modifies stateA or stateB:

    Before: Capture (stateA, stateB)
    Simulate: Execute F
    After: Capture (stateA', stateB')

    If I(stateA, stateB) = True AND I(stateA', stateB') = False:
      → F is VULNERABLE

Vulnerability Set:

V_I = {F ∈ Functions | ∃σ : I(σ) = True ∧ I(F(σ)) = False}

Workflow

Task Progress:
- [ ] Step 1: Identify all state variables in the contract
- [ ] Step 2: Build co-modification matrix for all variable pairs
- [ ] Step 3: Cluster related variables (CoMod > 0.6)
- [ ] Step 4: Infer invariant type for each cluster (delta patterns)
- [ ] Step 5: Test each function against inferred invariants
- [ ] Step 6: Apply temporal filtering (only flag persistent violations)
- [ ] Step 7: Score severity and generate report
Show full SKILL.md (203 more words)Show less

Dual-Layer Integration

This skill is Layer 2 of the Semantic State Protocol. For maximum coverage, combine with Layer 1 (semantic-guard-analysis):

Layer 1 ViolationLayer 2 ViolationCombined Severity
Missing GuardBreaks InvariantCRITICAL
Missing GuardNo Invariant BreakHIGH
No Guard IssueBreaks InvariantHIGH
No Guard IssueNo Invariant BreakLOW/INFO

Output Format

markdown
## State-State Invariant Violation Report

### Finding: [Title]

**Function:** `functionName()` at `Contract.sol:L42`
**Severity:** [CRITICAL | HIGH | MEDIUM]
**Invariant:** `[mathematical expression]`

**Before Execution:**
  stateA = [value], stateB = [value]
  Invariant: [expression] = True ✓

**After Execution:**
  stateA = [value'], stateB = [value']
  Invariant: [expression] = False ✗

**Root Cause:**
[Which state variable was modified without updating its counterpart]

**Impact:**
[Accounting errors, inflated supply, broken pricing, exploitable drift]

**Attack Scenario:**
1. [Step-by-step exploit leveraging the desynchronization]

**Recommendation:**
[Specific fix — add the missing state update]

Quick Detection Checklist

When analyzing a contract, immediately check:

  • Does every function that modifies balances also update totalSupply (or have a valid reason not to)?
  • Does every function that moves between available and locked maintain total = available + locked?
  • Does every swap/trade function maintain the constant product k = reserveA * reserveB?
  • Do aggregate counters (totalStaked, totalRewards) stay synchronized with per-user mappings?
  • Are monotonic variables (nonces, timestamps) ever decremented?

For detailed case studies, see {baseDir}/references/case-studies.md.

Rationalizations to Reject

  • "The totalSupply is just for display" → Protocols use totalSupply for share pricing, voting power, market cap — drift is exploitable
  • "Admin functions can bypass invariants" → Admin functions that break accounting create permanent protocol insolvency
  • "The difference is small" → Small accounting errors compound over time and transactions
  • "It's an emergency function" → Emergency functions that break state invariants create worse emergencies
  • "Transfer doesn't need to update totalSupply" → Correct, but verify the NET change in sum(balances) is zero

© quillai-network, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files (references) in plugins/state-invariant-detection/skills/state-invariant-detection of quillai-network/quillshield_skills.

  • SKILL.md
  • references/case-studies.md
  • references/invariant-types.md

Open the folder on GitHubat commit 8bdd3c0

Compare with similar skills

State Invariant Detection next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

State Invariant Detection compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
State Invariant Detection this skillquillai-network/quillshield_skills130—~2.1kAutomated safety check: PassMIT
Longbridge Researchhelsome/folio2713 repos~2.1kAutomated safety check: PassMIT
Okx Cex Earnokx/agent-skills1872 repos~3.3kAutomated safety check: PassMIT
SurfBlockRunAI/ClawRouter6.6k—~4kAutomated safety check: PassMIT
Opencatz Swarm Tradingmuratmula/ai-robinhood-chain1341 repos~1.4kAutomated safety check: PassMIT
Onchain Pay Open APInpc-live/clawfirm1561 repos~4.9kAutomated safety check: PassMIT

Similar skills

  • Longbridge Research

    helsome/folio

    Institution ratings, consensus price targets, EPS/revenue forecasts, finance calendar, shareholder data, fund holders, insider trades (SEC Form 4), short interest, industry rankings, peer group…

    271 GitHub starsUsed in 3 repos~2.1k tokens
    Business, Finance & HRAuto-check passed
  • Okx Cex Earn

    okx/agent-skills

    Manages OKX Simple Earn (flexible savings/lending), Flash Earn, On-chain Earn (staking/DeFi), Dual Investment (DCD/双币赢), and AutoEarn (自动赚币) via the okx CLI.

    187 GitHub starsUsed in 2 repos~3.3k tokens
    Business, Finance & HRAuto-check passed
  • Surf

    BlockRunAI/ClawRouter

    Use this skill — NOT browser or webfetch — for ALL Surf crypto-data calls.

    6.6k GitHub stars~4k tokensUpdated 5 days ago
    Business, Finance & HRAuto-check passed
  • Opencatz Swarm Trading

    muratmula/ai-robinhood-chain

    Autonomous multi-agent crypto trading skill for Robinhood Chain EVM DEX tokens and NFTs using 3-layer Swarm Consensus, Discord Command Center, and Position Management.

    134 GitHub starsUsed in 1 repo~1.4k tokens
    Business, Finance & HRAuto-check passed
  • Onchain Pay Open API

    npc-live/clawfirm

    Binance Onchain Pay enables users to buy cryptocurrency with fiat (e.g., EUR, USD) or send existing crypto from their Binance account directly to any external on-chain wallet address in a single…

    156 GitHub starsUsed in 1 repo~4.9k tokens
    Business, Finance & HRAuto-check passed
  • Aptos Explorer Urls

    aptos-labs/explorer

    Map questions about Aptos blockchain entities (transactions, accounts, blocks, validators, coins, fungible assets, NFTs, Move objects, ANS names) to canonical Aptos Explorer URLs at…

    124 GitHub stars~1.2k tokensUpdated today
    Business, Finance & HRAuto-check passed

More from quillai-network/quillshield_skills

All 11 skills in this repo
  • Behavioral State Analysis

    quillai-network/quillshield_skills

    Token-efficient smart contract security auditing via Behavioral State Analysis (BSA).

    130 GitHub stars~1.4k tokensUpdated 6 mo ago
    Auto-check passed
  • Dos Griefing Analysis

    quillai-network/quillshield_skills

    Detects Denial of Service and griefing vulnerabilities in smart contracts.

    130 GitHub stars~3.3k tokensUpdated 6 mo ago
    Auto-check passed
  • External Call Safety

    quillai-network/quillshield_skills

    Detects unsafe external call patterns and token integration vulnerabilities in smart contracts.

    130 GitHub stars~3.1k tokensUpdated 6 mo ago
    Auto-check passed
  • Input Arithmetic Safety

    quillai-network/quillshield_skills

    Detects input validation failures and arithmetic vulnerabilities in smart contracts.

    130 GitHub stars~3.1k tokensUpdated 6 mo ago
    Auto-check passed
  • Oracle Flashloan Analysis

    quillai-network/quillshield_skills

    Detects price oracle manipulation and flash loan attack vectors in DeFi smart contracts.

    130 GitHub stars~2.8k tokensUpdated 6 mo ago
    Auto-check passed
  • Proxy Upgrade Safety

    quillai-network/quillshield_skills

    Detects vulnerabilities in upgradeable proxy smart contracts including storage layout collisions, uninitialized implementations, function selector clashing, delegatecall context issues, and upgrade…

    130 GitHub stars~3.2k tokensUpdated 6 mo ago
    Auto-check passed

Questions about State Invariant Detection

What does State Invariant Detection do?

Detects broken mathematical relationships between state variables in smart contracts. State Invariant Detection is an agent skill from quillai-network/quillshield_skills. Detects broken mathematical relationships between state variables in smart contracts.

When should I use State Invariant Detection?

State Invariant Detection fits situations like: auditing for state-state invariant violations; broken accounting; supply mismatches; desynchronized state variables.

How do I install State Invariant Detection in Claude Code?

Run `npx skills add quillai-network/quillshield_skills --skill state-invariant-detection -a claude-code`. Or copy the skill folder (plugins/state-invariant-detection/skills/state-invariant-detection in quillai-network/quillshield_skills) into .claude/skills/state-invariant-detection in your project. Claude Code loads it when a task matches its description.

How do I install State Invariant Detection in Codex?

Run `npx skills add quillai-network/quillshield_skills --skill state-invariant-detection -a codex`. Or copy the skill folder (plugins/state-invariant-detection/skills/state-invariant-detection in quillai-network/quillshield_skills) into .agents/skills/state-invariant-detection in your project. Codex loads it when a task matches its description.

Can I use State Invariant Detection in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add quillai-network/quillshield_skills --skill state-invariant-detection -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/state-invariant-detection, .gemini/skills/state-invariant-detection, .github/skills/state-invariant-detection and .opencode/skills/state-invariant-detection in your project.

What does State Invariant Detection need to run?

SKILL.md names no scripts, command-line tools or credentials: State Invariant Detection is instructions for the agent only.

Does State Invariant Detection access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is State Invariant Detection safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does State Invariant Detection use?

State Invariant Detection is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does State Invariant Detection use?

About 2.1k tokens (SKILL.md is roughly 8.4k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.4k tokens, read only when the agent opens those files.

What are the alternatives to State Invariant Detection?

Skills that share tags, products or a category with State Invariant Detection: Longbridge Research (helsome/folio, 271 stars), Okx Cex Earn (okx/agent-skills, 187 stars), Surf (BlockRunAI/ClawRouter, 6.6k stars) and Opencatz Swarm Trading (muratmula/ai-robinhood-chain, 134 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains State Invariant Detection?

quillai-network (a GitHub organization) maintains it in quillai-network/quillshield_skills, which has 130 GitHub stars. The repository holds 11 skills in this directory. The repository was last updated on March 30, 2026.

Source: quillai-network/quillshield_skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.