# How Borrowing Works

This page walks through the borrowing lifecycle end to end: creating a vault, depositing collateral, borrowing L, and repaying. If you haven't read [The Big Idea](http://./the-big-idea.md) yet, read it first — most of the vocabulary here (L, sL, √K, idle, vault) is introduced there.

The flow is intentionally narrow. A vault is always bound to one pool. Its collateral is always in that pool's two tokens. Its debt is always in L for that pool. There is no cross-pool netting.

### The lifecycle at a glance

&#x20; create vault ─► deposit idle ─► attach NFTs (optional) ─► borrow L

&#x20;                                                             │

&#x20;                                                             ▼

&#x20;                                                      do something

&#x20;                                                      with the tokens

&#x20;                                                             │

&#x20;                                                             ▼

&#x20;                                 repay L ─► detach NFTs ─► withdraw idle ─► (optional) close vault

All of these steps happen through AegisRouterV1. Most integrators will batch several steps into a single transaction using the router's action encoding — see Router and Actions Reference.

### Step 0: the session model

Every state-changing interaction with Engine happens inside a session. A session has three nested layers:

1. Outer transaction. The user calls AegisRouterV1.execute(unlockData, deadline).
2. PoolManager unlock frame. The router calls PoolManager.unlock(...), which gives it access to ERC-6909 currency accounting and delta settlement. At the end of this frame, Uniswap enforces that all deltas net to zero.
3. AE session. Inside the unlock frame, the router calls AegisEngine.aeUnlock(...), which opens an AE session. The session tracks which vaults the caller has unlocked for mutation and guarantees that they are all re-locked before the session ends.

Inside the session, the borrower must call unlockVault(vaultId) before mutating their vault, and lockVault(vaultId) at the end (or leave it locked implicitly — the session epilogue enforces all vaults relocked). lockVault is where the solvency check happens.

Everything that touches the PoolManager — deposit, withdraw, borrow, repay, peel, micro-liq — has to execute inside the unlock frame (Phase-1). NFT attach and detach have to execute outside the unlock frame (Phase-0), because Uniswap's PositionManager requires the PoolManager to be locked for ERC-721 transfers of its NFTs. See Architecture and Contract Roles for the full two-phase story.

### Step 1: create a vault

A borrower creates a vault with createVault(poolKey). This mints an ERC-721 from VaultRegistry; the NFT owner becomes the vault owner. The vault is permanently bound to that pool.

Ownership can be transferred like any ERC-721, subject to one restriction: the vault NFT cannot be transferred while the vault is "unlocked" in an active AE session. This prevents a mid-session transfer from bypassing session-level authorization checks.

### Step 2: deposit idle collateral

Before borrowing, the vault needs collateral. Idle collateral is either token of the pool pair, deposited directly:

* The router takes the tokens from the user via PoolManager.sync + transferFrom + settleFor(AE), which credits Engine with a positive delta in the PoolManager's ERC-6909 accounting.
* Engine records the delta as idle\[vaultId]\[currency] += amount.

At the end of the session, the PoolManager's delta-zero invariant ensures the tokens were actually moved from the user; Engine's session epilogue ensures no stray funding buffer remains.

Optionally, a borrower can attach up to MAX\_NFTS\_PER\_VAULT (currently 4) CL or LO NFTs as collateral. When attached, the NFT's ownership transfers from the user to Engine. Attach happens in Phase-0 and completes a handshake via onERC721Received. Attached NFTs count toward the vault's collateral floor in addition to idle balances.

### Step 3: borrow L

The borrower calls borrowL(vaultId, dL, ...) on the router. Inside the session, Engine does four things:

1. Accrue. First touch of this pool in the session triggers a single feeSync(); accrue(); pass. Fees earned by the pooled full-range position are realized into L; the market's borrowIndexWad advances to "now."
2. Burn L from the pool. Engine removes dL \* M units of liquidity from the pooled full-range position, where M is the scale factor between the market's real and nominal L ledgers (see Shares, Debt, and Core Accounting). This produces two token amounts (x\_out, y\_out) determined by the pool's current √P at the moment of the burn.
3. Credit idle. Engine adds x\_out and y\_out to the vault's idle balances in PoolManager ERC-6909.
4. Book debt. Engine increases the vault's rL principal and the market's totalRlBorrowed by the conservative bridge defined in the L-ledger research (R-0009).

