# KRAIKEN Parameter Search Results

## Objective
Map the full 4D optimizer parameter space (CI, AS, AW, DD) after fixing the sqrt price
bug and outstandingSupply inflation (commit `0e2104b`). Primary optimization target:
**maximize fee revenue while staying safe** (trader cannot profit from bull-bear cycles).

## Executive Summary

**The sqrt price bug was the critical issue.** Fixing it makes `capitalInefficiency` (CI)
the dominant safety parameter — it now correctly controls floor placement via VWAP-adjusted
scarcity calculations. All other parameters are secondary.

### Key Findings

| Finding | Detail |
|---------|--------|
| **CI is the safety dial** | CI=0% → 100% safe. CI≥40% → 100% unsafe. Boundary at CI=20-30%. |
| **Fee revenue is parameter-independent** | ~1.5 ETH per bull→bear cycle regardless of CI/AS/AW/DD |
| **No safety-fee trade-off** | Lowering CI to protect the LM costs ZERO fee revenue |
| **AW is the secondary safety factor** | Narrow anchor (AW=20) maximizes LM protection |
| **DD now has measurable (but small) effect** | Higher DD adds ~5 safe combos at boundaries |
| **Optimal safe config** | CI=0%, AS=10%, AW=20, DD=100% — max protection, full fees |

### Bottom Line
**Set CI=0% for maximum safety with zero fee cost.** CI is the only parameter the optimizer
needs to manage for solvency. AS, AW, and DD can be tuned freely for UX and fee optimization
without affecting protocol safety at CI=0%.

## What Changed: The Sqrt Bug Fix

### Before (broken scarcity math)
```solidity
// OLD: _priceAtTick returns price*2^96 (Q96), NOT price^2*2^96
uint256 requiredEthForBuyback = outstandingSupply.mulDiv(sqrt(vwapX96), (1 << 96));
// sqrt(price*2^96) ≈ sqrt(price) * 2^48 — a ~445x OVERESTIMATE of the actual price
```

The old code applied `sqrt()` to a value that was already a linear price (not a squared price).
This produced a buyback requirement ~445x too high, making `ethScarcity` **permanently true**
regardless of actual ETH reserves. Result: the floor ratchet was always on, and CI had zero effect.

### After (corrected)
```solidity
// NEW: vwapX96 IS the price — use directly
uint256 requiredEthForBuyback = outstandingSupply.mulDiv(vwapX96, (1 << 96));
```

Now scarcity triggers when actual floor ETH is insufficient to cover outstanding supply at
VWAP — the intended behavior. CI adjusts VWAP (`adjustedVWAP = 70%*VWAP + CI*VWAP`),
which directly controls how generous the buyback valuation is and thus when scarcity fires.

### OutstandingSupply Fix
Additionally, `outstandingSupply` now conditionally excludes `feeDestination` and `stakingPool` balances:
```solidity
uint256 supply = kraiken.outstandingSupply();  // totalSupply minus LM's own tokens
if (feeDestination != address(0) && feeDestination != address(this)) {
    supply -= kraiken.balanceOf(feeDestination);  // accumulated fee KRK
}
(, address stakingPoolAddr) = kraiken.peripheryContracts();
if (stakingPoolAddr != address(0)) {
    supply -= kraiken.balanceOf(stakingPoolAddr);  // staked KRK
}
```
This has zero effect in the test environment (both balances are 0) but prevents false
scarcity on mainnet where fees accumulate.

## Methodology

### BullBearSweep — Deterministic Bull→Bear Scenario
Each of the 1050 parameter combinations runs an identical scenario:

| Phase | Action | Details |
|-------|--------|---------|
| **Setup** | Deploy fresh environment | LM funded with 200 ETH, initial recenter |
| **Bull** | 10 buys × 15 ETH | Total 150 ETH spent, recenter every 3 buys |
| **Transition** | Final recenter | Records VWAP, redeploys positions |
| **Bear** | Sell all KRK | Multiple sell attempts with recenters between |
| **Measure** | Trader PnL | `final_WETH - initial_WETH` (negative = LM gain) |

### Full 4D Parameter Space (1050 combos)

| Parameter | Values | Count |
|-----------|--------|-------|
| capitalInefficiency | 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 100% | 10 |
| anchorShare | 10%, 20%, 30%, 40%, 50%, 70%, 100% | 7 |
| anchorWidth | 20, 40, 60, 80, 100 | 5 |
| discoveryDepth | 20%, 50%, 100% | 3 |
| **Total** | | **1050** |

