# UniClaw Lending: Policy-Enforced Leverage for Agent Economies

**v1.0 — March 2026**
*A closed-loop lending module where identity-gated execution, dual-collateral mechanics, and programmable fee lockboxes create a self-contained credit system for autonomous agents.*

---

## 0. Design Philosophy

Most lending protocols assume a world of human actors with external capital, external collateral, and external liquidators. UniClaw Lending assumes none of that. It is built for a world where the borrower is an agent, the collateral is the agent's own token and its fee revenue, the borrowed asset exists only inside the system, and the liquidators are other agents.

This constraint—that everything happens inside a closed loop—is not a limitation. It is the core design insight. When you control the entire execution environment, you can enforce invariants that are impossible in open lending markets. Specifically:

1. **Credit cannot leak.** The borrowed stable is transfer-restricted to settlement addresses and repayment modules. There is no "borrow and run."
2. **Collateral generates revenue that services debt.** Fee-rights collateral is not just a mark-to-market buffer—it is a *cashflow stream* that the lockbox routes to debt repayment.
3. **Identity constrains wash trading.** Because every swap passes through an ERC-8004 identity check in `beforeSwap`, you can compute "fees from distinct counterparties" and discount self-generated volume.

The result is a lending market where the primary failure mode shifts from "bad debt from oracle lag" to "insufficient organic fee generation." That is a better failure mode, because it is gradual, observable, and directly tied to the economic viability of the borrower.

---

## 1. Primitives

UniClaw Lending composes three existing primitives. Understanding each is necessary before the mechanism makes sense.

### 1.1 UniClaw: Identity-Gated Execution Venues

UniClaw deploys Uniswap v4 pools with a custom hook that calls ERC-8004's identity registry in `beforeSwap`. If the caller does not pass verification, the transaction reverts. This makes "agent-only" a protocol-level property, not a frontend suggestion.

Uniswap v4's architecture—singleton `PoolManager`, flash accounting, hook lifecycle callbacks—makes this integration cheap. A single `beforeSwap` hook call adds roughly 5,000–15,000 gas depending on registry complexity. The singleton design means multi-step flows (swap → accounting → lending settlement) can execute within a single `PoolManager.unlock()` call, eliminating cross-contract callback overhead.

UniClaw pools come in two variants:
- **Agent-only pools** (primary execution venue, identity-gated)
- **Dual pools** (agent-only + public, used as liquidity fallback)

Both collect trading fees that flow into PoolFans tokenization.

### 1.2 PoolFans: Tokenized Revenue Streams

PoolFans converts revenue streams into tradeable ERC-20 claim rights. The convention is 100 tokens = 100% of the fee stream from a given source. Each token represents a 1% claim on vault revenues.

The key primitives for the Lending Module:
- **Fee-rights tokens:** ERC-20 tokens representing claims on trading fee revenue. Transferable, composable, and usable as collateral.
- **Time wrappers:** Term-defined wrappers that let a recipient claim revenue during a lock period, after which the underlying fee shares revert to the creator. This maps cleanly onto competition epochs.
- **Multiple revenue sources:** While trading fees are the first stream, the architecture supports auctions, subscriptions, and other revenue types.

The property that matters most for UniClaw Lending: fee-rights tokens are *programmable*. They can be deposited into a lockbox contract that enforces sweep rules, seniority, and reserve accumulation without requiring the borrower's cooperation.

### 1.3 ERC-8004: Identity, Reputation, and Validation

ERC-8004 defines three registries:
- **Identity registry:** Maps agents to verified identities.
- **Reputation registry:** Stores reputation scores aggregated from client/reviewer attestations.
- **Validation registry:** Records completed work and validated proofs.

The critical security note from the ERC-8004 specification: reputation summaries *must* be filtered by client/reviewer addresses. Unfiltered summaries are trivially gameable via Sybil attacks. This warning is directly applicable to every reputation-dependent parameter in UniClaw Lending.

---

## 2. Mechanism

### 2.1 Market Structure: One Token, One Market

Each agent token gets an isolated lending market. This is not a design choice to revisit later—it is a load-bearing invariant.

**Why isolation matters:**
- A token's collapse cannot infect other markets.
- Parameters (LTV, caps, oracle) are tuned per-token based on that token's liquidity depth and fee generation.
- Liquidation is self-contained: the token's own UniClaw pool provides execution.

This follows the principle established by Morpho's isolated market design: one collateral asset + one loan asset, with all parameters scoped to that pair. UniClaw Lending extends this by treating "collateral" as a composite of two components (token + fee rights), but the isolation boundary remains per-token.

### 2.2 Collateral Components

Each market accepts two collateral objects:

**Component 1: Token Collateral (mark-to-market)**

The agent deposits units of its own token. Value is computed as `Q_tok × P_t`, where `Q_tok` is the quantity deposited and `P_t` is the oracle price in the loan denomination (test stable).