At the end of the session, lockVault(vaultId) recomputes the vault's √K collateral floor and enforces:

* Post-borrow LTV ≤ MAX\_LTV\_PIPS (currently 980,000 / 98%).
* Post-borrow utilization ≤ UTILIZATION\_CAP\_PIPS (currently 950,000 / 95%).

If either is violated, the session reverts and nothing persists.

The two cap values are compile-time constants — not governance-tunable parameters — so the envelope in which borrowing is allowed is fixed and transparent.

### Step 4: use the tokens

At this point the vault holds the (x\_out, y\_out) tokens as idle. The borrower can withdraw them to their own address with withdrawIdle(v, c, amount, to=self). Once withdrawn, the tokens are theirs to use however they want — trade, deposit elsewhere, bridge, whatever. Engine no longer tracks what happens to them.

The vault's debt is the L owed back to the pool, not any specific use of the borrowed tokens. This is why the protocol is infrastructure for applications, not a trading product itself.

### Step 5: repay L

Repayment is the reverse of borrow. The borrower provides tokens (either from idle still in the vault or freshly deposited) and calls repayL(vaultId, dL, ...).

1. Accrue is called on first touch per session (same as borrow).
2. Mint L back into the pool. Engine uses the provided tokens to add liquidity back to the pooled full-range position. The actual L minted depends on the current √P and the token amounts available. Engine reads the actual minted liquidity back from Uniswap v4's return value — it does not guess.
3. Reduce debt conservatively. The vault's rL is reduced by rLEff = floor(liquidityMinted / M). "Conservative" means if there's any rounding ambiguity, the borrower's debt is reduced by at most the amount actually minted, never more.
4. Adjust idle. The tokens used to mint are subtracted from the vault's idle balances.

If the borrower passes dL = 0 as a sentinel, Engine repays the entire outstanding rL. This is the standard way to close out a vault.

A partial repayment is always allowed as long as post-repay LTV passes the cap. Repayment has no utilization check — utilization can only go down on repay.

### Step 6: detach NFTs and close out

If the vault had NFTs attached, the borrower detaches them with detachUserNft(vaultId, nftRef, to). Engine verifies that:

* The caller is the vault owner or approved operator.
* The post-detach LTV still passes the cap.

On success, Engine transfers the NFT back from itself to to. Like attach, detach happens in Phase-0.

Finally, remaining idle can be withdrawn, and the vault NFT can be kept (for future use) or transferred.

### What the borrower pays

Borrowing is not free. Two costs accrue:

* Interest. borrowIndexWad advances whenever the market accrues. The rate is set by a Frax-style variable interest rate oracle that follows a kinked utilization curve: low rate below a target utilization, steep increase above. A configurable marketProtocolFee (bps) directs a share of interest to protocol-owned sL shares; the rest accretes to sL share price (i.e., lenders).
* Swap fees, if the borrower also trades. Tokens borrowed and then used to swap pay the normal dynamic fee on whichever pool they swap through. Engine doesn't charge a separate origination fee.

There is no liquidation penalty as such — see [Liquidations and Keepers](/part-2-core-engine-concepts/liquidations-and-keepers.md) for how the keeper bounty is structured and why it isn't punitive.

### Edge cases worth knowing

* Borrow then immediately repay, same transaction. Supported. This is a common pattern for keepers and for atomic composed strategies. The session epilogue enforces solvency only at lockVault time, so intermediate states can be temporarily unsafe as long as the final state is not.
* Borrow from one vault and deposit into another, same transaction. Supported via the router's withdrawIdle(..., to=address(0)) sentinel, which keeps the AE positive delta across actions in the same frame. See Router and Actions Reference.
* Borrowing when utilization is already at the cap. Rejected at lockVault time with a utilization-cap error. Lenders can still redeem normally.
* Borrowing with zero idle and only attached NFTs. Allowed, subject to the post-borrow LTV check. The NFTs' liquidation-adjusted token amounts count toward the floor.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aegis.markets/part-2-core-engine-concepts/how-borrowing-works.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
