Component: Borrowing (market + limit matching via Orderbook → Pool borrow)
Description
Turns borrower intent (market or limit) into loans across whitelisted pools.
Enforces collateral, liquidity, and pricing checks.
Updates borrow shares, pool totals, fees, and orderbook state.
What it does:
Market borrow:
matchMarketBorrowOrderfinds best lender orders, aggregates pools, computes required collateral, pulls once, and may charge a flat fee.Limit borrow:
insertLimitBorrowOrderescrows collateral; later a keeper callsmatchLimitBorrowOrderat borrower’s chosen terms, refunding any excess.Pool side:
BorrowRepay._borrowmints borrow shares, updates totals, checks safety and liquidity, then transfers loan tokens.
How it works:
Orders stored in a red-black tree keyed by rate/LTV.
Collateral per pool calculated via
previewBorrow, then summed and transferred once.Fees: optional flat matching fee goes to
feeRecipient.Permissions: pools must be whitelisted; limit matching keeper-only; borrow allowed if sender is borrower, orderbook, or permitted.
Safety: entry points are
nonReentrantandwhenNotPaused; pool accrues interest before updates.
Invariants
Liquidity:
totalBorrowAssets ≤ totalSupplyAssetsalways holds.Position safety: borrower’s debt must stay ≤ collateral value * LLTV.
Accounting: borrow shares and assets stay in sync; accrual only increases totals; fee shares mint against supply.
Access control: only whitelisted pools can list; only keepers match limit orders; only owner adjusts fees/recipients.
Attack surface
Borrower params:
Market:
amount > 0,collateralBuffer ≥ 1%, enforceminAmountExpected.Limit: upfront collateral, within
MAX_LIMIT_ORDERS, keeper-only matching, refund logic, LTV/buffer bounds.
Matching window: pool state may change, but final
minAmountExpectedguard and livepreviewBorrowmitigate.
Collateral/oracle: depends on oracle pricing; weak or stale oracles risk under-collateralization, needs system-level hardening.
Pool selection: can’t inject arbitrary pools; whitelist + factory validation required.
Fees:
flatMatchingFeemay be set high, but limited byInsufficientAmountReceivedcheck.
Reentrancy: guarded with
nonReentrantand safe ERC20; state updated before pool calls.
Allowances: orderbook manages approvals; user doesn’t expose pools directly.
DoS: paused pools skipped; match loops capped in length and gas.
Escrow correctness: limit orders require
totalCollateral + fee ≤ escrowed; order canceled before pool calls, excess refunded.