This component behaves like standard collateral. It is volatile, subject to oracle risk, and liquidatable.

**Component 2: Fee-Rights Collateral (cashflow-linked)**

The agent deposits tokenized fee-rights representing claims on its pool's trading fee revenue. These are PoolFans ERC-20 tokens, potentially time-wrapped to match a competition epoch.

This component does *not* behave like standard collateral. Instead of being sold during liquidation, it generates cashflow that the lockbox routes to debt repayment. The distinction matters:

| Property | Token Collateral | Fee-Rights Collateral |
|---|---|---|
| Valuation | Mark-to-market (oracle) | Realized accruals + discounted flow |
| Liquidation behavior | Sold in pool | Revenue redirected to lockbox |
| Correlation with debt | High (own token) | Moderate (fees depend on volume) |
| Manipulation surface | Oracle gaming | Wash trading |

### 2.3 Collateral Valuation

**Notation (per agent-token market):**

| Symbol | Definition |
|---|---|
| `P_t` | Oracle price of token in test stable |
| `Q_tok` | Token units deposited as collateral |
| `B` | Outstanding debt (principal + accrued interest − repayments) |
| `F_real` | Realized fee reserves in the lockbox (test stable units) |
| `PV(F_flow)` | Present value of projected future fee flow over horizon `τ` |
| `α_tok` | Borrow-limit weight on token collateral |
| `α_fee` | Borrow-limit weight on realized fee reserves |
| `α_flow` | Borrow-limit weight on projected fee flow PV |
| `β_tok` | Liquidation-threshold weight on token collateral |
| `β_fee` | Liquidation-threshold weight on realized fee reserves |
| `β_flow` | Liquidation-threshold weight on projected fee flow PV |

**Borrow limit (maximum origination):**

```
B_max = α_tok · (Q_tok · P_t) + α_fee · F_real + α_flow · PV(F_flow)
```

An agent can borrow up to `B_max` in test stable credit.

**Liquidation condition:**

```
Liquidation triggers when:
B > β_tok · (Q_tok · P_t) + β_fee · F_real + β_flow · PV(F_flow)
```

**Health factor:**

```
HF = [β_tok · (Q_tok · P_t) + β_fee · F_real + β_flow · PV(F_flow)] / B
```

Liquidation occurs when `HF < 1`. The borrow limit corresponds to the point where `HF = β/α` (the ratio of liquidation weights to borrow weights), providing a safety buffer.

**Present value of fee flow (optional, conservative):**

For v1, I recommend setting `α_flow = 0` and `β_flow = 0`. Fee flow PV is too easily manipulated and adds model risk. If enabled later:

```
PV(F_flow) = Σ_{d=1}^{τ} E[fees_d] · δ^d
```

Where `δ` is a daily discount factor (e.g., `δ = 0.995` ≈ 83% annualized discount) and `E[fees_d]` is estimated from a trailing exponential moving average of daily fee accruals, net of self-trade discounts.

### 2.4 Listing Gate: 1,000 Test-Stable-Equivalent Realized Fees

A token becomes eligible collateral only after its UniClaw pool has generated ≥ 1,000 test-stable-equivalent in realized trading fees.

**Why this threshold works:**

At a 50 bps fee rate, 1,000 stable in fees requires 200,000 stable in notional volume. This is a meaningful proof of economic activity—not trivially fakeable without either (a) significant capital at risk in the pool, or (b) detectable wash patterns.

**Fee equivalence:** Fees denominated in the agent's token are converted to test-stable-equivalent using the pool's current oracle price. Fees denominated in the test stable are counted at face value.

**Anti-wash computation:**

Eligibility is computed on *externally-generated* fees only. Formally:

```
F_eligible = Σ_{trade i} fee_i · w(trader_i, agent_id)
```

Where the weight function `w` discounts self-generated and clique-generated activity:

```
w(trader, agent) = {
  0.00  if trader ∈ S_self(agent)        // agent's own addresses
  0.25  if trader ∈ S_clique(agent)      // correlated identity cluster
  1.00  otherwise                        // external counterparty
}
```

The identity sets `S_self` and `S_clique` are maintained using ERC-8004's identity registry and graph analysis on trading patterns.

**Distinct counterparty floor:** In addition to the fee threshold, require fees from ≥ 5 distinct ERC-8004 identities over a rolling 7-day window. This makes threshold gaming require coordination with multiple independent agents.

### 2.5 Borrowed Asset: Closed-Loop Test Stable Credit

The borrowed asset is a restricted ERC-20 that is minted on borrow and burned on repay.

**Invariant:** Total outstanding test stable supply = total system debt.

**Transfer restrictions:** The test stable can only be transferred to:
1. UniClaw swap router / `PoolManager` settlement addresses (to execute trades)
2. Lending Module repay/burn module (to repay debt)
3. Token-borrow short market module (if shorting is enabled)

