# Risk rails

> The risk rails on every vault, from DNA limits, the daily loss stop and the drawdown latch to flatten, wind-down and skin in the game.

Source: https://docs.degenhive.ai/vaults/risk

Every vault trades inside three layers of limits. DNA is permanent and set at creation. Risk params are the manager's execution knobs, which tighten at once and loosen only after 7 days. Platform caps come from the council through `HyperVaultConfig`.

> [!IMPORTANT]
> These contracts are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md).

## The rails at a glance

| Rail | Trigger | Effect | Cleared by |
|---|---|---|---|
| Daily loss stop | Equity falls `maxDailyLossBps` below the UTC day's start | Steps revert; anyone may flatten | The next UTC day, automatically |
| Drawdown latch | Live share price falls `maxDrawdownBps` below the high-water mark | Steps, new deposits and `deployToEngine` revert; anyone may flatten | Council `clearDrawdownStop()` only |
| Emergency flatten | Council `setEmergencyFlatten(true)` | Steps revert; anyone may flatten | Council `setEmergencyFlatten(false)` |
| Inactivity | No step or heartbeat for `maxIdleSecs` | Anyone may flatten | The next step or `heartbeat()` |
| Margin floor | Equity over notional below `minMarginRatioBps` | Gross-increasing steps revert; anyone may flatten | Margin back above the floor |
| Wind-down | Manager or council `initiateWindDown()` | Reduce-only, no deposits; anyone may flatten | Never. It is permanent. |

## DNA limits

DNA is copied into the engine at creation and has no setter.

| Field | Bound | Enforced as |
|---|---|---|
| `maxGrossBps` | 5,000–50,000 (0.5x–5x), at most the tier cap | A step may not raise gross above it (`GrossLeverageExceeded`) |
| `maxNetExposureBps` | At most `maxGrossBps` and the tier cap | A step may not raise absolute net above it (`NetExposureExceeded`) |
| `maxDailyLossBps` | 50–1,000 (0.5%–10%) | Daily loss stop |
| `maxDrawdownBps` | 200 to the tier cap; 0 (off) for flagships only | Drawdown latch |
| `marketTier` | 1–3 | Which assets the vault may trade |
| `vaultTier` | `FLAGSHIP`, `INSTITUTIONAL`, `COMMUNITY_ARENA` | Tier ceilings and the per-asset weight multiplier |