### Metrics Tracked (19 per combo)
- **trader_pnl**: Trader's ETH gain/loss. Primary safety metric (negative = safe).
- **lm_net_gain**: LM ETH gained over the cycle.
- **drawdown_bps**: Peak-to-trough LM ETH drop during bear phase.
- **fee_weth_total / fee_krk_total**: Fee revenue at `feeDestination`.
- **floor_moved**: Whether the floor position shifted during the cycle.
- **sell_attempts**: Rounds needed to liquidate all KRK.

## Results

### 1. Safety by CI Value

| CI | Safe | Unsafe | Safe % | Avg Trader PnL (ETH) | Avg LM Net Gain (ETH) |
|----|------|--------|--------|-----------------------|------------------------|
| **0%** | **105** | 0 | **100%** | -21.69 | +20.21 |
| **10%** | **87** | 18 | **83%** | -10.72 | +9.24 |
| **20%** | **55** | 50 | **52%** | +0.34 | -1.82 |
| **30%** | **20** | 85 | **19%** | +11.40 | -12.88 |
| 40% | 0 | 105 | 0% | +21.54 | -23.02 |
| 50% | 0 | 105 | 0% | +30.87 | -32.35 |
| 60% | 0 | 105 | 0% | +38.29 | -39.77 |
| 70% | 0 | 105 | 0% | +44.38 | -45.86 |
| 80% | 0 | 105 | 0% | +49.37 | -50.85 |
| 100% | 0 | 105 | 0% | +55.70 | -57.18 |

**Total: 267 safe / 783 unsafe out of 1050 combos.**

CI is the dominant safety control. The PnL crossover is between CI=10% (avg -10.72) and
CI=20% (avg +0.34). Each 10% CI increment shifts average PnL by ~10 ETH toward traders.

### 2. Fee Revenue — Completely Parameter-Independent

| Dimension | Values Tested | Avg feeWethTotal | Range |
|-----------|--------------|-----------------|-------|
| CI (0-100%) | 10 values | 1.4814 ETH | ±0.000 |
| AS (10-100%) | 7 values | 1.44-1.50 ETH | 0.06 |
| AW (20-100) | 5 values | 1.43-1.50 ETH | 0.07 |
| DD (20-100%) | 3 values | 1.48 ETH | ±0.004 |

**Fee revenue is 1.50 ETH for 87.6% of combos.** The remaining 12.4% earn 1.35 ETH (10% less),
occurring only at high-AS + low-AW configurations (AS≥50% with AW=20, AS=100% with AW≤40).

**KRK fees are zero** across all 1050 combos — all fee revenue is WETH-denominated.

**Critical implication: there is NO trade-off between safety and fee revenue.** Setting CI=0%
for maximum protection earns identical fees as CI=100% (which bleeds 55+ ETH to traders).

### 3. CI=0% — Full Safety with Fee Revenue

All 105 combos at CI=0% are safe. Trader PnL matrix (ETH, avg across DD):

| AS \ AW | 20 | 40 | 60 | 80 | 100 |
|---------|------|------|------|------|------|
| **10%** | **-43.1** | -42.9 | -37.6 | -29.3 | -16.0 |
| **20%** | -39.1 | -38.2 | -33.1 | -23.7 | -13.2 |
| **30%** | -34.8 | -33.2 | -27.8 | -18.3 | -8.6 |
| **40%** | -29.9 | -28.2 | -22.5 | -14.3 | -6.5 |
| **50%** | -25.5 | -25.0 | -19.6 | -13.6 | -6.0 |
| **70%** | -20.2 | -20.1 | -16.9 | -11.8 | -7.4 |
| **100%** | -14.1 | -12.4 | -11.1 | -8.8 | -6.6 |

Every cell is negative (safe). The worst case (AS=100%, AW=100) still costs the trader 6.6 ETH.
At CI=0%, **the entire AS/AW/DD space is available for free tuning** without safety concerns.

Fee revenue at CI=0%:

| AS \ AW | 20 | 40 | 60 | 80 | 100 |
|---------|------|------|------|------|------|
| 10% | 1.50 | 1.50 | 1.50 | 1.50 | 1.50 |
| 20% | 1.50 | 1.50 | 1.50 | 1.50 | 1.50 |
| 30% | 1.50 | 1.50 | 1.50 | 1.50 | 1.50 |
| 40% | 1.45* | 1.50 | 1.50 | 1.50 | 1.50 |
| 50% | 1.35 | 1.50 | 1.50 | 1.50 | 1.50 |
| 70% | 1.35 | 1.50 | 1.50 | 1.50 | 1.50 |
| 100% | 1.35 | 1.35 | 1.50 | 1.50 | 1.50 |