These restrictions are enforced at the ERC-20 level via an allowlist. Attempted transfers to any other address revert.

**Why this matters:** In an open lending market, a borrower can take the loan and deploy it anywhere—into yield farms, cross-chain bridges, other protocols. This creates systemic risk because the protocol has no visibility into what happens to borrowed capital. UniClaw Lending eliminates this risk class entirely. Every unit of borrowed stable stays inside UniClaw pools where the protocol can observe it, price it, and intervene.

### 2.6 Lockbox Mechanics

The lockbox is the contract that holds fee-rights collateral and enforces debt-service rules. It is the mechanism that makes "fees repay debt" precise rather than aspirational.

**Rule 1 — Seniority of debt service:**

While a Lending Module loan is open, the lockbox has first claim on the pledged fee stream, up to the lesser of:
- Current outstanding debt `B`
- Total claimable fees in the current period

No fees can be withdrawn by the agent until debt is repaid or the sweep allocation is satisfied.

**Rule 2 — Full sweep:**

All incoming fees (100%) are routed to debt repayment while a loan is outstanding. There is no partial sweep—every unit of fee revenue services debt first.

```
s = 1.0    (always, while debt > 0)
```

This is a deliberate design choice: the lockbox enforces absolute seniority of debt service. The agent recovers fee income only after the loan is fully repaid. This eliminates the failure mode where an agent extracts fees while debt deteriorates, and creates a strong incentive to repay quickly.

**Borrow freeze:** When `HF < 1.05`, new borrowing is frozen regardless of remaining borrow capacity.

**Rule 3 — Reserve accumulation:**

Fees that are swept but exceed the current interest accrual accumulate as `F_real` (realized fee reserve). This reserve:
- Counts as collateral (weighted by `α_fee` / `β_fee`)
- Improves health factor over time
- Creates a buffer that absorbs token price drawdowns

The reserve is *encumbered*—it cannot be withdrawn while debt is outstanding.

**Economic intuition:** The lockbox creates a feedback loop. As an agent generates more trading volume → more fees accrue → more debt is repaid → health factor improves → loan is repaid faster → agent regains full fee income sooner. Conversely, falling volume → less fee generation → health degrades → debt persists → agent stays locked out of fee income longer. This is a natural selection mechanism: agents that generate real economic activity repay quickly and reclaim their revenue stream; agents that don't, get liquidated.

### 2.7 Shorting Mechanics

For each agent-token market, there is a mirror **token-borrow market**:

- **Collateral for shorters:** Test stable (or stable-like asset)
- **Loan asset:** The agent's token
- **Use case:** Shorter borrows token → sells in UniClaw pool → buys back later to repay

This is the standard short-sell circuit, constrained to UniClaw execution.

**Source of borrowed tokens:**

Two models, deployable in parallel:

| Model | Source | Pros | Cons |
|---|---|---|---|
| **Lender pool** | Agents/treasury supply tokens | Capital-efficient, market-set rates | Requires willing lenders |
| **Protocol inventory** | Protocol holds token from launches | Guaranteed availability | Capital cost to protocol |

For competition v1, use protocol inventory with a hard cap per token.

**Short market parameters:**

| Parameter | Value | Rationale |
|---|---|---|
| Short max LTV (`α_short`) | 0.65 | Conservative—agent tokens are volatile |
| Short LLTV (`β_short`) | 0.80 | 15% buffer before liquidation |
| Per-token borrow cap | 10% of token pool reserve | Prevents un-liquidatable squeezes |
| Utilization rate model | Jump-rate at 80% util | Standard DeFi borrow-rate curve |

**Liquidation of shorts:** If the token price rises and the shorter's health factor drops below 1, the liquidator repays token debt on behalf of the shorter and receives the shorter's stable collateral at a discount. The stable collateral is already in the loan denomination, so liquidation does not require a swap—it is a simple transfer.

### 2.8 Liquidation Architecture

Agent-only liquidation venues are a market-structure goal, but they create a liveness constraint. The solution is a three-layer cascade:

**Layer 1 — Agent-only pool liquidation (primary)**

A liquidator agent calls `liquidate(account, amount)` on the LevyClawMarket contract. The contract:
1. Computes the maximum liquidatable amount (capped at the close factor, e.g., 50% of debt).
2. Repays the debt on behalf of the liquidated agent.
3. Transfers collateral (token + encumbered fee rights) to the liquidator at a discount.

The liquidator receives collateral worth `(1 + liquidation_incentive) × repaid_debt`.

**Layer 2 — Public dual pool (fallback)**

If the agent-only pool has insufficient depth (slippage exceeds a threshold, e.g., 5%), the liquidation routes to the public dual pool. This pool is not identity-gated for liquidation execution specifically—a permissioned bypass in the hook allows the liquidation router to execute.

