State Invariant Detection logo

State Invariant Detection

Organization
quillai-network
state-invariant-detection

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.

Overview

Publisherquillai-network
Repositoryquillshield_skills
Skill namestate-invariant-detection
Stars
131
Forks
28
Bundled files
2
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by quillai-network on GitHub. Read the source before you install it.

Installation

Install the State Invariant Detection AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/quillai-network/quillshield_skills/tree/main/plugins/state-invariant-detection/skills/state-invariant-detection
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/quillai-network/quillshield_skills.git /tmp/quillshield_skills
mkdir -p .claude/skills
cp -r /tmp/quillshield_skills/plugins/state-invariant-detection/skills/state-invariant-detection .claude/skills/state-invariant-detection
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable State Invariant Detection in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads State Invariant Detection on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so State Invariant Detection is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

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

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the State Invariant Detection AI skill do?

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.

Why use State Invariant Detection on TypingMind?

Because you install it once and use it with any model. State Invariant Detection is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install State Invariant Detection in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/quillai-network/quillshield_skills/tree/main/plugins/state-invariant-detection/skills/state-invariant-detection. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use State Invariant Detection?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with State Invariant Detection?

As many as you like. As long as a model supports skills, you can use State Invariant Detection with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the State Invariant Detection AI skill free?

Yes. It is published on GitHub by quillai-network under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