Skip to content

x402agent/SolanaOS / skills/solana-formal-verification

qedgen

Flagged

Formally verify programs by writing Lean 4 proofs. Trigger this skill whenever the user wants to formally verify code, generate Lean 4 proofs, prove properties about algorithms or smart contracts, verify invariants, convert program logic into formal specifications, or anything involving Lean 4 and formal verification. Also trigger when the user mentions "qedgen", "lean proof", "formal proof", "verify my code", "prove correctness", "formal verification", or wants mathematical guarantees about their implementation.

FileKindSize
.gitignoreother753 B
.npmignoreother352 B
Cargo.lockmanifest46.3 KB
Cargo.tomlmanifest307 B
LICENSEother1.0 KB
README.mdmarkdown3.7 KB
SKILL.mdskill md10.8 KB
bin/leanstralexecutablescript6.2 MB
claude.mdmarkdown6.8 KB
crates/qedgen/Cargo.tomlmanifest544 B
crates/qedgen/lean_support/QEDGen.leanother166 B
crates/qedgen/lean_support/QEDGen/Solana.leanother166 B
crates/qedgen/lean_support/QEDGen/Solana/Account.leanother4.0 KB
crates/qedgen/lean_support/QEDGen/Solana/Authority.leanother285 B
crates/qedgen/lean_support/QEDGen/Solana/Cpi.leanother3.3 KB
crates/qedgen/lean_support/QEDGen/Solana/State.leanother1.9 KB
crates/qedgen/lean_support/QEDGen/Solana/Token.leanother1.4 KB
crates/qedgen/lean_support/QEDGen/Solana/Valid.leanother2.0 KB
crates/qedgen/lean_support/README.mdmarkdown2.8 KB
crates/qedgen/lean_support/lake-manifest.jsonconfig119 B
crates/qedgen/lean_support/lakefile.leanother112 B
crates/qedgen/lean_support/lean-toolchainother25 B
crates/qedgen/lean_support/test_lemmas.leanother1.2 KB
crates/qedgen/src/api.rsscript32.3 KB
crates/qedgen/src/consolidate.rsscript6.9 KB
crates/qedgen/src/main.rsscript4.1 KB
crates/qedgen/src/project.rsscript3.1 KB
crates/qedgen/src/spec.rsscript19.3 KB
crates/qedgen/src/validate.rsscript5.6 KB
crates/qedgen/templates/.gitignoreother29 B
crates/qedgen/templates/Main.leanother154 B
crates/qedgen/templates/PROMPT_TEMPLATE.mdmarkdown3.2 KB
crates/qedgen/templates/README.lean.mdmarkdown1.6 KB
crates/qedgen/templates/lakefile.leanother293 B
crates/qedgen/templates/lean-toolchainother25 B
docs/CNAMEother10 B
docs/index.htmlother10.9 KB
docs/llms-full.txtmarkdown8.7 KB
docs/llms.txtmarkdown2.1 KB
docs/logo-dark.svgother648 B
docs/logo-light.svgother648 B
docs/style.cssother7.6 KB
example/escrow/.gitignoreother67 B
example/escrow/.prettierignoreother61 B
example/escrow/Anchor.tomlconfig353 B
example/escrow/Cargo.lockmanifest72.8 KB
example/escrow/Cargo.tomlmanifest215 B
example/escrow/migrations/deploy.tsscript428 B
example/escrow/package.jsonmanifest528 B
example/escrow/programs/escrow/Cargo.tomlmanifest376 B
example/escrow/programs/escrow/Xargo.tomlconfig62 B
example/escrow/programs/escrow/src/lib.rsscript6.7 KB
example/escrow/tests/escrow.tsscript8.6 KB
example/escrow/tsconfig.jsonconfig205 B
example/percolator/.cargo/config.tomlconfig33 B
example/percolator/.gitignoreother320 B
example/percolator/Cargo.lockmanifest8.5 KB
example/percolator/Cargo.tomlmanifest639 B
example/percolator/LICENSEother11.1 KB
example/percolator/README.mdmarkdown4.9 KB
example/percolator/examples/offsets.rsscript1.3 KB
example/percolator/scripts/audit-proof-strength.mdmarkdown6.4 KB
example/percolator/scripts/proof-strength-audit-results.mdmarkdown89.2 KB
example/percolator/scripts/run_kani_full_audit.shexecutablescript1.2 KB
example/percolator/spec.mdmarkdown108.4 KB
example/percolator/src/i128.rsscript20.4 KB
example/percolator/src/percolator.rsscript139.2 KB
example/percolator/src/wide_math.rsscript59.8 KB
example/percolator/tests/amm_tests.rsscript7.4 KB
example/percolator/tests/common/mod.rsscript4.7 KB
example/percolator/tests/fuzzing.proptest-regressionsother4.7 KB
example/percolator/tests/fuzzing.rsscript43.1 KB
example/percolator/tests/proofs_arithmetic.rsscript17.1 KB
example/percolator/tests/proofs_audit.rsscript35.0 KB
example/percolator/tests/proofs_instructions.rsscript64.8 KB
example/percolator/tests/proofs_invariants.rsscript21.0 KB
example/percolator/tests/proofs_lazy_ak.rsscript22.4 KB
example/percolator/tests/proofs_liveness.rsscript17.1 KB
example/percolator/tests/proofs_safety.rsscript104.2 KB
example/percolator/tests/proofs_v1131.rsscript25.4 KB
example/percolator/tests/unit_tests.rsscript93.8 KB
install.shexecutablescript4.9 KB
package.jsonmanifest1.1 KB