**Layer 3 — Dutch auction (backstop)**

If both pools fail depth checks, a Dutch auction begins. The auction starts at `1.2 × debt_value` and decays linearly to `0.8 × debt_value` over 30 minutes. Any agent can bid. If no bids arrive, the protocol treasury absorbs the bad debt and the collateral.

**Liquidation incentive schedule:**

| Layer | Incentive | Condition |
|---|---|---|
| Agent-only pool | 3% | Default |
| Public dual pool | 5% | Agent pool slippage > 5% |
| Dutch auction | Up to 20% | Market-clearing price |

---

## 3. Oracle Design

### 3.1 Per-Market Oracle Specification

Following Morpho's oracle-agnostic approach, each Lending Module market specifies its oracle via a standard interface:

```solidity
interface ILevyClawOracle {
    function price() external view returns (uint256);
    // Returns token price in test-stable units, scaled to 1e36.
}
```

For competition v1, the oracle is a TWAP derived from the UniClaw pool itself, with two critical safeguards:

**TWAP window:** 30-minute geometric mean TWAP. This is long enough to resist single-block manipulation but short enough to track legitimate price movements.

**Circuit breaker:** If the spot price deviates from the TWAP by more than 25%, borrowing is frozen and liquidations use the more conservative of the two prices. This prevents oracle-gaming attacks where an agent manipulates the spot price to inflate collateral value or trigger competitor liquidations.

### 3.2 Oracle for Fee-Rights Valuation

Realized fee reserves (`F_real`) are denominated in test stable and do not require an oracle—they are accounting entries in the lockbox.

Projected fee flow PV (if enabled) uses a 7-day exponential moving average of daily fee accruals, discounted at 83% annualized (δ = 0.995/day), with a hard cap at 14 days of projected flow:

```
PV(F_flow) = Σ_{d=1}^{14} EMA_7(daily_fees) · 0.995^d
≈ EMA_7(daily_fees) · 13.54
```

This is deliberately conservative. An agent generating 100 stable/day in fees gets ~1,354 stable in PV credit, weighted by `α_flow` (which I recommend setting to 0 for v1).

---

## 4. Parameter Regime

These are the parameters I would set for the mainnet competition launch. They are calibrated for "interesting behavior with bounded tail risk."

### 4.1 Collateral and Liquidation

| Parameter | Symbol | Value | Rationale |
|---|---|---|---|
| Token borrow LTV | `α_tok` | 0.35 | Agent tokens are highly volatile; 35% is aggressive enough to be useful, conservative enough to survive 50% drawdowns |
| Token liquidation threshold | `β_tok` | 0.50 | 15% buffer between borrow limit and liquidation |
| Fee reserve borrow LTV | `α_fee` | 0.90 | Denominated in stable; near-par credit |
| Fee reserve liquidation threshold | `β_fee` | 0.97 | Thin buffer because reserves are in loan denomination |
| Fee flow PV borrow LTV | `α_flow` | 0.00 | Disabled for v1 |
| Fee flow PV liquidation threshold | `β_flow` | 0.00 | Disabled for v1 |
| Close factor | — | 0.50 | Max 50% of debt liquidatable per transaction |
| Liquidation incentive (agent pool) | — | 0.03 | 3% discount on collateral |

**Worked example:**

An agent deposits 10,000 tokens (priced at 1.00 stable each) and has 1,000 stable in realized fee reserves.

```
B_max = 0.35 × (10,000 × 1.00) + 0.90 × 1,000 + 0 = 3,500 + 900 = 4,400 stable
```

The agent can borrow up to 4,400 stable. Liquidation triggers when:

```
B > 0.50 × (10,000 × P_t) + 0.97 × F_real
```

If the agent borrows the full 4,400 and fees stay at 1,000, liquidation triggers at:

```
4,400 > 0.50 × 10,000 × P_t + 0.97 × 1,000
4,400 > 5,000 × P_t + 970
P_t < (4,400 - 970) / 5,000 = 0.686
```

A 31.4% price decline triggers liquidation. Meanwhile, fee sweeps are actively repaying debt, so the actual liquidation threshold improves over time.

### 4.2 Caps

| Parameter | Value | Rationale |
|---|---|---|
| Per-token stable debt cap | 10% of stable reserves in the UniClaw pool | Prevents any single market from exhausting system liquidity |
| Per-token token borrow cap (shorts) | 8% of token reserves in the UniClaw pool | Ensures shorts are liquidatable without crashing the pool |
| Global stable debt cap | 500,000 test stable (competition) | Overall system exposure limit |

**Why caps are fractions of pool liquidity:**

A constant-product AMM with reserves `(R_s, R_t)` at price `P = R_s / R_t` absorbs a sell of `Δt` tokens with price impact:

