> ## Documentation Index
> Fetch the complete documentation index at: https://ouroborai.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Lending

> Supply and borrow on Aave V3 with health monitoring

Supply assets to earn yield, borrow against your collateral, and monitor your health factor -- all through natural language commands powered by the Aave V3 integration on Arbitrum.

## Aave V3 on Arbitrum

The `AaveV3Adapter` integrates with the Aave V3 lending pool on Arbitrum One, providing four core operations:

<CardGroup cols={2}>
  <Card title="Supply" icon="arrow-up">
    Deposit assets to earn variable yield. You receive aTokens that represent your position and accrue interest continuously.
  </Card>

  <Card title="Borrow" icon="arrow-down">
    Borrow assets against your supplied collateral at variable interest rates. Requires sufficient health factor.
  </Card>

  <Card title="Repay" icon="rotate-left">
    Repay outstanding borrows partially or in full. Pass the maximum uint256 value to repay the entire debt.
  </Card>

  <Card title="Withdraw" icon="arrow-right-from-bracket">
    Withdraw supplied collateral by burning aTokens. Pass the maximum uint256 value to withdraw everything.
  </Card>
</CardGroup>

## How It Works

### Supplying Assets

When you supply an asset to Aave V3:

1. The agent approves the Aave V3 Pool to pull your tokens
2. Calls `pool.supply(asset, amount, onBehalfOf, referralCode)`
3. You receive an equivalent amount of **aTokens** (e.g., supply USDC and get aUSDC)
4. Your aToken balance increases over time as interest accrues

<Info>
  aTokens are rebasing -- their balance grows in your wallet automatically. There is no need to claim or harvest yield.
</Info>

### Borrowing Assets

To borrow, you must first supply collateral. The amount you can borrow depends on the loan-to-value (LTV) ratio of your collateral asset.

1. The agent calls `pool.borrow(asset, amount, interestRateMode, referralCode, onBehalfOf)`
2. Borrowed tokens are transferred to your wallet
3. Your debt accrues interest at the variable rate

<Warning>
  Borrowing reduces your health factor. If it drops below 1.0, your position becomes eligible for liquidation. The agent monitors this and warns you proactively.
</Warning>

### Repaying Debt

Repaying works in two modes:

* **Partial repay**: specify the exact amount to repay
* **Full repay**: the agent passes `type(uint256).max` to clear the entire debt including accrued interest

The agent approves the pool to pull your tokens before submitting the repay transaction.

### Withdrawing Collateral

Withdrawal burns your aTokens and returns the underlying asset. Withdrawing collateral reduces your health factor, so the agent checks that the withdrawal will not put your position at liquidation risk.

## Health Factor

The health factor is the single most important metric for lending positions. It represents how safe your position is from liquidation.

| Health Factor | Status                                 |
| ------------- | -------------------------------------- |
| > 2.0         | Safe -- comfortable margin             |
| 1.5 - 2.0     | Moderate -- consider adding collateral |
| 1.0 - 1.5     | At risk -- close to liquidation        |
| \< 1.0        | Liquidatable -- anyone can liquidate   |

The agent fetches your health factor via `pool.getUserAccountData(address)`, which returns:

| Field                         | Description                                  |
| ----------------------------- | -------------------------------------------- |
| `totalCollateralBase`         | Total collateral value in USD (8 decimals)   |
| `totalDebtBase`               | Total debt value in USD (8 decimals)         |
| `availableBorrowsBase`        | Remaining borrowing capacity                 |
| `currentLiquidationThreshold` | Weighted liquidation threshold               |
| `ltv`                         | Current loan-to-value ratio                  |
| `healthFactor`                | Position health (18 decimals, > 1e18 = safe) |

<Tip>
  Ask the agent "what's my health factor?" at any time to get a snapshot of your Aave position. The agent will flag positions below 1.5 as requiring attention.
</Tip>

## Liquidation Monitor Contract

For proactive health monitoring at scale, the platform includes a **LiquidationMonitor** Stylus contract written in Rust. This contract runs on-chain with 10-100x gas savings compared to equivalent Solidity.

### Dynamic Protocol Registry

The LiquidationMonitor maintains a registry of lending and perp protocols using indexed mappings:

* **Lending protocols**: Aave V3 pools (extensible to Radiant, Compound V3)
* **Perp protocols**: GMX V2 readers (future)
* **Soft-delete pattern**: protocols can be deactivated without reindexing

### How Scanning Works

1. The contract stores a list of tracked account addresses
2. A configurable `risk_threshold` defines the health factor warning level
3. When `scanAccounts()` is called, it iterates through tracked accounts and checks each against all registered lending protocols
4. Accounts below the risk threshold emit an `AccountAtRisk` event with the health factor and timestamp

### Events

The contract emits events that the off-chain agent can monitor:

| Event                    | Description                                                        |
| ------------------------ | ------------------------------------------------------------------ |
| `AccountAtRisk`          | Fired when a tracked account's health factor drops below threshold |
| `AccountAdded`           | New account added to the monitoring list                           |
| `AccountRemoved`         | Account removed from monitoring                                    |
| `ThresholdUpdated`       | Risk threshold changed by the owner                                |
| `LendingProtocolAdded`   | New lending protocol registered                                    |
| `LendingProtocolRemoved` | Lending protocol deactivated                                       |

<Note>
  The LiquidationMonitor is a Stylus contract that compiles to WASM and runs on the Arbitrum Stylus VM. It is not yet deployed to mainnet -- see the [deployment guide](/docs/guides/deploy-contracts) for instructions.
</Note>

## Contract Addresses

| Contract              | Address                                      |
| --------------------- | -------------------------------------------- |
| Aave V3 Pool          | `0x794a61358D6845594F94dc1DB02A252b5b4814aD` |
| Aave V3 Data Provider | `0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654` |
| Aave V3 Oracle        | `0xb56c2F0B653B2e0b10C9b928C8580Ac5Df02C7C7` |

## Example Prompts

```
Supply 1000 USDC to Aave
```

```
Borrow 0.5 ETH against my USDC collateral
```

```
What's my Aave health factor?
```

```
Repay all my ETH debt on Aave
```

```
Withdraw 500 USDC from Aave
```

```
Show my full Aave position summary
```

## SDK Reference

The lending adapter is in the `@arb-agent/adapters` package as `AaveV3Adapter`.

### `supply(params)`

Supplies an asset to earn yield. Accepts `SupplyParams`:

| Field        | Type      | Required | Description                            |
| ------------ | --------- | -------- | -------------------------------------- |
| `asset`      | `Address` | Yes      | Token address to supply                |
| `amount`     | `bigint`  | Yes      | Amount in token decimals               |
| `onBehalfOf` | `Address` | No       | Recipient of aTokens (default: sender) |

### `borrow(params)`

Borrows an asset at variable rate. Accepts `BorrowParams`:

| Field              | Type      | Required | Description                    |
| ------------------ | --------- | -------- | ------------------------------ |
| `asset`            | `Address` | Yes      | Token address to borrow        |
| `amount`           | `bigint`  | Yes      | Amount in token decimals       |
| `interestRateMode` | `number`  | No       | 2 = variable (default)         |
| `onBehalfOf`       | `Address` | No       | Account to borrow on behalf of |

### `repay(asset, amount)`

Repays a borrow position. Pass `2n ** 256n - 1n` to repay the full debt.

### `withdraw(asset, amount)`

Withdraws supplied collateral. Pass `2n ** 256n - 1n` to withdraw everything.

### `getAccountData()`

Returns the full account summary including health factor, collateral, debt, and available borrows.