Tier ceilings are on [Vaults](https://docs.degenhive.ai/vaults.md#tiers).

## Daily loss stop

At the first engine call of each UTC day, the engine records day-start equity and clears the day's turnover. Every later step or flatten compares live equity with it:

`Daily loss`

```math
lossBps = (dayStartEquity - equity) * 10,000 / dayStartEquity
```

When `lossBps >= maxDailyLossBps`, the engine latches `dayLossStopped` for the rest of the UTC day and emits `DailyLossStopTriggered(day, startEquity, currentEquity)`. Steps then revert with `DayStopped()` and anyone may flatten. The stop clears at the first call of the next UTC day. Moving USDC between vault and engine rescales day-start equity, so deposits and withdrawals do not count as gains or losses.

## Drawdown latch

The latch compares the vault's live share price (`livePricePerShare()`) with its high-water mark, the highest post-fee price any roll has set:

`Drawdown`

```math
drawdownBps = (peak - livePps) * 10,000 / peak
```

When `drawdownBps >= maxDrawdownBps`, the engine latches `drawdownStopped` and emits `DrawdownStopTriggered(highWaterMark, livePricePerShare, maxDrawdownBps)`. While latched:

- steps revert with `DrawdownStopped()`;
- `requestDeposit` and `deployToEngine` revert with `EngineDrawdownStopped()`;
- anyone may flatten;
- redemptions and claims continue.

Only the council can clear it, with `clearDrawdownStop()`. Clearing re-anchors the peak at today's live price, so the vault can trade again without first recovering to the old high-water mark. The stored peak then rises with later rolls and returns to the high-water mark once a roll settles at or above it. USDC in flight between HyperEVM and HyperCore is added back to the live price, so a bridge does not trip the latch.

> [!WARNING]
> Both stops read one instant. `flatten` runs the day and drawdown checks before it checks whether flattening is allowed, so any caller can trip a stop from a single low reading and then close the book. Size `maxDailyLossBps` and `maxDrawdownBps` with intraday noise in mind.

## Emergency flatten

`setEmergencyFlatten(bool active)` is a council switch on each engine. While it is on, steps revert with `DayStopped()` and anyone may flatten. It is reversible and has no delay.

## Inactivity flatten

Every successful step records activity, and so does `heartbeat()`. `maxIdleSecs` (1 to 14 days by default bounds; never 0) sets how long a vault may sit with neither. After that, `isInactive()` is true and anyone may flatten. Nothing closes on its own: a keeper or any outside caller has to send the `flatten` transaction. A manager whose model intentionally holds positions should heartbeat at least once per `maxIdleSecs`.

## Margin floor

`currentMarginRatioBps()` is equity over total notional, in bps. Below `minMarginRatioBps`:

- a step that grows an asset's gross reverts with `MarginRatioTooLow(nextMarginRatioBps, minMarginRatioBps)`;
- anyone may flatten.

The council's floor on `minMarginRatioBps` is 1,000 bps by default (hard minimum 100).

## Flatten

```solidity
function flatten(uint32[] calldata assetIds) external returns (uint256 ordersSent);
function canFlatten() external view returns (bool);
```

`flatten` closes each listed asset in full with a reduce-only IOC order at `maxSlippageBps` and cancels its resting order. It is open to anyone while any of these holds: the daily loss stop, the drawdown latch (or a live breach), emergency flatten, wind-down, inactivity, or the margin floor. Otherwise it reverts with `Unauthorized()`.

- Assets that are flat, have no price, are not listed in the signal book or already received an order this block are skipped, not reverted.
- If closing the batch would raise absolute net above both its prior value and the DNA net cap, the call reverts with `NetExposureExceeded`. Pass hedged legs in the same call.
- IOC orders at a slippage limit may fill partly. Call again until `isFlat()` is true.

When withdrawals are unfunded, depositors have a second permissionless path, `forceDeleveraging` on the vault. See [Depositors](https://docs.degenhive.ai/vaults/depositors.md#unfunded-withdrawals).

## Wind-down

`initiateWindDown()` on the vault closes it for good. On a third-party vault the manager or the council may call it; on a flagship, only the council.

> [!WARNING]
> Wind-down cannot be undone. The vault never accepts deposits or trades toward new positions again.

From that moment:

- `requestDeposit` and `deployToEngine` revert with `VaultWindingDown()`. Pending deposits are refunded at the next roll; depositors collect them with `claimWithdraw()` or cancel before it.
- The engine sets `windingDown`. Every step targets 0, skips the turnover cap, and anyone may flatten. `bridgeUsdcToCore` reverts.
- Rolls, fees, redemptions and claims continue as normal.
- The factory lowers the manager's active vault count.

The manager's own stake stays locked under the skin-in-the-game floor until 14 days after the wind-down, and then only once the withdrawal queue is empty, nothing is unfunded and the engine is flat.

## Markets and asset caps

An asset is tradable for a vault when the council has listed it in `HyperVaultConfig` at a market tier no higher than the vault's `marketTier`, and it is listed in `HyperSignalBook`. Each asset's cap is a share of equity:

1. Start from the asset's override, or the tier default: 25% for tier 1, 10% for tier 2, 3% for tier 3.
2. Multiply by the vault tier's `assetWeightMultiplierBps` (1x, or 4x for `COMMUNITY_ARENA`) and cap at 100%.
3. On flagships, take the lower of that and the signal book market's `maxWeightBps`.
4. On assets HyperCore marks isolated-only, take the lower of that and the adapter's `isolatedCapBps`. CoreWriter cannot set margin mode, so a cap of 0 forces the asset flat.

Targets are clamped to the cap. Portfolio limits come from DNA gross and net. If the council delists or downgrades an asset, existing positions can only be stepped to 0. A market paused in the signal book steps to 0 on its next step.

## Manager skin in the game

When the council turns it on, a third-party manager must keep their own capital in the vault in proportion to outside money. The defaults in `SkinInGameConfig`:

| Field | Default |
|---|---|
| `enabled` | `false` |
| `coInvestMultiplier` | 20 (bounds 1–100) |
| `freeStarterCapUsdc` | 50,000 USDC |
| `dgvBondCreditBps`, `maxDgvShareOfBondBps` | 0. Locked DGV can count toward the stake at token launch. |

`Outside capital limit`

```math
maxExternalTvl = freeStarterCapUsdc + coInvestUsdc * coInvestMultiplier
```

`Manager stake floor`

```math
minCoInvest = ceil((externalTvl - freeStarterCapUsdc) / coInvestMultiplier)
```

Example: a manager with 10,000 USDC in the vault may take up to 50,000 + 10,000 × 20 = 250,000 USDC from others. With 200,000 USDC of outside money, the floor is (200,000 − 50,000) / 20 = 7,500 USDC.

- A deposit that would push outside money past the limit reverts with `VaultCapExceeded(afterTvl, cap)`. The manager's own deposits are exempt.
- A manager redemption, share transfer or claim to another address that would leave less than the floor reverts with `ManagerCoInvestLocked(coInvestUsdc, minRequiredUsdc)`.
- The council can exempt a vault with `setVaultCoInvestExempt`.

## Vault caps

`setVaultCap(capUsdc)` limits NAV plus pending deposits. A manager may set up to `maxCapForManager(manager)` (2,000,000 USDC by default, or a council override); the council has no ceiling. `effectiveVaultCapUsdc()` returns the binding cap after skin in the game. A deposit over it reverts with `VaultCapExceeded(afterTvl, cap)`. Lowering the cap below current TVL only blocks new deposits.

## Changing risk params

```solidity
function updateRiskParams(EngineRiskParams calldata next) external;   // tighten now
function scheduleRiskParams(EngineRiskParams calldata next) external; // any change, ready in 7 days
function executeRiskParams() external;
function cancelRiskParams() external;
```

The manager or the council may call these; the keeper may not. `updateRiskParams` reverts with `RiskLooseningRequiresTimelock()` if any field loosens. A change loosens when it:

- lowers `minMarginRatioBps`;
- raises or removes the turnover cap or the step cap;
- raises `maxSlippageBps` or `makerOffsetBps`;
- changes `defaultTif` to anything but IOC;
- lengthens `maxIdleSecs`.

`scheduleRiskParams` stores the change with `readyAt = now + 7 days` and replaces any pending one, which restarts the clock. `executeRiskParams` reverts with `TimelockNotReady(readyAt)` before then and `NoPendingPolicy()` with nothing pending, and it re-checks the params against the council's current bounds. Depositors can watch `pendingRiskParams()` and the `RiskParamsScheduled` event, and leave before a change they dislike takes effect.

## Related

- [Trading](https://docs.degenhive.ai/vaults/trading.md) The guardrails each step runs.
- [Depositors](https://docs.degenhive.ai/vaults/depositors.md) Withdrawals, unfunded epochs and wind-down refunds.
- [Fees & high-water mark](https://docs.degenhive.ai/vaults/fees.md) How vault fees and high-water marks work.
- [Networks & status](https://docs.degenhive.ai/network.md) Chains, deployment status and API discovery.