docs/llms-full.txt

View on GitHub
# QEDGen

> An agent skill that formally verifies Solana programs by generating Lean 4 proofs. Your agent writes the proofs; Mistral's Leanstral model handles hard sub-goals.

## Installation

```bash
npx skills add qedgen/solana-skills
```

The installer automatically sets up Rust, Lean/elan, the CLI binary, and a global Mathlib cache.

## Setup

Export a free Mistral API key from [console.mistral.ai](https://console.mistral.ai):

```bash
export MISTRAL_API_KEY=your_key_here
```

## What It Does

QEDGen verifies your core business logic. Your agent reads the codebase, writes Lean 4 models and proofs, iterates on compiler errors, and calls Leanstral (Mistral's theorem prover) only for hard sub-goals.

### How It Works

1. **Agent reads your code** — checks for existing specs or IDLs, reads source directly, and builds a model of the program's state, transitions, and invariants.
2. **Writes spec and proofs** — generates SPEC.md with security goals and formal properties, then writes Lean 4 theorems and proofs. Runs `lake build` and iterates on errors.
3. **Hard sub-goals go to Leanstral** — when the agent can't close a `sorry`, it calls Leanstral via `fill-sorry` with pass@N sampling. First compilable result wins.

### Supported Agents

Works with any coding agent — Cursor, Windsurf, Claude Code, GitHub Copilot, and anything supporting the [Agent Skills spec](https://agentskills.io).

## CLI Commands

### Full pipeline (recommended)

```bash
qedgen verify \
  --idl target/idl/my_program.json \
  --validate
```

The IDL is the primary input. Optional flags: `--input` (Rust source, passed to the LLM as context but not parsed) and `--tests` (test files, used as hint signals for property ranking).

### Analysis only

```bash
qedgen analyze \
  --idl target/idl/my_program.json
```

Emits `analysis.json` with ranked property candidates and one prompt file per property.

### Generate from an existing prompt

```bash
qedgen generate \
  --prompt-file /tmp/analysis/property.prompt.txt \
  --output-dir /tmp/proof \
  --passes 4 \
  --validate
```

### Fill sorry markers

```bash
qedgen fill-sorry \
  --file formal_verification/Proofs/Hard.lean \
  --passes 3 \
  --validate
```

Sends each `sorry` location to the Leanstral model with focused context. Review the result — The Leanstral model may introduce tactics you can learn from for future proofs.

### Consolidate proofs

```bash
qedgen consolidate \
  --input-dir /tmp/proofs \
  --output-dir my_program/formal_verification
```

Merges validated `Best.lean` files into a single Lean project with namespaced proofs.

### Generate a draft spec

```bash
qedgen spec --idl target/idl/program.json --output-dir ./formal_verification
```

### Set up global validation workspace

```bash
qedgen setup
```

First-time Mathlib build takes 15-45 minutes. Subsequent builds reuse the cache.

## Proof-Writing Workflow (SKILL.md)

The skill instructs your agent to follow this workflow:

### Step 1: Understand the program

Check for existing artifacts:
1. **spec.md exists** — read it, extract security goals, state model, and formal properties
2. **IDL exists** — run `qedgen spec --idl <path>` to generate a draft SPEC.md
3. **Neither exists** — read source code directly, ask scoping questions

### Step 2: Scope the verification

Interactive quiz to determine security goals:
- Authorization / access control
- Token conservation / correct routing
- One-shot safety / no replay
- Arithmetic safety / no overflow
- Conservation (e.g., vault >= total claims)

### Step 3: Write SPEC.md

Structure: Security Goals, State Model, Operations (with signers, preconditions, effects, postconditions), Formal Properties, Trust Boundary, Verification Results.

### Step 4: Set up the Lean project

```
formal_verification/
  lakefile.lean          # import lean_support and Mathlib
  lean-toolchain         # leanprover/lean4:v4.15.0
  lean_support/          # Solana axiom library
  Proofs.lean            # root import
  Proofs/
    AccessControl.lean
    Conservation.lean
    StateMachine.lean
    ArithmeticSafety.lean
```

### Step 5: Write Lean proofs

For each property:
1. Define the state as a Lean structure
2. Define the transition as `Option StateType` (return `none` on precondition failure)
3. State the theorem matching the SPEC.md property
4. Write the proof
5. Run `lake build` and iterate

### Step 6: Call Leanstral model for hard sub-goals

```bash
qedgen fill-sorry --file formal_verification/Proofs/Hard.lean --validate
```

### Step 7: Verify and report

Run `lake build` and update SPEC.md verification results.

## Support Library API

After `import QEDGen.Solana` and `open QEDGen.Solana`:

**Types:** `Pubkey` (= Nat), `U64` (= Nat), `Account`, `Lifecycle` (open | closed), `TransferCpi`, `MintToCpi`, `BurnCpi`, `CloseCpi`

**Constants:** `TOKEN_PROGRAM_ID`, `SYSTEM_PROGRAM_ID`, `U8_MAX`, `U16_MAX`, `U32_MAX`, `U64_MAX`, `U128_MAX`

**Functions:** `findByKey`, `findByAuthority`, `canWrite`, `transferCpiValid`, `closes`, `valid_u64`

**Key lemmas:** `closes_is_closed`, `closes_was_open`, `closed_irreversible`, `valid_u64_preserved_by_zero`, `valid_u64_preserved_by_same`, `find_map_update_other`, `find_map_update_same`

## Proof Patterns

### Access control — signer must match authority

```lean
def cancelTransition (s : ProgramState) (signer : Pubkey) : Option Unit :=
  if signer = s.authority then some () else none

theorem cancel_access_control (s : ProgramState) (signer : Pubkey)
    (h : cancelTransition s signer ≠ none) :
    signer = s.authority := by
  unfold cancelTransition at h
  split_ifs at h with h_eq
  · exact h_eq
  · contradiction
```

### Conservation — invariant preserved across operations

```lean
def conservation (s : EngineState) : Prop := s.V >= s.C_tot + s.I

def depositTransition (s : EngineState) (amount : Nat) : Option EngineState :=
  if s.V + amount <= MAX_VAULT_TVL then
    some { V := s.V + amount, C_tot := s.C_tot + amount, I := s.I }
  else none

theorem deposit_conservation (s s' : EngineState) (amount : Nat)
    (h_inv : conservation s)
    (h : depositTransition s amount = some s') :
    conservation s' := by
  unfold depositTransition at h
  split_ifs at h with h_le
  · cases h
    unfold conservation at h_inv ⊢
    omega
  · contradiction
```

### State machine — lifecycle transitions

```lean
theorem cancel_closes_escrow (pre post : ProgramState)
    (h : cancelTransition pre = some post) :
    post.escrow.lifecycle = Lifecycle.closed := by
  unfold cancelTransition at h
  split_ifs at h with h_open
  cases h
  rfl
```

### CPI correctness — parameters match (pure rfl)

```lean
theorem cancel_cpi_correct (ctx : CancelContext) :
    let cpi := cancel_build_cpi ctx
    cpi.program = TOKEN_PROGRAM_ID ∧ cpi.amount = ctx.amount := by
  unfold cancel_build_cpi
  exact ⟨rfl, rfl⟩
```

## Critical Tactic Rules

| Do | Don't |
|---|---|
| `unfold f at h` before `split_ifs` | `simp [f] at h` before `split_ifs` (kills if-structure) |
| `unfold pred at h_inv ⊢` for named predicates | `unfold pred` only in goal (omega can't see hypotheses) |
| `cases h` after `split_ifs` on `some = some` | `injection h` (unnecessary) |
| `omega` for linear arithmetic | `norm_num` for linear goals |
| `exact ⟨rfl, rfl, rfl⟩` for conjunctions of rfl | `constructor` + `rfl` chains (verbose) |

## Common Errors and Fixes

| Error | Fix |
|---|---|
| `omega could not prove the goal` | Unfold named predicates in hypotheses: `unfold pred at h ⊢` |
| `no goals to be solved` | Remove redundant tactic (e.g., `· contradiction` after auto-closed branch) |
| `unknown constant 'X'` | Check imports; add `import QEDGen.Solana.X` or `open QEDGen.Solana` |
| `tactic 'split_ifs' failed, no if-then-else` | Use `unfold` first, not `simp` |

## Working Examples

### Escrow (Anchor) — 9/9 proofs verified

A token escrow that lets two parties trade safely. Properties verified: cancel access control, exchange access control, initialize access control, cancel CPI correctness, exchange CPI correctness, initialize CPI correctness, cancel closes escrow, exchange closes escrow, initialize arithmetic safety.

### Percolator (Pure Rust) — 7/7 proofs verified

A perpetual DEX risk engine with protected principal, junior profit claims, and lazy A/K side indices. Properties verified: deposit conservation, top-up insurance conservation, deposit fee credits conservation, PnL negation safety, deposit bounded, ADL lifecycle, fee credits nonpositive.

## Environment Variables

- `MISTRAL_API_KEY` — required for `fill-sorry` and `generate` commands. Free from console.mistral.ai.
- `QEDGEN_VALIDATION_WORKSPACE` — optional override for global Mathlib cache location.

## Requirements

- Rust toolchain (auto-installed if missing)
- Lean 4 / elan (auto-installed if missing)
- `MISTRAL_API_KEY` environment variable

## License

MIT
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall