# Quant VM (QVM) — Tutorial

Build, simulate, evolve, and deploy DeFi strategies on Solana. From your first swap to a self-evolving arb bot.

## 1. Your First Strategy

```bash
# List available presets
aex strategy list
```
```
  2hop             2-pool swap chain (A->B->C)
  split-50-50      50/50 split across 2 pools
  adaptive         Self-modifying split (auto-adjusts by pool depth)
  guarded          Swap with price guard (stale execution protection)
  ...
```

Every preset is a bytecode template you can simulate, inspect, and execute.

### Simulate

```bash
aex strategy sim --preset 2hop --trace
```
```
Strategy: 2hop — 2-pool swap chain (A->B->C)
Input: 1000000000, Min output: 0

  op 1: SWAP pool dir=0 slot=0
  op 2: SWAP pool dir=1 slot=3

Execution trace:
op#  opcode            acc              acc2
  1  SWAP         996995040                0
  2  SWAP         993999125                0

Result: OK
  Output:       993999125
  Fees:         admin=2995477 lp=2995478
```

The accumulator (`acc`) flows through each op. Input 1B lamports → two swaps with 30bps fee each → output 993.99M.

### Against Live Pools

```bash
aex strategy sim --preset roundtrip \
  --pool 9zuZVSCe4dwobVaVixi5qJc68zgvDDveiQQ1Hd5jmBgZ \
  --amount 100000000 --trace
```

The simulator fetches real on-chain pool state (balances, amp, fees) and runs the strategy locally. No gas cost.

## 2. Understanding Opcodes

### The Accumulator Model

QVM uses a single-accumulator architecture. Every op reads from `acc` and writes back to `acc`:

```
Input: 1,000,000,000 → [SWAP] → 996,995,040 → [SWAP] → 993,999,125 → Output
         acc               acc                    acc                    acc
```

For dual-output ops (REMLIQ, VECLMFEE), the second output goes to `acc2`.

### Registers

8 general-purpose u64 registers (r0-r7) for intermediate storage:

```
STORE r0    — save acc to r0
LOAD r0     — restore acc from r0
SWAP_REG r1 — exchange acc ↔ r1
ADD_R r0    — acc += r0
SUB_R r1    — acc -= r1
```

### Split Routing

Send portions of your input through different pools to minimize price impact:

```bash
aex strategy sim --preset split-50-50 --trace
```
```
  op 1: SPLIT n=2 pcts=[5000, 5000]    # Split acc into 2 legs (50%/50%)
  op 2: LEG                             # Load leg 0 input (500M)
  op 3: SWAP pool dir=0 slot=0          # Swap 500M through pool A
  op 4: LEG                             # Load leg 1 input (500M)
  op 5: SWAP pool dir=0 slot=3          # Swap 500M through pool B
  op 6: MERGE                           # Sum: 498.5M + 498.5M = 997M
```

Split gives 997M output vs 994M from 2hop — **3M lamports better** because each half-swap has less price impact.

## 3. Adaptive Strategies

The most powerful QVM feature: strategies that **modify themselves at runtime** based on live pool state.

### ADAPT_SPLIT

Automatically adjusts split percentages by pool depth:

```bash
aex strategy sim --preset adaptive --trace
```

On balanced pools (1T:1T), ADAPT_SPLIT keeps 50/50. On imbalanced pools (10T:1T), it rewrites to ~91%/9% — routing more traffic through the deeper pool.

```
  op 1: SPLIT n=2 pcts=[5000, 5000]    # Placeholder
  op 2: ADAPT_SPLIT slot_a=0 slot_b=3  # Reads depths, rewrites pcts
  op 3: LEG → SWAP → LEG → SWAP → MERGE
```

### AUTO_DIR

Picks optimal swap direction from pool balance ratio:

```
  AUTO_DIR slot=0 reg=r0    # r0 = 0 if bal0≥bal1, 1 otherwise
```

### PRICE_GUARD

Halts execution if the pool price has moved too far since the strategy was built:

```
  SET 1000000               # Expected price (1:1 = 1M scaled)
  PRICE_GUARD slot=0 50bps  # Halt if price drifted > 0.5%
  SET 1000000000            # Reset to input amount
  SWAP pool dir=0 slot=0    # Safe to swap
```

This prevents stale execution — if you simulated at block N but execute at block N+2, and the price moved, PRICE_GUARD aborts (losing only gas, not principal).

### SCALE_DEPTH

Scales your trade size by pool depth. Prevents outsized swaps on shallow pools:

```
  SCALE_DEPTH slot=0 ref=1000000000000   # Scale by depth/1T
  SWAP pool dir=0 slot=0                 # Smaller swap on shallow pools
```

## 4. Branching and Loops

### Conditional Jumps

```
  JUMP_IF_GT 2000000000 offset=15   # If acc > 2B, jump to offset 15
  SWAP pool dir=0 slot=0            # Only executes if acc ≤ 2B
  HALT
  # offset 15:
  SET 0                              # acc was too large, zero it
```

### CALL / RET

Compose sub-strategies like function calls:

```
  CALL offset=4          # Jump to sub-strategy at byte 4
  HALT                   # After return, halt with sub's result
  # Sub-strategy at offset 4:
  SET 42
  STORE r1
  RET                    # Return to caller
```

HALT inside a CALL acts as RET — seamless nesting up to 4 levels.

### Loop Guard

Any strategy that exceeds 1000 opcodes or 200,000 CU is terminated with a clean error. JUMP loops are safe — they can't run forever.

## 5. Flash Arbitrage

Borrow → swap → swap → repay in a single atomic TX. If unprofitable, the TX reverts.

```bash
aex strategy sim --preset flash-arb --trace
```
```
  op 1: F_BORROW slot=0 dir=0    # Borrow from pool 0
  op 2: SWAP pool dir=0 slot=3   # Swap on pool 1
  op 3: SWAP pool dir=1 slot=6   # Swap on pool 2
  op 4: F_REPAY                   # Repay principal + fee
  op 5: ASSERT_GT 0               # Must be profitable
```

If `acc < principal + fee` at F_REPAY, the strategy errors. You lose only gas (~5000 lamports), never the borrowed amount.

## 6. Strategy Evolution

Use a genetic algorithm to discover optimal strategies:

```bash
aex strategy evolve --gens 100 --pop 64 --amount 5000000000
```
```
Gen    0: best=-14566827 split=5494/4506 dirs=0,0 split=true
Gen  100: best=-14565799 split=4860/5140 dirs=0,0 split=true

=== Best Strategy ===
Split: 4860/5140 (48.6%/51.4%)
Dirs: 0,0  Use split: true

Hex bytecode: 0202f60f1a170801000000080100000303
```

The GA breeds strategies against imbalanced pool pairs, discovering the optimal split ratio through crossover and mutation. Export the hex bytecode to execute on-chain.

## 7. Strategy Competition

Pit strategies head-to-head across randomized pool states:

```bash
aex strategy compete --a adaptive --b 2hop --rounds 1000
```
```
Results:
  adaptive         wins=  950  avg_profit=-2790135  variance=7543049344276
  2hop             wins=   50  avg_profit=-6007280  variance=268152191

Winner: adaptive (95% win rate)
```

## 8. Amount Sweep

Find the optimal trade size where price impact vs absolute return peaks:

```bash
aex strategy sweep --preset adaptive
```
```
     SOL             Input            Output      Slip          Fees  Net
   0.001           1000000            997000      30bp          3000       -3000
       1        1000000000         996997522      30bp       2999992    -3002478
    1000     1000000000000      993720253242      62bp    2990131152  -6279746758

Optimal: 0.001 SOL (-3000 lamports)
```

## 9. Fuzz Testing

Verify your strategy never crashes on adversarial input:

```bash
# Random bytecodes
aex strategy fuzz --iters 50000
# 581K/s, 0 crashes

# Adversarial CU maximization
aex strategy fuzz --adversarial --iters 10000
# Worst-case successful strategy: 112K CU (56% of 200K budget)
```

## 10. Strategy Marketplace

### Register On-Chain

```bash
aex strategy register --preset adaptive
```

Creates a Strategy PDA with your bytecode. Each execution against this PDA tracks:
- Execution count + success rate
- Total input volume + cumulative P/L
- Best/worst single execution
- DAO fee earnings (0.1bps of input)

### Browse Leaderboard

```bash
aex strategy browse --sort profit
```
```
  #  Address                                       Bytes  Forks   Execs  Win%        Profit  Creator
  1  5vUgSmbnE9kWC6cHs2dFeRYbKwSRTTwFUonphGS2Rw9o     20      0       0  100%            0  55KLP138
```

### Detail View

```bash
aex strategy browse --detail <address>
```

Shows full reputation breakdown: ROI, avg P/L per execution, creator earnings estimate, bytecode disassembly.

### Versioning

Re-registering on the same PDA increments the version and resets reputation, but preserves fork count:

```bash
# v1: 2hop
aex strategy register --preset 2hop

# v2: adaptive (upgrade — same PDA, forks preserved)
aex strategy register --preset adaptive
```

### Strategy Derivatives

Bet on strategy performance:

```
stbet   — place long/short bet (wager SOL)
stsettle — settle after 10+ executions (2x or nothing)
```

### Autonomous Fund

Pool capital across top strategies:

```
stfund  — create fund, deposit SOL
stfexec — fund manager executes a strategy
```

## 11. Arb Daemon

Autonomous flash arb scanner that runs continuously:

```bash
# Scan only (report mode)
aex402-daemon arb --poll-interval 15

# Auto-execute on mainnet
aex402-daemon arb --execute \
  --rpc-url https://api.mainnet-beta.solana.com \
  --arb-amount 5000000000 --priority-fee 50000

# Swarm: 4 parallel scanners
aex402-daemon arb --swarm 4 --execute
```

Architecture:
1. **Bootstrap**: fetch all pools, build token graph, full N² scan
2. **Hot loop** (500ms): re-fetch only pools in profitable routes
3. **JIT cycle detection**: O(D²) per pool change via token graph
4. **Self-evolving**: GA breeds strategies against live pool state every 30s
5. **wss:// TLS**: WebSocket subscriber for real-time pool updates

## 12. Composability ABI

Build libraries of reusable strategy components:

```zig
var cs = ComposableStrategy.init(1_000_000_000, 0);

// Main strategy
cs.s().call(swap_opt_offset);  // Call the swap optimizer
cs.s().halt();

// Library: swap_opt at known offset
buildSwapOptimizer(&cs);  // ADAPT_SPLIT + SWAP × 2 + MERGE
```

The ABI header maps names to bytecode offsets. Users compose strategies by CALLing published routines.

## 13. Try It Live

Every example in this tutorial can be run against the live API at `rpc.aex402.com`. No setup needed — just `curl`.

### Simulate a 2-hop swap

```bash
curl -s -X POST https://rpc.aex402.com/v1/strategy/simulate \
  -H "Content-Type: application/json" \
  -d '{
    "bytecode": "0100000001000103",
    "pools": ["9zuZVSCe4dwobVaVixi5qJc68zgvDDveiQQ1Hd5jmBgZ"],
    "amount": 1000000000
  }' | jq .
```

### Simulate adaptive split

```bash
curl -s -X POST https://rpc.aex402.com/v1/strategy/simulate \
  -H "Content-Type: application/json" \
  -d '{
    "bytecode": "020288138813c300030801000000080100000303",
    "pools": ["9zuZVSCe4dwobVaVixi5qJc68zgvDDveiQQ1Hd5jmBgZ"],
    "amount": 1000000000
  }' | jq .
```

### Simulate a guarded swap (price protection)

```bash
curl -s -X POST https://rpc.aex402.com/v1/strategy/simulate \
  -H "Content-Type: application/json" \
  -d '{
    "bytecode": "2040420f0000000000c50000322000ca9a3b0000000001000000",
    "pools": ["9zuZVSCe4dwobVaVixi5qJc68zgvDDveiQQ1Hd5jmBgZ"],
    "amount": 1000000000
  }' | jq .
```

### Browse the strategy leaderboard

```bash
curl -s https://rpc.aex402.com/v1/strategy/browse | jq .
```

### Build your own bytecode

Use the opcode table to construct custom strategies byte-by-byte:

```
# NOP + NOP + NOP (passthrough — returns input unchanged)
07 07 07

# SET 42 + HALT (returns 42 regardless of input)
20 2a00000000000000 ff

# SWAP dir=0 slot=0 + ASSERT_GT 900000000
01 00 00 00 40 002f685400000000
```

Paste your hex into the simulate API to test:

```bash
curl -s -X POST https://rpc.aex402.com/v1/strategy/simulate \
  -H "Content-Type: application/json" \
  -d '{"bytecode": "070707", "pools": ["<any_pool>"], "amount": 1000000}'
```

## Quick Reference

### Error Codes

| Code | Name | Meaning |
|------|------|---------|
| 6002 | ERR_MATH | Arithmetic overflow |
| 6003 | ERR_ZERO | Zero amount |
| 6004 | ERR_SLIP | Output < min_out |
| 6005 | ERR_DATA | Invalid instruction data |
| 6025 | ERR_FLASH | Flash loan repayment failed |

### CU Budget

Total budget: 200,000 CU. Worst-case successful strategy: 112,150 CU (56%).

| Op Class | CU | Example |
|----------|-----|---------|
| SWAP | 2500 | Heaviest single op |
| SPLIT/MERGE | 200/100 | Control flow |
| Register ops | 50 | STORE, LOAD, SET |
| Assertions | 50 | ASSERT_GT, ASSERT_NZ |
| Adaptive | 80-200 | ADAPT_SPLIT, PRICE_GUARD |
| Branching | 50-80 | JUMP, CALL, RET |

### Strategy Size

Maximum bytecode: 256 bytes. Typical strategies: 8-30 bytes.

| Strategy | Bytes | Ops |
|----------|-------|-----|
| 2-hop swap | 8 | 2 |
| Split 50/50 | 17 | 6 |
| Adaptive split | 20 | 7 |
| Flash arb | 18 | 6 |
| Compound farm | 24 | 9 |
| Guarded swap | 26 | 4 |