*Mixed across DD values. Only high-AS/low-AW combos see a minor 10% fee reduction.

### 4. Safe/Unsafe Boundary Maps

For each (CI, AS, AW), shows whether ALL DD values are Safe (S), ALL Unsafe (U), or Mixed (M):

#### CI=10% (83% safe overall)
```
AS\AW     20    40    60    80   100
10%        S     S     S     S     M
20%        S     S     S     S     M
30%        S     S     S     S     U
40%        S     S     S     S     U
50%        S     S     S     S     U
70%        S     S     S     S     U
100%       S     S     S     S     U
```
Only AW=100 is problematic at CI=10%. All narrow-anchor combos are safe.

#### CI=20% (52% safe overall)
```
AS\AW     20    40    60    80   100
10%        S     S     S     M     U
20%        S     S     S     M     U
30%        S     S     S     U     U
40%        S     S     M     U     U
50%        S     S     U     U     U
70%        S     S     U     U     U
100%       S     S     U     U     U
```
The unsafe zone expands to AW≥60 for high AS. Low AS (10-20%) remains safe through AW=80.

#### CI=30% (19% safe overall)
```
AS\AW     20    40    60    80   100
10%        S     S     M     U     U
20%        S     S     U     U     U
30%        S     U     U     U     U
40%        M     U     U     U     U
50%        M     U     U     U     U
70%        U     U     U     U     U
100%       U     U     U     U     U
```
Only the tightest configs (low AS + low AW) remain safe. AS≥70% is universally unsafe.

**Pattern**: The safe boundary sweeps diagonally — lower CI allows wider anchor/higher share.
At any CI, you can trade AS for AW along iso-safety curves.

### 5. Discovery Depth: Measurable but Small Effect

#### DD impact on safety boundary (8 combos where DD flips outcome):

| CI | AS | AW | DD=20% PnL | DD=50% PnL | DD=100% PnL | Pattern |
|----|----|----|-----------|-----------|------------|---------|
| 10% | 10% | 100 | +7.77 (U) | -3.19 (S) | -8.59 (S) | Higher DD saves |
| 10% | 20% | 100 | +6.63 (U) | +0.53 (U) | -1.93 (S) | Only DD=100% safe |
| 20% | 10% | 80 | +4.18 (U) | -2.67 (S) | -6.46 (S) | Higher DD saves |
| 20% | 20% | 80 | +7.46 (U) | +3.20 (U) | -0.05 (S) | Barely safe at DD=100% |
| 20% | 40% | 60 | +1.11 (U) | -0.12 (S) | +0.26 (U) | Non-monotonic |
| 30% | 10% | 60 | +0.79 (U) | -2.32 (S) | -2.43 (S) | Higher DD saves |
| 30% | 40% | 20 | +1.07 (U) | -0.82 (S) | -0.81 (S) | Higher DD saves |
| 30% | 50% | 20 | +0.71 (U) | +0.80 (U) | -0.95 (S) | Only DD=100% safe |

In 7 of 8 boundary cases, higher DD improves safety. The mechanism: more discovery liquidity
density provides additional sell-side absorption, slightly reducing the trader's exit proceeds.
Combo #5 (CI=20%, AS=40%, AW=60) shows a non-monotonic anomaly — likely a precision effect
at the exact boundary.

#### DD within safe combos (negligible):

| DD | Avg PnL (ETH) | Avg feeWethTotal (ETH) | Safe Count |
|----|---------------|----------------------|------------|
| 20% | -15.08 | 1.479 | 85 |
| 50% | -15.09 | 1.473 | 90 |
| 100% | -15.40 | 1.479 | 92 |

DD changes the safe count by only 7 combos (85→92) across the entire space. Within safe
combos, its effect on PnL and fees is negligible.

### 6. Drawdown Analysis

Average drawdown (bps) during the bear sell-off:

| CI | Avg Drawdown | Interpretation |
|----|-------------|---------------|
| 0% | 3681 bps (36.8%) | LM absorbs sell pressure well |
| 10% | 3996 bps (40.0%) | |
| 20% | 4313 bps (43.1%) | |
| 30% | 4631 bps (46.3%) | |
| 40% | 4922 bps (49.2%) | |
| 50% | 5189 bps (51.9%) | |
| 60% | 5402 bps (54.0%) | |
| 70% | 5577 bps (55.8%) | |
| 80% | 5720 bps (57.2%) | |
| 100% | 5901 bps (59.0%) | LM gives back most of peak ETH |

Drawdown scales linearly with CI. Even at CI=0%, the LM experiences ~37% drawdown during
a 150 ETH bull-to-bear cycle, but **recovers to a net gain** (20.21 ETH average).
At CI≥40%, the LM never recovers — drawdown exceeds 100% of the bull gains.