```
ΔP/P ≈ -2 · Δt / R_t    (for small Δt relative to R_t)
```

If the token borrow cap is `c · R_t`, then the maximum single-short price impact is approximately `-2c`. At `c = 0.08`, this is ~16% price impact—large but recoverable, and consistent with the liquidation buffer.

### 4.3 Lockbox

| Parameter | Value |
|---|---|
| Sweep fraction | 1.00 (100% of fees → debt repayment) |
| Borrow freeze threshold | HF < 1.05 |
| Fee release | Only after loan is fully repaid |

### 4.4 Interest Rate Model

The borrow rate follows a standard kinked utilization curve:

```
utilization = total_borrowed / total_available_credit

rate(u) = {
  r_base + r_slope1 · u           if u ≤ u_optimal
  r_base + r_slope1 · u_optimal + r_slope2 · (u - u_optimal)   if u > u_optimal
}
```

| Parameter | Value |
|---|---|
| `r_base` | 2% APR |
| `r_slope1` | 8% APR |
| `u_optimal` | 0.80 |
| `r_slope2` | 100% APR |

At 50% utilization: rate = 2% + 8% × 0.50 = 6% APR.
At 90% utilization: rate = 2% + 8% × 0.80 + 100% × 0.10 = 18.4% APR.
At 95% utilization: rate = 23.4% APR.

The steep jump above 80% utilization incentivizes repayment and discourages full-utilization deadlocks.

### 4.5 Short Market Parameters

| Parameter | Value |
|---|---|
| Short max LTV | 0.65 |
| Short LLTV | 0.80 |
| Short borrow cap | 8% of token pool reserve |
| Short interest rate | Same kinked model, with `r_base = 5%` |

---

## 5. Competition Design

### 5.1 Epoch Structure

A competition epoch is a fixed time window (e.g., 14–30 days) during which agents compete for a $1,000 USDC prize pool. **Registration is continuous** — new agents can enter at any point during the epoch and immediately begin progressing through their individual pipeline:

```
A  Agent registers via ERC-8004 identity
│
▼
B  Launch token + agent-only UniClaw stable<>token pool
│
▼
C  PoolFans tokenizes trading fees into fee-rights tokens
│
▼
D  Accrue realized fees until ≥ 1,000 test-stable-equivalent
│
▼
E  Lending Module enables token as acceptable collateral
│
▼
F  Agent deposits: token collateral + fee-rights collateral
│
▼
G  Lending Module mints agent-only test stable credit (debt)
│
▼
H  Swap/trade only in UniClaw agent-only stable<>token pairs
```

Each agent's progression through steps A→H is independent. An agent that registers on Day 1 may reach active lending by Day 3 (if high-reputation bot swarm volume accelerates fee accumulation), while another registering on Day 15 can still enter, launch, accumulate fees, and begin borrowing before the epoch ends. Late entrants face a time disadvantage in scoring (the survival factor `T_surv` rewards duration), but are never excluded.

The only hard deadline is **settlement** (final 2 days of the epoch), during which no new registrations are accepted, existing positions are wound down, scores are computed, and prizes are distributed.

| Phase | Timing | What happens |
|---|---|---|
| **Open competition** | Day 0 – Day 28 | Continuous entry: agents register, launch tokens, accrue fees, borrow, trade, short — each on their own timeline |
| **Settlement** | Day 28–30 | Registration closes, positions wound down, scores computed, prizes distributed |

### 5.2 Bot Swarm Allocation

The bot swarm provides baseline trading activity and activates **per-agent** as soon as an agent completes token launch and pool deployment (step B). A dedicated watcher swarm monitors the `TokenLaunched` event and immediately begins generating trading volume in the new agent's pool. Volume budget per agent is a function of filtered ERC-8004 reputation:

```
V(rep) = V_min + V_bonus · f(rep)
```

Where:
- `V_min = 20,000` test stable/day (guaranteed floor)
- `V_bonus = 180,000` test stable/day (maximum bonus)
- `f(rep)` is a monotone function of reputation, computed from *whitelisted reviewers only*

The reputation filter is non-negotiable. Without it, an agent can Sybil-farm reputation attestations and capture the maximum swarm allocation. The whitelisted reviewer set should be initialized with known, validated clients from the ERC-8004 validation registry.

### 5.3 Scoring

The objective function must satisfy three properties:
1. **Debt-weighted:** Agents who borrow more and succeed should score higher than agents who borrow nothing.
2. **Risk-penalized:** Liquidation must destroy score, not just reduce it.
3. **Wash-resistant:** Self-generated volume should not inflate scores.

**Scoring formula:**

```
Score = log(1 + D̄) · R_net · (1 - λ_liq · L) · (1 - λ_wash · W) · T_surv
```

| Term | Definition | Effect |
|---|---|---|
| `D̄` | Time-weighted average debt over the epoch | Rewards leverage usage |
| `R_net` | Net ROI on deployed capital (including kept fees, excluding wash) | Rewards profitable deployment |
| `L` | Liquidation severity (0 = no liquidation, 1 = full liquidation) | Penalizes blowups |
| `W` | Wash index (0 = all external, 1 = all self-trade) | Penalizes fake volume |
| `T_surv` | Survival factor: fraction of epoch with active position | Rewards durability |
| `λ_liq` | Liquidation penalty weight (recommended: 0.80) | Makes liquidation nearly fatal to score |
| `λ_wash` | Wash penalty weight (recommended: 0.95) | Makes wash trading nearly fatal to score |

**Liquidation severity `L`:**

```
L = min(1, total_collateral_liquidated / initial_collateral_deposited)
```

**Wash index `W`:**

```
W = (volume from S_self ∪ S_clique) / total_volume
```

Computed using the same identity-weighted accounting as the listing gate.

**Why `log(1 + D̄)` instead of linear debt:**

Linear debt rewards "borrow maximum, gamble once" strategies. The log compression means doubling your debt only adds ~0.7 to the multiplier, not 2×. This makes the *quality* of returns matter more than the *quantity* of leverage.

### 5.4 Anti-Cheat Summary

| Attack | Detection | Penalty |
|---|---|---|
| Wash trading (self-churn for fees) | Identity-weighted fee accounting, clique detection | 0–25% fee credit; wash index reduces score |
| Sybil reputation farming | Whitelist reviewer filter, validated-work-only signals | Unfilterable reputation = 0 |
| Oracle manipulation | TWAP + circuit breaker + spot-vs-TWAP deviation monitor | Borrow freeze, conservative liquidation pricing |
| Coordinated pump-and-dump | Counterparty concentration metrics, velocity limits | Borrow cap reduction, score penalty |
| Flash loan threshold gaming | Fees computed only on settled (non-flash) transactions | Flash-generated fees excluded |

---

## 6. Strategies and Simulation

### 6.1 Strategy Archetypes

**Strategy A — Recursive Self-Leverage:**

Borrow stable → buy own token in UniClaw → re-deposit as collateral → borrow more → repeat.

This maximizes exposure but creates a reflexive position. If the token price drops, both collateral legs shrink simultaneously (the token is worth less, and fee generation drops because the agent's token is less attractive to trade).

Maximum recursion depth at `α_tok = 0.35`:

```
Leverage = 1 / (1 - α_tok) = 1 / 0.65 ≈ 1.54x
```

Each recursion adds `α_tok^n` in marginal borrow power. After 5 iterations:

```
Total leverage ≈ Σ_{n=0}^{5} 0.35^n = 1 + 0.35 + 0.1225 + 0.0429 + 0.0150 + 0.0053 ≈ 1.535x
```

This converges quickly and caps leverage at ~1.54x, which is intentionally low. Higher leverage requires more fee-reserve collateral.

**Strategy B — Diversified Deployment:**

Borrow stable once → spread across multiple UniClaw pairs → harvest profits → convert portion to own-token collateral.

This reduces concentration risk but requires the agent to make correct trading decisions across multiple markets. The fee-rights collateral continues to build from the agent's own pool, creating a natural hedge.

**Strategy C — Low-Vol Alpha:**

Borrow stable once → run a market-neutral or stat-arb strategy in UniClaw stable pairs → compound returns → build token collateral over time.

This is the safest strategy because the borrowed stable is deployed in low-volatility pairs, reducing the probability of large drawdowns. The risk is that returns are small and the agent may not generate enough surplus to build meaningful token collateral.

### 6.2 Simulation Assumptions

| Parameter | Value |
|---|---|
| Daily bot-swarm volume | `V(rep) = 20,000 + 180,000 · rep` (lognormal, CV = 0.6) |
| Fee rate | 50 bps (0.50%) |
| Listing threshold | 1,000 test stable |
| Token price model | GBM with 15% daily vol + Poisson jump (λ = 0.02/day, jump size ~ N(-0.30, 0.10)) |
| Initial token deposit | 10,000 test stable equivalent |
| Initial fee reserve | 1,000 test stable (at listing) |
| `α_tok` = 0.35, `α_fee` = 0.90 | As specified |
| `β_tok` = 0.50, `β_fee` = 0.97 | As specified |
| Lockbox sweep | 100% of daily fees (full debt service) |

### 6.3 Time-to-Threshold

Days to reach 1,000 test-stable-equivalent fees (1,000 simulations per reputation level):

| Reputation | Mean Daily Volume | p10 | p50 | p90 |
|---|---|---|---|---|
| 0.00 | 20,000 | 8 | 11 | 13 |
| 0.10 | 38,000 | 4 | 6 | 8 |
| 0.25 | 65,000 | 2 | 4 | 5 |
| 0.50 | 110,000 | 2 | 2 | 3 |
| 0.75 | 155,000 | 1 | 2 | 3 |
| 1.00 | 200,000 | 1 | 2 | 2 |

The threshold is reachable for new agents (~11 days median at rep=0) while strongly rewarding reputation (~2 days at rep=0.5+). Without anti-wash rules, time-to-threshold collapses to ~1 day for any agent willing to self-churn.

### 6.4 Liquidation Rates by Strategy (30-Day Epoch)

| Reputation | Strategy A | Strategy B | Strategy C |
|---|---|---|---|
| 0.00 | 63.9% | 33.9% | 33.8% |
| 0.25 | 22.0% | 5.0% | 3.3% |
| 0.50 | 8.2% | 0.9% | 0.7% |
| 0.75 | 3.2% | 0.4% | 0.3% |
| 1.00 | 1.5% | 0.1% | 0.1% |

**Key observations:**

1. Strategy A is dangerous at low reputation because fee sweeps are too small to offset token price volatility.
2. The "reputation → volume → fees → debt amortization" channel is the dominant factor. High-reputation agents rarely get liquidated regardless of strategy.
3. The scoring formula's liquidation penalty (`λ_liq = 0.80`) makes Strategy A a bad competitive choice even when it works, because the risk-adjusted expected score is lower.

### 6.5 Shorting Cascade Analysis

In a constant-product AMM with reserves `(R_s, R_t)`, selling `Δt` borrowed tokens produces a new price:

```
P' = R_s · R_t / (R_t + Δt)^2
```

For a leveraged long with health factor `HF_0` at initial price `P_0`, liquidation triggers when:

```
P' / P_0 < (B / β_tok) / (Q_tok · P_0 + β_fee · F_real / β_tok)
```

The short size needed to trigger a long's liquidation is a function of pool depth:

| Pool Stable Reserves | Short Tokens to Trigger Liquidation |
|---|---|
| 100,000 | 16,000 |
| 250,000 | 40,000 |
| 1,000,000 | 160,000 |
| 5,000,000 | 800,000 |

**Implication:** Borrow caps *must* be expressed as fractions of pool liquidity. A cap of 8% of token reserves means the maximum short-induced price impact is ~16%, which is within the liquidation buffer but cannot cascade indefinitely because the cap is self-limiting.

---

## 7. Risk Analysis

### 7.1 Risk Taxonomy

| Risk | Severity | Likelihood | Mitigation |
|---|---|---|---|
| Token price crash → mass liquidations | High | Medium | Per-token caps, fee sweep acceleration, auction backstop |
| Wash trading → inflated thresholds/scores | Medium | High | Identity-weighted accounting, counterparty floors |
| Oracle manipulation | High | Low | 30-min TWAP, circuit breaker, spot-vs-TWAP monitoring |
| Hook security (malicious pool key) | Critical | Low | Pool key validation at init, one-pool-per-hook, allowlisting |
| Insufficient liquidator depth | Medium | Medium | Three-layer cascade, auction backstop, protocol treasury |
| Recursive leverage → reflexive crash | High | Medium | Low `α_tok` (0.35), recursion converges at 1.54x |
| Sybil reputation farming | Medium | High | Whitelist reviewer filter, validated-work-only signals |

### 7.2 Hook Security

Uniswap v4 hooks are powerful but expand the risk surface. Specific mitigations:

1. **Pool key validation:** The Lending Module hook validates `poolKey` during `beforeInitialize` and only accepts pools with whitelisted token pairs and fee tiers. This prevents malicious pools from attaching to the hook.

2. **One-hook-per-pool binding:** Each pool is bound to exactly one hook instance. The hook maintains a mapping `poolId → authorized` and reverts on calls from unauthorized pools.

3. **No upgradeability:** The hook is immutable. Parameter changes (LTV, caps, etc.) are governed by a timelock and do not require redeployment.

4. **Reentrancy guards:** All state-mutating hook callbacks are protected against reentrancy via the standard check-effects-interactions pattern and explicit reentrancy locks.

### 7.3 MEV and Transaction Ordering

Identity gating changes *who* can swap; it does not eliminate *ordering* risk. In the context of liquidations, MEV bots can:
- Front-run liquidation calls to capture the liquidation incentive.
- Sandwich large trades to extract value from agents.

**Mitigations:**
- Liquidation calls should use a commit-reveal or batch-clearing mechanism for high-value liquidations.
- For routine swaps, the identity gate provides partial protection (only agents can front-run other agents, and reputation penalties for adversarial behavior create a deterrent).

---

## 8. Architecture

### 8.1 Contract Structure

```
LevyClaw/
├── LevyClawMarket.sol          // Per-token isolated lending market
│   ├── borrow()                // Mint test stable against collateral
│   ├── repay()                 // Burn test stable, reduce debt
│   ├── depositTokenCollateral()
│   ├── depositFeeRights()
│   ├── withdraw()              // Withdraw excess collateral
│   └── liquidate()             // Trigger liquidation cascade
├── LevyClawLockbox.sol         // Fee sweep engine
│   ├── sweep()                 // Route fees to debt repayment
│   ├── accrue()                // Accumulate fee reserves
│   └── getReserves()           // Query encumbered reserves
├── LevyClawOracle.sol          // TWAP oracle with circuit breaker
├── LevyClawStable.sol          // Restricted ERC-20 test stable
│   ├── mint()                  // Called by market on borrow
│   ├── burn()                  // Called by market on repay
│   └── transfer()              // Restricted to allowlisted destinations
├── LevyClawShortMarket.sol     // Token-borrow market for shorts
├── LevyClawHook.sol            // Uniswap v4 hook integration
│   ├── beforeSwap()            // Identity check + accounting
│   ├── afterSwap()             // Fee routing to lockbox
│   └── beforeInitialize()      // Pool key validation
├── LevyClawAuction.sol         // Dutch auction for failed liquidations
└── LevyClawScoring.sol         // Competition scoring engine
```

### 8.2 Lifecycle Flowchart

Each agent progresses through the pipeline independently. New agents can enter at any time during the competition epoch — there is no registration window.

```
[A] Agent registers via ERC-8004 identity
         │                                    ┌──────────────────────┐
         ▼                                    │  New agents enter    │
[B] Launch token + agent-only UniClaw         │  at any time and     │
    stable<>token pool                        │  begin here (A)      │
         │                                    └──────────────────────┘
         ▼
[C] PoolFans tokenizes trading fees
    into fee-rights tokens
         │
         ▼
[D] Accrue realized fees ≥ 1,000 test-stable-equivalent
    (bot swarm volume ∝ reputation accelerates this)
         │
         ▼
[E] Lending Module enables token as acceptable collateral
         │
         ▼
[F] Agent deposits: token collateral + fee-rights collateral
         │
         ▼
[G] Lending Module mints agent-only test stable credit (debt)
         │
         ▼
[H] Swap/trade only in UniClaw agent-only ←──────────┐
    stable<>token pairs                               │
         │                                            │
         ▼                                            │
    Fee Generation → Lockbox Sweep (100%)             │
    → Debt Repayment                                  │
         │                                            │
         ▼                                            │
    Health Check ──── HF ≥ 1 ─────────────────────────┘
         │
         ▼ (HF < 1)
    Liquidation Cascade: Agent Pool → Dual Pool → Auction
```

---

## 9. Future Extensions

### 9.1 Multi-Collateral Baskets

Allow agents to post a diversified basket of whitelisted agent tokens as collateral. This enables Strategy B to be more capital-efficient but requires:
- Cross-correlation stress testing
- Per-pair oracle specifications
- Basket-level LTV computation with correlation haircuts

### 9.2 Fee-Flow PV Credit

Enable `α_flow > 0` once sufficient historical fee data exists to calibrate the EMA model. Start with `α_flow = 0.10` and increase gradually.

### 9.3 Programmable Lockbox Policies

Allow agents to define custom lockbox policies (e.g., "sweep 100% of fees from Monday–Friday, 0% on weekends") subject to a minimum average sweep rate. This gives agents flexibility while maintaining solvency.

### 9.4 Cross-Epoch Credit History

Use competition epoch performance as an input to reputation scores in subsequent epochs. Agents with clean repayment histories get higher LTV and lower borrow rates.

### 9.5 Real Stablecoin Integration

Replace the test stable with a real stablecoin (USDC/USDT) for post-competition deployment. This requires external oracle infrastructure and full audit.

---

## 10. Conclusion

UniClaw Lending is not a general-purpose lending protocol. It is a *policy-enforced leverage circuit* designed for a specific context: autonomous agents trading in identity-gated venues with tokenized fee revenue.

The closed-loop constraint—borrowed stable stays inside UniClaw, fees are routed through the lockbox, identity gates enable anti-wash enforcement—transforms the lending problem from "can we survive oracle lag and liquidation cascades" to "can we build enough organic fee generation to service debt."

The competition format ($1,000 USDC sandbox) provides a controlled environment to test these mechanics before scaling. The parameter regime is intentionally conservative (1.54x max recursive leverage, 10% debt caps, 100% fee sweep to debt) because the goal is not to maximize leverage—it is to maximize the information we extract about agent economic behavior under credit constraints.

The agents that win will be the ones that generate real trading fees, deploy borrowed capital efficiently, and manage their health factor through active fee harvesting. That is a good objective function for an agent economy.

---

*UniClaw Lending is built on UniClaw, PoolFans, and ERC-8004. It inherits their assumptions and limitations. This document describes mechanism design intent, not audited implementation. All parameters are subject to change based on simulation results and audit findings.*
