# Security Agent: Sonar

Sonar is Sail's real-time risk intelligence agent. It operates as a continuously active pre-filter to the Sail Engine, scanning every active vault position across all monitored lending protocols on Arbitrum and Base. Sonar gates the optimizer's candidate set before any rebalancing decision is made. The engine never sees flagged positions and never allocates into a vault exhibiting active risk signals.

***

**Architecture**

Sonar maintains two live blacklists:

* **Vault-level kill switch (B\_V):** vaults removed from the optimizer's candidate set.
* **Token-level kill switch (B\_T):** (token, chain) pairs removed from allowed positions.

This two-gate design ensures that risk-mitigating actions are decoupled from yield optimization. No modifications to the objective function or constraint set are required. Flagged positions simply do not exist from the optimizer's perspective.

All on-chain reads are batched via Multicall3 into a single RPC round-trip per chain, ensuring the full detection cycle completes efficiently across all active vault positions simultaneously.

***

**Detection Layer 1: TVL Monitoring**

Sonar monitors Total Value Locked per vault as a rapid liquidity-flight indicator. A vault is flagged for the kill switch if its TVL falls below $500,000, or if TVL drops by 20% or more within a two-hour window. A 20% TVL drop within two hours is a strong signal of informed capital flight that cannot be explained by normal yield rebalancing alone.

***

**Detection Layer 2: Multi-Source Depeg Detection**

Stablecoin depegs represent the most acute risk vector for USD and EUR yield strategies. Sonar employs a multi-source architecture with a numeric severity score (0 to 100) that replaces simple binary flags:

**Price deviation (0 to 40 points).** Authoritative price is sourced from Chainlink latestRoundData() (single-block latency) with CoinGecko as fallback.

**DEX pool imbalance (0 to 25 points).** When a stablecoin begins depegging, informed traders swap out of it on-chain before aggregator prices reflect the move. Sonar measures the fraction of the target token in its primary Uniswap v3 pool. A pool holding more than 50% of one stablecoin has absorbed net sell pressure.

**TWAP divergence (0 to 15 points).** A 30-minute time-weighted average price from the same Uniswap v3 pool provides an independent cross-check against the Chainlink spot price.

**Cross-chain correlation (0 to 20 points).** The same stablecoin depegging simultaneously on multiple chains is a systemic event. If a token accumulates a non-negligible risk score on at least two distinct chains simultaneously, the cross-chain signal fires and the token is immediately blocked across all positions.

Severity thresholds: a score above 60 (or any cross-chain signal) triggers a Critical classification and adds the token to the kill switch. Scores between 30 and 60 are logged as warnings for observability but do not affect allocation.

***

**Detection Layer 3: Lending Market Health**

For vaults deployed to lending protocols, exit feasibility depends on available liquidity in the underlying lending market. Sonar evaluates three signals per vault:

* **High utilization:** supply utilization exceeds 90%.
* **Critical exit feasibility:** a user cannot withdraw more than half their allocated balance due to insufficient liquidity.
* **Elevated borrow rate:** variable borrow APR exceeds 80%, indicating extreme demand pressure.

Exit feasibility is evaluated independently per user. A vault with moderate aggregate utilization may still trigger a kill switch for a specific user whose position size exceeds available liquidity, while remaining open to users with smaller allocations. This per-user resolution prevents unnecessary exclusions for the majority of users.

For Morpho vaults, the collateral dependency tree is traversed to expose indirect risk: a USDC vault backed by wstETH collateral inherits the stETH/ETH depeg risk.

***

**Detection Layer 4: Whale Exit Monitoring**

Large single-transaction withdrawals from a vault are a leading indicator of informed capital flight. Sonar monitors ERC-4626 Withdraw events and classifies them by magnitude:

* A single withdrawal exceeding 10% of vault TVL triggers a Critical classification and adds the vault to the kill switch.
* A withdrawal exceeding 5% triggers a warning for observability.

The whale monitor processes only blocks since the previous scan cycle and completes in a single RPC call per chain.

***

**Detection Layer 5: Protocol Repository Anomaly Detection**

Protocol development teams react to exploits on GitHub before public announcements. Sonar monitors protocol repositories for four signal types:

* **Keyword commits:** pushes to main/master containing terms such as emergency, pause, exploit, hotfix, vulnerability, incident, freeze, hack, attack, drain, reentrancy, overflow, or security.
* **Fast PR merges:** pull requests opened and merged within 2 hours.
* **Off-hours releases:** new release tags published between 00:00 and 06:00 UTC.
* **Direct pushes:** commits pushed directly to main without a merge commit parent, bypassing standard review flow.

Any signal flags all vault addresses belonging to the associated protocol for the vault-level kill switch. Monitored repositories include Aave v3, Morpho (morpho-blue and metamorpho), Euler, Fluid, Compound v3, and Moonwell.

***

**Risk Aggregation**

Each detector owns a private tracking set. The risk aggregator computes the union of all detector outputs into a single authoritative state. When a detector clears a vault (risk resolved), only entries that detector was previously responsible for are removed. Entries contributed by other detectors are preserved.

***

**Performance and Balance Tiers**

Sonar performs even better for higher balance tiers. Larger balances unlock higher execution frequency, meaning that when Sonar detects a risk event, the agent can exit faster and reduce exposure sooner. Sonar has successfully detected and mitigated risks in live market conditions, including depegs, resulting in no user losses to date.

***

**Planned Extensions**

**Statistical baselines and z-score gating.** After sufficient data collection, each monitored metric (utilization, depeg score, TVL) will be gated against its historical distribution. Only deviations exceeding the 30-day mean by more than two standard deviations will escalate to Warn or Critical. This approach mirrors the spike detection mechanism applied to yield signals.

**Sentiment and social signal layer.** Public exploit documentation feeds and community security channels will be integrated as confirmatory signals. Social signals will never directly modify blacklists without on-chain corroboration. They will trigger accelerated on-chain verification runs.