### 7. Secondary Parameter Impact (at CI=0%)

Since CI=0% is universally safe, the other parameters only affect *how much* the LM gains:

| Parameter | Range | PnL Impact | Fee Impact |
|-----------|-------|-----------|-----------|
| **AW** (anchor width) | 20→100 | 27 ETH (strongest secondary) | <5% |
| **AS** (anchor share) | 10%→100% | 29 ETH | <10% |
| **DD** (discovery depth) | 20%→100% | 0.3 ETH (negligible) | <0.5% |

AW and AS have roughly equal impact at CI=0%. Both affect how much ETH the LM keeps
during the bear phase, but neither threatens safety.

### 8. Floor Movement

Floor moves in 99.7% of combos (1047/1050). The 3 static-floor combos are all at CI=0%
with moderate AS (40-50%) and AW=20 — the floor is placed so conservatively that the
sell-off never reaches it. Floor movement does NOT correlate with safety — both safe
and unsafe combos have floor_moved=true.

## Parameter Sensitivity Ranking

From most to least impactful:

1. **capitalInefficiency** — THE safety dial. Each +10% shifts avg PnL by ~10 ETH toward traders.
   CI=0%: 100% safe. CI≥40%: 100% unsafe. **Must be actively managed.**
2. **anchorWidth** — Secondary safety factor. Each +20 ticks increases avg PnL by ~8 ETH.
   Narrow anchor (20) maximizes resistance; wide (100) allows more traversal.
3. **anchorShare** — Tertiary. Higher AS means less floor ETH. Effect is ~5 ETH per +20%.
4. **discoveryDepth** — Negligible for safety (<1 ETH across full range). Only matters at
   exact boundary conditions (8 out of 1050 combos).

## Recommended Configuration

### For Maximum Safety: CI=0%
```
capitalInefficiency = 0              (0%)
anchorShare         = 200000000000000000  (20%)
anchorWidth         = 60             (60 ticks)
discoveryDepth      = 500000000000000000  (50%)
```

**Rationale:**
- CI=0% guarantees safety across the ENTIRE AS/AW/DD space
- AS=20% provides moderate anchor liquidity for fee capture (1.50 ETH)
- AW=60 balances concentrated liquidity (fees) with sell resistance
- DD=50% is a neutral choice (DD has negligible effect)
- Trader loses ~33 ETH out of 150 ETH round trip (22% loss)
- LM drawdown ~33% during bear, recovers to net +31 ETH gain

### Adaptive Strategy
The optimizer should treat CI as a risk dial:

| Market Regime | CI | AS | AW | Rationale |
|--------------|-----|-----|-----|-----------|
| **Conservative** | 0% | 10-20% | 20-40 | Maximum protection; floor at 30% discount |
| **Balanced** | 0% | 20-30% | 60-80 | Full safety with broader fee capture |
| **Growth** | 10% | 30-50% | 60-80 | 83% safe; more anchor liquidity |
| **NEVER** | ≥40% | any | any | Universally unsafe |

### Why Not CI>0%?
At CI=0%, adjusted VWAP = 70% of raw VWAP (floor at 30% discount). This means:
- The floor buys KRK at a 30% discount to recent trading price
- This is highly protective — traders selling into the floor get terrible prices
- Fee revenue is IDENTICAL to higher CI values
- There is literally zero benefit to increasing CI in the current model

The only reason to increase CI would be if the 30% discount floor prevents organic
price discovery — but the BullBearSweep shows this doesn't happen (anchor and discovery
positions handle normal trading; the floor only matters during sell-offs).

## Raw Data

Full results: `analysis/sweep-FULL-4D-summary.csv` (1050 rows)

### CSV Schema
```
ci,anchor_share,anchor_width,discovery_depth,trader_pnl,bull_spent,
lm_eth_start,lm_eth_after_bull,lm_eth_end,lm_retention_pct,floor_moved,
lm_eth_trough,drawdown_bps,sell_attempts,lm_net_gain,
fee_weth_bull,fee_krk_bull,fee_weth_total,fee_krk_total
```

All monetary values in wei (18 decimals). CI/AS/DD scaled to 18 decimals.
AW in raw tick count. drawdown_bps and retention_pct in basis points.

---
*Generated: 2026-02-08*
*Sweep: 1050 combos (10 CI x 7 AS x 5 AW x 3 DD) via BullBearSweep.s.sol*
*Commit: 0e2104b (sqrt price bug + outstandingSupply fix)*
*Branch: fix/floor-ratchet*
