- Analysis: parameter sweep scripts, adversarial testing, 2D frontier maps - Research: KRAIKEN_RESEARCH_REPORT, SECURITY_REVIEW, STORAGE_LAYOUT - FuzzingBase: consolidated fuzzing helper, BackgroundLP simulation - Sweep results: CSV data for full 4D sweep (1050 combos), bull-bear, AS sweep, VWAP fix validation - Code quality: .gitignore for fuzz CSVs, gas snapshot, updated docs - Remove dead analysis helpers (CSVHelper, CSVManager, ScenarioRecorder) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
9.3 KiB
Agent Brief: Kraiken Protocol
Protocol Philosophy & Business Logic
What KRAIKEN is: A token with a self-managing liquidity manager (LM) on Uniswap V3. The LM positions liquidity across three positions (floor, anchor, discovery) and recenters them as price moves. An optimizer adjusts parameters based on staking sentiment.
Revenue model: TRANSACTION FEES are the product.
- Every swap through the LM's positions generates Uniswap LP fees
- Fees (WETH + KRK) flow to
feeDestination— this is what founders withdraw - Locked ETH in the protocol has NO value to founders — it's locked forever
- More trading volume = more fees = more revenue
- The protocol WANTS active trading, even if traders extract some ETH
Bull market behavior (desired):
- Encourage risk-taking: wide anchor, big discovery → catch more trades, earn more fees
- Floor can be minimal — ETH abundance means low risk
- Parameters should maximize fee capture, not protect locked ETH
Bear market behavior (desired):
- Protect the floor: prevent catastrophic ETH drain
- But NOT at the expense of killing all trading — some exposure is acceptable
- The question is always: does protecting X ETH cost more in lost fees than it saves?
The optimization target is NOT "minimize trader PnL". It is "maximize fee revenue while keeping the protocol solvent." Trader losses beyond what's needed for solvency represent missed fee opportunities.
Key mechanism: Floor placement
The floor position protects protocol solvency by holding ETH far from the current price. Its tick is computed as:
floorTick = max(scarcityTick, mirrorTick, clampTick) toward KRK-cheap side
Three signals determine the floor:
- scarcityTick: derived from
vwapX96and ETH/supply ratio. Correct when ETH is scarce. - mirrorTick:
currentTick + |adjustedVwapTick - currentTick|on KRK-cheap side. Reflects VWAP distance symmetrically. UsesgetAdjustedVWAP(CI). - clampTick: minimum distance from anchor edge.
anchorSpacing = 200 + (34 × 20 × AW / 100)ticks.
There is no EthScarcity/EthAbundance branching — the unified formula takes the max of all three signals.
VWAP mirror defense: During sell-heavy trading, the current tick drops but the VWAP stays higher, so the mirror distance grows — the floor naturally resists being walked down. CI controls mirror distance through getAdjustedVWAP(CI) with no magic numbers.
Directional VWAP recording: VWAP only records on ETH inflow (buys into the LM), preventing attackers from diluting VWAP with sells. shouldRecordVWAP compares lastRecenterTick to current tick to detect direction. Bootstrap: always records when cumulativeVolume == 0. (Commits c97714c + ba018c4.)
Four optimizer parameters:
capitalInefficiency (CI)— adjusts VWAP for floor placement: adjustedVWAP = 70%VWAP + CIVWAP. Zero effect on fee revenue — pure risk lever. CI=0% is safest.anchorShare (AS)— ETH split between floor and anchor (low AS = more floor, high AS = more anchor)anchorWidth (AW)— how wide the anchor position is in ticksdiscoveryDepth (DD)— discovery position liquidity density. Zero effect on floor safety.
Parameter safety (2D frontier):
Only extreme AS×AW configurations survive adversarial attack:
| Config | Safe | Why |
|---|---|---|
| AS ≤ 35%, AW = 100 | Yes | Wide clamp (7000 ticks) prevents floor drain. Thin anchor = less ETH for attacker. |
| AS ≥ 50%, AW = 20 | Yes | Thin concentrated anchor near price. Floor far away with minimal ETH. |
| AW 40-80 at most AS | No | Kill zone — moderate depth AND moderate clamp distance. |
Design principle: Fix root causes, don't add band-aids. Safety comes from the parameter space, not from position ratchets or overrides.
Optimizer V3
src/OptimizerV3.sol — UUPS upgradeable. Uses on-chain Harberger staking data to switch between safe bear and aggressive bull configurations.
Inputs: percentageStaked (0-100%), averageTaxRate (maps to effective index 0-29 in discrete tax array, with +1 shift at index ≥14)
Direct 2D mapping — no intermediate score:
staked ≤ 91%→ always BEAR (no euphoria signal)staked > 91%→ BULL ifdeltaS³ × effIdx / 20 < 50, else BEARdeltaS = 100 - stakedPct(0-8 range)- Bull requires high staking AND low tax. Any decline snaps to bear instantly.
Binary parameter output:
- BEAR: AS=30%, AW=100, CI=0, DD=0.3e18
- BULL: AS=100%, AW=20, CI=0, DD=1e18
The binary step avoids the AW 40-80 kill zone entirely. ~94% of the staking state space maps to bear.
Harberger Staking Triangle Cycle
The staking system naturally traces a triangle in (staking%, avgTax) space:
Phase 1 — Fill up (bottom edge): Staking grows 0→100%, tax starts low. Optimizer stays bear. Transitions to bull at ~95% staked.
Phase 2 — Snatching wars (right edge): 100% staked, snatching wars push average tax rate up. Always bull. Euphoria overwhelms tax cost.
Phase 3 — Collapse (hypotenuse): Nervous exits. High tax + declining staking → cubic term snaps to bear within 4-6% staking drop.
Game theory validates this trajectory — incentive structures force participants through this cycle.
System Snapshot
- Solidity/Foundry DeFi protocol built around the Kraiken ERC20 token, a staking auction, and a three-position Uniswap V3 liquidity manager.
- LiquidityManager.sol mints/burns supply to maintain ANCHOR (near price), DISCOVERY (offset discovery band), and FLOOR (VWAP-protected) positions with asymmetric slippage to resist arbitrage.
- VWAPTracker.sol stores squared price in X96 format, compresses history, and feeds adjusted VWAP data for FLOOR placement. VWAP records directionally (ETH inflow only).
- OptimizerV3.sol (UUPS upgradeable) reads staking sentiment to output capitalInefficiency, anchorShare, anchorWidth, and discoveryDepth via a direct 2D binary mapping.
- Stake.sol runs the self-assessed tax staking system with snatching auctions, discrete tax brackets, and redistribution to tax recipients/UBI.
Development Workflow
- Tooling: Foundry (
forge build,forge test,forge fmt,forge snapshot), Anvil for local chain, Base Sepolia deployment script (forge script ...BaseSepoliaDeploy). - Repo structure highlights:
src/(core contracts),test/helpers/(Uniswap/Kraiken bases),lib/uni-v3-lib(math + JS setup),script/(deploy),out/(artifacts), config viafoundry.toml&remappings.txt. - Setup steps: clone repo, init/update submodules (
git submodule update --init --recursive), installlib/uni-v3-libdependencies (npm installinlib/uni-v3-lib/), ensure Foundry installed. - ABI Architecture: Contract ABIs are exported via
kraiken-lib/src/abis.ts, which imports directly fromonchain/out/(forge build artifacts). All consumers (ponder, web-app) import from kraiken-lib for type-safe, single-source-of-truth ABIs. Runforge buildinonchain/to update ABIs across the stack.
Containerized Builds (Podman/Docker)
- Git Submodules: Must be initialized before building (
git submodule update --init --recursive). Emptylib/directories cause compilation failures. - uni-v3-lib Dependencies: Requires
npm installinlib/uni-v3-lib/to populatenode_modules/with Uniswap interfaces (IUniswapV3Pool, IUniswapV3Factory) and solady dependencies. - Foundry Image: Use
ghcr.io/foundry-rs/foundry:latestfor containers. The image includesforge,cast,anvilbut NOTjqorcurl. - Root Access: Bootstrap scripts that create deployment artifacts may need to run as root (user: "0:0") to write to mounted volumes.
- Volume Permissions: Use
:z(shared SELinux label) instead of:Z(private) for multi-container access to the same mount.
Strategy & Mechanics
- Outstanding supply excludes liquidity position balances and KRK held by
feeDestination/stakingPool; enforce 20% staking cap (~20k positions). - Anchor width and discovery depth adjusted dynamically; anchorShare tunes ETH allocation, discoveryDepth controls liquidity density multiples, capitalInefficiency shifts VWAP floor valuation (70%-170%).
token0isWethflag flips meaning of amount0/amount1 to ETH/KRAIKEN respectively.- Recenter logic keeps Uniswap positions aligned; floor placement uses
vwapX96directly (not sqrt) in fixed-point math.
Testing & Analysis Suite
- Fuzzing scripts under
analysis/support configurable trade/stake biases, adversarial attack patterns, background LP competition, and parameter sweeps. Seeanalysis/README.mdfor full details. - Adversarial testing (
run-adversarial.sh,run-v3-adversarial.sh) validates floor defense against sell-heavy attacks. - Background LP fee analysis (
run-bglp-fee-test.sh) measures fee retention under LP competition. - On-chain LP scanner (
scan-final.py) compares real Uniswap V3 LP distributions to the BackgroundLP model. - Recorded artifacts include CSV tick traces, frontier maps, and human-readable summaries for exploit triage.
Guardrails & Conventions
- Respect access controls (
onlyLiquidityManager, owner) and avoid editing implementation helpers like LiquidityProvider or ThreePositionStrategy. - Debug tips: inspect position CSVs, verify token type assumptions, and check VWAP recording direction during simulations.
- Staking positions tracked by
positionId; tax rates drawn from discrete array within Stake.sol.