Verified contractPartialGPL-2.0-or-later
LCCLeveragedFundHelper
Address0xf50be32d233d8005b4bd8d3eaa89a3e416d86c0f
- Balance
0 ETH
- Transactions
35
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 150 runs
- EVM version
- cancun
- Via IR
- yes
- License
- GPL-2.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,286,838
- Creation transaction
- 0xa8ce30a26e…d335eae3f2
26 files
- src/lcc/LCCLeveragedFundHelper.solmain47.73 KB
- lib/openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- lib/openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin/contracts/utils/ReentrancyGuardTransient.sol2.09 KB
- lib/openzeppelin/contracts/utils/TransientSlot.sol5.08 KB
- lib/openzeppelin/contracts/utils/introspection/IERC165.sol870 B
- lib/openzeppelin/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/IOracle.sol747 B
- src/lcc/interfaces/ILCCLeveragedFundHelper.sol39.42 KB
- src/lcc/interfaces/ILCCNotificationVault.sol836 B
- src/lcc/interfaces/ILCCVault.sol43.56 KB
- src/lcc/interfaces/ILCCVaultFactory.sol1.48 KB
- src/lcc/interfaces/IMorphoBlue.sol2.72 KB
- src/lcc/libraries/LCCAuctionLib.sol20.86 KB
- src/lcc/libraries/LCCErrorsLib.sol4.76 KB
- src/libraries/ConstantsLib.sol851 B
- src/libraries/MathLib.sol3.22 KB
- src/libraries/SharesMathLib.sol2.36 KB
src/lcc/LCCLeveragedFundHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.35;
import {IERC20} from "../../lib/openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "../../lib/openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "../../lib/openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "../../lib/openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "../../lib/openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "../../lib/openzeppelin/contracts/utils/math/SafeCast.sol";
import {ReentrancyGuardTransient} from "../../lib/openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IOracle} from "../interfaces/IOracle.sol";
import {ORACLE_PRICE_SCALE} from "../libraries/ConstantsLib.sol";
import {MathLib} from "../libraries/MathLib.sol";
import {SharesMathLib} from "../libraries/SharesMathLib.sol";
import {ILCCLeveragedFundHelper} from "./interfaces/ILCCLeveragedFundHelper.sol";
import {ILCCVault} from "./interfaces/ILCCVault.sol";
import {ILCCVaultFactory} from "./interfaces/ILCCVaultFactory.sol";
import {LCCAuctionLib} from "./libraries/LCCAuctionLib.sol";
import {IMorphoBlue, IMorphoBlueFlashLoanCallback} from "./interfaces/IMorphoBlue.sol";
import {ILCCNotificationVault, ILCCRedeemableVault} from "./interfaces/ILCCNotificationVault.sol";
/// @title LCCLeveragedFundHelper
/// @author 3Jane
/// @custom:contact [email protected]
/// @notice Levered LCC funding, shortfall-auction takes, and unwinds on the pinned canonical Morpho Blue singleton.
/// `ILCCLeveragedFundHelper` is the behaviour specification; `src/lcc/README.md` is the auditor narrative.
/// @dev Layout: entrypoints size and validate a request with view reads (a take also syncs the vault), then
/// `_executeFund`, `takeAuction`, or `_executeUnwind` runs it directly or through `_bridge`, whose flash-loan
/// callback dispatches on the payload's `OperationKind` to `_runFund`, `_runTake`, or `_runUnwind`. Persistent state is
/// the cooldown book, which every entry and `trimCooldowns` bound by live collateral; the in-flight operation hash and
/// the reentrancy lock are transient.
contract LCCLeveragedFundHelper is ILCCLeveragedFundHelper, IMorphoBlueFlashLoanCallback, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
using MathLib for uint256;
using SharesMathLib for uint256;
/* CONSTANTS & TYPES */
/// @dev Mirrors the vault's bound on the extra funding asset pulled so a dust obligation mints one USD3 share.
uint256 internal constant MAX_FUNDING_TOP_UP = 1_000;
uint256 public constant MAX_COOLDOWNS = 12;
/// @dev First field of every flash-loan payload, so the callback dispatches on the operation it was armed for.
enum OperationKind {
Fund,
Unwind,
Take
}
/// @dev Inputs one funding binds; hashed with its kind as the in-flight operation.
struct FundOperation {
address user;
address vault;
address marginAsset;
IMorphoBlue.MarketParams market;
uint256 obligation;
uint256 fundingAmount;
uint256 contribution;
uint256 borrowAssets;
uint256 marginAssets;
uint256 maxMarginShares;
uint256 minCollateral;
uint256 maxCollateral;
}
/// @dev Final values of one take, scaled to the fill; hashed with its kind as the in-flight operation.
struct TakeOperation {
address user;
address vault;
address marginAsset;
IMorphoBlue.MarketParams market;
uint256 fill;
uint256 contribution;
uint256 borrowAssets;
uint256 marginAssets;
uint256 minMarginAward;
uint256 minCollateral;
}
/// @dev Inputs one unwind binds; hashed with its kind as the in-flight operation.
struct UnwindOperation {
address user;
IMorphoBlue.MarketParams market;
uint256 shares;
uint256 repayAssets;
uint256 repayShares;
bool usd3Out;
}
/// @dev A position's debt as read by `_debtOf`.
struct DebtState {
uint256 borrowShares;
uint256 collateral;
uint256 assets;
uint256 totalBorrowAssets;
uint256 totalBorrowShares;
}
/* IMMUTABLES & STATE */
address public immutable override morpho;
address public immutable override factory;
address public immutable override usdc;
address public immutable override usd3;
address public immutable override usd3l;
bytes32 private transient _operation;
mapping(address user => mapping(bytes32 marketId => Cooldown[])) private _cooldowns;
/* CONSTRUCTOR */
/// @notice Grants Morpho the standing maximal USD3l and USDC allowances `ILCCLeveragedFundHelper` describes.
/// @param morpho_ Canonical Morpho Blue singleton.
/// @param factory_ LCC vault factory whose registered vaults may be funded.
/// @param usd3l_ USD3l, the notification vault wrapping USD3 and the collateral token of every market served. USD3
/// is derived as `usd3l_.asset()` and USDC as `usd3.asset()`.
constructor(address morpho_, address factory_, address usd3l_) {
if (morpho_.code.length == 0 || factory_.code.length == 0 || usd3l_.code.length == 0) {
revert InvalidConfiguration();
}
address usd3_ = IERC4626(usd3l_).asset();
if (usd3_.code.length == 0) revert InvalidConfiguration();
address usdc_ = IERC4626(usd3_).asset();
if (usdc_.code.length == 0) revert InvalidConfiguration();
morpho = morpho_;
factory = factory_;
usdc = usdc_;
usd3 = usd3_;
usd3l = usd3l_;
IERC20(usd3l_).forceApprove(morpho_, type(uint256).max);
IERC20(usdc_).forceApprove(morpho_, type(uint256).max);
}
/// @dev Requires the helper's USD3l balance to end the entrypoint where it started (`UnexpectedBalance`): the
/// helper is a bypassed USD3l owner, so it must never keep USD3l it handled, and donated USD3l is never touched.
modifier keepsUsd3lBalance() {
uint256 usd3lBefore = _usd3lBalance();
_;
_requireUsd3lBalance(usd3lBefore);
}
/* FUND */
/// @inheritdoc ILCCLeveragedFundHelper
/// @dev The allowance checks follow sizing, which makes only view calls, and precede any token movement.
function fund(FundParams calldata params)
external
nonReentrant
keepsUsd3lBalance
returns (uint256 obligation, uint256 fundingAmount, uint256 collateral)
{
if (_needsAuthorization(params.borrowAssets)) revert NotAuthorized();
FundOperation memory op = _sizeFund(params);
_requireContributionAllowance(op.contribution);
_requireAllowance(usd3l, op.maxCollateral, "");
if (op.marginAssets != 0) _requireAllowance(op.marginAsset, op.maxMarginShares, "");
return (op.obligation, op.fundingAmount, _executeFund(op, _marketId(op.market), params.maxEntryLtv));
}
/// @inheritdoc ILCCLeveragedFundHelper
/// @dev The signatures are applied after sizing, which makes only view calls, and before any token moves.
function fundWithSignatures(
FundParams calldata params,
PermitSignature calldata usdcPermit,
PermitSignature calldata usd3lPermit,
PermitSignature calldata marginPermit,
IMorphoBlue.Authorization calldata authorization,
IMorphoBlue.Signature calldata authorizationSignature
) external nonReentrant keepsUsd3lBalance returns (uint256 obligation, uint256 fundingAmount, uint256 collateral) {
FundOperation memory op = _sizeFund(params);
if (op.contribution != 0) _applyPermit(usdc, usdcPermit, op.contribution);
_applyPermit(usd3l, usd3lPermit, op.maxCollateral);
if (op.marginAssets != 0) _applyPermit(op.marginAsset, marginPermit, op.maxMarginShares);
if (_needsAuthorization(op.borrowAssets)) _applyAuthorization(authorization, authorizationSignature);
return (op.obligation, op.fundingAmount, _executeFund(op, _marketId(op.market), params.maxEntryLtv));
}
/* TAKE */
/// @inheritdoc ILCCLeveragedFundHelper
/// @dev The only allowance checked is the caller's USDC allowance against the scaled contribution: the USD3l and
/// the margin award are delivered to this helper, and the award withdrawal burns the helper's own shares.
function takeAuction(TakeParams calldata params)
external
nonReentrant
keepsUsd3lBalance
returns (uint256 filled, uint256 collateral)
{
if (_needsAuthorization(params.borrowAssets)) revert NotAuthorized();
TakeOperation memory op = _sizeTake(params);
_requireContributionAllowance(op.contribution);
bytes32 id = _marketId(op.market);
_trimCooldowns(msg.sender, id);
uint256 flashAssets = op.borrowAssets + op.marginAssets;
if (flashAssets == 0) {
_pullContribution(op.contribution);
collateral = _runTake(op);
_startCooldown(msg.sender, id, collateral);
} else {
collateral = _executeBridgedEntry(
abi.encode(OperationKind.Take, op),
flashAssets,
op.contribution,
op.market,
id,
op.borrowAssets != 0,
params.maxEntryLtv
);
}
emit AuctionTaken(op.user, op.vault, id, op.fill, collateral, op.borrowAssets, op.marginAssets);
return (op.fill, collateral);
}
/* UNWIND */
/// @inheritdoc ILCCLeveragedFundHelper
function unwind(UnwindParams calldata params)
external
nonReentrant
keepsUsd3lBalance
returns (uint256 repaidAssets, uint256 amountOut)
{
if (!_isAuthorized()) revert NotAuthorized();
return _executeUnwind(params);
}
/// @inheritdoc ILCCLeveragedFundHelper
function unwindWithAuthorization(
UnwindParams calldata params,
IMorphoBlue.Authorization calldata authorization,
IMorphoBlue.Signature calldata authorizationSignature
) external nonReentrant keepsUsd3lBalance returns (uint256 repaidAssets, uint256 amountOut) {
if (!_isAuthorized()) {
_applyAuthorization(authorization, authorizationSignature);
}
return _executeUnwind(params);
}
/* FLASH-LOAN CALLBACK */
/// @inheritdoc IMorphoBlueFlashLoanCallback
/// @dev Accepted only from Morpho and only when the loaned `assets` and `data` hash to the operation this helper
/// recorded before its own `flashLoan` call, so the amount is bound with the payload; with nothing in flight the
/// record is zero and no hash matches it. The record is cleared before any external call, and the callback then
/// only dispatches. Morpho pulls the repayment under the standing USDC allowance.
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external override {
if (msg.sender != morpho) revert InvalidCallback();
if (keccak256(abi.encodePacked(assets, keccak256(data))) != _operation) revert InvalidCallback();
_operation = bytes32(0);
OperationKind kind = abi.decode(data[:32], (OperationKind));
if (kind == OperationKind.Fund) {
(, FundOperation memory op) = abi.decode(data, (OperationKind, FundOperation));
_runFund(op);
} else if (kind == OperationKind.Unwind) {
(, UnwindOperation memory op) = abi.decode(data, (OperationKind, UnwindOperation));
_runUnwind(op);
} else {
(, TakeOperation memory op) = abi.decode(data, (OperationKind, TakeOperation));
_runTake(op);
}
}
/* COOLDOWN TRIM */
/// @inheritdoc ILCCLeveragedFundHelper
function trimCooldowns(address user, bytes32 marketId) external nonReentrant returns (uint256 trimmed) {
return _trimCooldowns(user, marketId);
}
/* VIEWS */
/// @inheritdoc ILCCLeveragedFundHelper
function cooldowns(address user, bytes32 marketId) external view returns (Cooldown[] memory) {
return _cooldowns[user][marketId];
}
/// @inheritdoc ILCCLeveragedFundHelper
function maxUnwindable(address user, bytes32 marketId) external view returns (uint256) {
uint256 collateral = _positionCollateral(marketId, user);
uint256 liveDuration = ILCCNotificationVault(usd3l).cooldownDuration();
if (_cooldownWaived(liveDuration)) return collateral;
return Math.min(collateral, _maturedShares(user, marketId, liveDuration));
}
/// @dev The helper's own USD3l balance.
function _usd3lBalance() private view returns (uint256) {
return IERC20(usd3l).balanceOf(address(this));
}
/// @dev Reverts with `UnexpectedBalance` unless the helper's USD3l balance equals `expected`.
function _requireUsd3lBalance(uint256 expected) private view {
uint256 balance = _usd3lBalance();
if (balance != expected) revert UnexpectedBalance(usd3l, balance, expected);
}
/* REQUEST VALIDATION */
/// @dev Checks shared by every entry and unwind: the deadline, then the market's loan and collateral tokens.
function _validateRequest(uint256 deadline, IMorphoBlue.MarketParams calldata market) private view {
if (block.timestamp > deadline) revert DeadlineExpired(); // deliberate wall-clock read
if (market.loanToken != usdc || market.collateralToken != usd3l) revert InvalidRequest();
}
/// @dev Requires `borrowAssets + marginAssets <= total` without overflowing (`BorrowAndMarginExceedTotal`).
function _requireSplit(uint256 borrowAssets, uint256 marginAssets, uint256 total) private pure {
if (borrowAssets > total || marginAssets > total - borrowAssets) {
revert BorrowAndMarginExceedTotal(borrowAssets, marginAssets, total);
}
}
/// @dev Morpho's id of `market`.
function _marketId(IMorphoBlue.MarketParams memory market) private pure returns (bytes32) {
return keccak256(abi.encode(market));
}
/* SIZING */
/// @dev Validates a funding request with view reads only and sizes it from the caller's current obligation.
function _sizeFund(FundParams calldata params) private view returns (FundOperation memory op) {
_validateRequest(params.deadline, params.market);
if (params.minCollateral == 0 || params.minCollateral > params.maxCollateral) {
revert InvalidRequest();
}
address marginAsset = _validateVault(params.vault);
if (params.marginAssets != 0) {
if (params.maxMarginShares == 0) revert InvalidRequest();
_requireUsdcVault(marginAsset);
op.marginAsset = marginAsset;
op.marginAssets = params.marginAssets;
op.maxMarginShares = params.maxMarginShares;
}
ILCCVault vault = ILCCVault(params.vault);
if (vault.currentPhase() != ILCCVault.Phase.Funding) revert NothingToFund();
op.user = msg.sender;
op.vault = params.vault;
op.market = params.market;
op.obligation = vault.obligationOf(vault.currentEpoch(), msg.sender);
if (op.obligation == 0) revert NothingToFund();
if (op.obligation > params.maxObligation) revert ObligationExceedsMax(op.obligation, params.maxObligation);
op.fundingAmount = Math.max(op.obligation, IERC4626(usd3).previewMint(1));
if (op.fundingAmount - op.obligation > MAX_FUNDING_TOP_UP) {
revert FundingTopUpExceeded(op.fundingAmount, op.obligation);
}
_requireSplit(params.borrowAssets, params.marginAssets, op.fundingAmount);
op.borrowAssets = params.borrowAssets;
op.contribution = op.fundingAmount - op.borrowAssets - op.marginAssets;
if (op.contribution > params.maxContribution) {
revert ContributionExceedsMax(op.contribution, params.maxContribution);
}
op.minCollateral = params.minCollateral;
op.maxCollateral = params.maxCollateral;
}
/// @dev Validates a take, syncs the vault (see `takeAuction`), sizes the fill, and scales it as `TakeParams` says.
function _sizeTake(TakeParams calldata params) private returns (TakeOperation memory op) {
_validateRequest(params.deadline, params.market);
if (params.minCollateral == 0) revert InvalidRequest();
uint256 maxFill = params.maxFill;
if (maxFill == 0 || params.minFill > maxFill) revert InvalidRequest();
_requireSplit(params.borrowAssets, params.marginAssets, maxFill);
address marginAsset = _validateVault(params.vault);
if (marginAsset == usdc || marginAsset == usd3) revert UnsupportedMarginAsset(marginAsset);
if (params.marginAssets != 0) _requireUsdcVault(marginAsset);
ILCCVault vault = ILCCVault(params.vault);
uint256 slot = vault.syncState().pendingAuctionEpochPlusOne;
if (slot != 0) vault.finalizeEpochSlash(slot - 1);
else vault.materializeAccount(address(this));
slot = vault.syncState().pendingAuctionEpochPlusOne;
if (slot == 0) revert NothingToFund();
LCCAuctionLib.AuctionState memory auction = vault.getAuctionState(slot - 1);
uint256 fill = Math.min(maxFill, uint256(auction.shortfallAmount) - auction.filledAmount);
if (fill < params.minFill) revert FillBelowMinimum(fill, params.minFill);
op.user = msg.sender;
op.vault = params.vault;
op.marginAsset = marginAsset;
op.market = params.market;
op.fill = fill;
op.contribution = Math.mulDiv(maxFill - params.borrowAssets - params.marginAssets, fill, maxFill);
op.marginAssets = Math.mulDiv(params.marginAssets, fill, maxFill);
if (params.borrowAssets != 0) op.borrowAssets = fill - op.contribution - op.marginAssets;
else if (params.marginAssets != 0) op.marginAssets = fill - op.contribution;
op.minMarginAward = Math.mulDiv(params.minMarginAward, fill, maxFill);
op.minCollateral = Math.max(1, Math.mulDiv(params.minCollateral, fill, maxFill));
}
/// @dev Prices the repayment against the just-accrued market, always as borrow shares: in full mode all of the
/// caller's shares; in partial mode the shares `repayAssets` buys, rounded down and at most the caller's shares,
/// with `repayAssets` at most the current debt (`RepayExceedsDebt`) and a nonzero amount that buys no share
/// rejected (`RepayRoundsToZero`). The repayment is the shares' value rounded up, exactly what Morpho pulls, and is
/// bounded by `maxRepayAssets`.
function _sizeUnwind(UnwindParams calldata params, bytes32 id) private view returns (UnwindOperation memory op) {
DebtState memory debt = _debtOf(id, msg.sender);
op.user = msg.sender;
op.market = params.market;
op.shares = params.shares;
op.usd3Out = params.usd3Out;
if (params.full) {
op.repayShares = debt.borrowShares;
} else if (params.repayAssets != 0) {
if (params.repayAssets > debt.assets) revert RepayExceedsDebt(params.repayAssets, debt.assets);
op.repayShares = Math.min(
params.repayAssets.toSharesDown(debt.totalBorrowAssets, debt.totalBorrowShares), debt.borrowShares
);
if (op.repayShares == 0) revert RepayRoundsToZero(params.repayAssets);
}
op.repayAssets = op.repayShares.toAssetsUp(debt.totalBorrowAssets, debt.totalBorrowShares);
if (op.repayAssets > params.maxRepayAssets) revert RepayExceedsMax(op.repayAssets, params.maxRepayAssets);
}
/* EXECUTION & FLASH BRIDGE */
/// @dev Trims the caller's cooldowns in market `id` to their pre-entry collateral, then runs a sized funding there,
/// directly through `_runFund` when it bridges nothing and otherwise through `_executeBridgedEntry`, and returns
/// the collateral supplied.
function _executeFund(FundOperation memory op, bytes32 id, uint256 maxEntryLtv)
private
returns (uint256 collateral)
{
_trimCooldowns(msg.sender, id);
uint256 flashAssets = op.borrowAssets + op.marginAssets;
if (flashAssets != 0) {
return _executeBridgedEntry(
abi.encode(OperationKind.Fund, op),
flashAssets,
op.contribution,
op.market,
id,
op.borrowAssets != 0,
maxEntryLtv
);
}
_pullContribution(op.contribution);
collateral = _runFund(op);
_startCooldown(msg.sender, id, collateral);
}
/// @dev The bridged half of a funding or take entry, shared by both: pulls the caller's `contribution`, runs the
/// entry's `payload` inside a flash loan of `flashAssets` (`_bridgeEntry`), and opens the cooldown for the
/// collateral supplied in market `id`.
function _executeBridgedEntry(
bytes memory payload,
uint256 flashAssets,
uint256 contribution,
IMorphoBlue.MarketParams memory market,
bytes32 id,
bool borrowed,
uint256 maxEntryLtv
) private returns (uint256 collateral) {
_pullContribution(contribution);
collateral = _bridgeEntry(payload, flashAssets, market, id, borrowed, maxEntryLtv);
_startCooldown(msg.sender, id, collateral);
}
/// @dev Pulls a nonzero USDC `contribution` from the caller to the helper.
function _pullContribution(uint256 contribution) private {
if (contribution != 0) IERC20(usdc).safeTransferFrom(msg.sender, address(this), contribution);
}
/// @dev Checks the request, consumes cooldowns (matured ones unless the gate is waived) before any state-changing
/// external call, accrues the market, sizes the repayment, runs the unwind directly or through the flash bridge
/// when the repayment is nonzero, and
/// sends the caller the output token's measured balance change of the helper. Full mode leaves zero debt because it
/// repays the exact share count read after accrual in this transaction.
function _executeUnwind(UnwindParams calldata params) private returns (uint256 repaidAssets, uint256 amountOut) {
_validateRequest(params.deadline, params.market);
if (params.shares == 0) revert InvalidRequest();
bytes32 id = _marketId(params.market);
uint256 collateral = _positionCollateral(id, msg.sender);
if (params.shares > collateral) revert SharesExceedCollateral(params.shares, collateral);
_consumeCooldowns(msg.sender, id, params.shares, false);
IMorphoBlue(morpho).accrueInterest(params.market);
UnwindOperation memory op = _sizeUnwind(params, id);
uint256 usdcBefore = IERC20(usdc).balanceOf(address(this));
uint256 usd3Before = params.usd3Out ? IERC20(usd3).balanceOf(address(this)) : 0;
if (op.repayAssets == 0) _runUnwind(op);
else _bridge(abi.encode(OperationKind.Unwind, op), op.repayAssets);
uint256 usdcAfter = IERC20(usdc).balanceOf(address(this));
address outToken;
if (params.usd3Out) {
if (usdcAfter != usdcBefore) revert UnexpectedBalance(usdc, usdcAfter, usdcBefore);
outToken = usd3;
amountOut = IERC20(usd3).balanceOf(address(this)) - usd3Before;
} else {
outToken = usdc;
amountOut = usdcAfter - usdcBefore;
}
if (amountOut < params.minOut) revert UnwindOutputBelowMinimum(amountOut, params.minOut);
if (amountOut != 0) IERC20(outToken).safeTransfer(msg.sender, amountOut);
emit Unwound(msg.sender, id, outToken, op.repayAssets, params.shares, amountOut);
return (op.repayAssets, amountOut);
}
/// @dev Bridges an entry and returns the change in the caller's collateral in market `id` across the flash loan.
/// The caller is read here, before bridging, because msg.sender is Morpho inside the callback. When the entry
/// borrowed, the read-back is the whole-position LTV check against `maxEntryLtv`.
function _bridgeEntry(
bytes memory data,
uint256 flashAssets,
IMorphoBlue.MarketParams memory market,
bytes32 id,
bool borrowed,
uint256 maxEntryLtv
) private returns (uint256) {
address user = msg.sender;
uint256 collateralBefore = _positionCollateral(id, user);
_bridge(data, flashAssets);
uint256 collateralAfter =
borrowed ? _checkEntryLtv(market, id, user, maxEntryLtv) : _positionCollateral(id, user);
return collateralAfter - collateralBefore;
}
/// @dev Records `keccak256(abi.encodePacked(assets, keccak256(data)))` as the in-flight operation, takes a Morpho
/// flash loan of `assets` USDC with `data`, and requires the callback to have consumed the record.
function _bridge(bytes memory data, uint256 assets) private {
_operation = keccak256(abi.encodePacked(assets, keccak256(data)));
IMorphoBlue(morpho).flashLoan(usdc, assets, data);
if (_operation != bytes32(0)) revert InvalidCallback();
}
/* RUN PATHS */
/// @dev Pays the vault from the helper's USDC (the caller's contribution plus any flash-loaned `borrowAssets` and
/// `marginAssets`), which also releases margin to the caller; measures the USD3l delivered to the caller, requires
/// at least `minCollateral`, and supplies up to `maxCollateral` of it as the caller's collateral (any excess stays
/// in the caller's wallet); then withdraws `marginAssets` of USDC from the caller's margin-asset shares to the
/// helper, burning no more than `maxMarginShares` and no more than the shares the vault released to the caller
/// across `fundCall`, so a pre-existing margin-asset balance is never consumed; then borrows `borrowAssets` for the
/// caller to the helper. Returns the collateral supplied.
function _runFund(FundOperation memory op) private returns (uint256 supplied) {
IERC20 collateralToken = IERC20(usd3l);
uint256 balanceBefore = collateralToken.balanceOf(op.user);
uint256 marginBefore = op.marginAssets != 0 ? IERC20(op.marginAsset).balanceOf(op.user) : 0;
IERC20(usdc).forceApprove(op.vault, op.fundingAmount);
_requireExactSpend(op.vault, ILCCVault(op.vault).fundCall(op.user) == op.obligation);
uint256 delivered = collateralToken.balanceOf(op.user) - balanceBefore;
if (delivered < op.minCollateral) revert CollateralBelowMinimum(delivered, op.minCollateral);
supplied = Math.min(delivered, op.maxCollateral);
collateralToken.safeTransferFrom(op.user, address(this), supplied);
IMorphoBlue(morpho).supplyCollateral(op.market, supplied, op.user, "");
if (op.marginAssets != 0) {
uint256 marginAfterFund = IERC20(op.marginAsset).balanceOf(op.user);
_withdrawUsdc(
op.marginAsset,
op.marginAssets,
op.user,
marginAfterFund,
marginAfterFund - marginBefore,
op.maxMarginShares
);
}
if (op.borrowAssets != 0) {
IMorphoBlue(morpho).borrow(op.market, op.borrowAssets, 0, op.user, address(this));
}
}
/// @dev Fills the vault's auction from the helper's USDC (the caller's contribution plus any flash-loaned
/// `borrowAssets` and `marginAssets`), receiving the USD3l delivery and the margin award; supplies the whole
/// measured delivery as the caller's collateral; withdraws `marginAssets` of USDC from the award when nonzero,
/// burning no more shares than the award so donated shares are never spent, and forwards the rest of the award;
/// and borrows `borrowAssets` for the caller to the helper. Returns the collateral supplied.
function _runTake(TakeOperation memory op) private returns (uint256 supplied) {
uint256 marginBefore = IERC20(op.marginAsset).balanceOf(address(this));
uint256 awardReceived;
(supplied, awardReceived) = _fillAndSupply(op, _usd3lBalance(), marginBefore);
uint256 awardForwarded = awardReceived;
if (op.marginAssets != 0) {
awardForwarded -= _withdrawUsdc(
op.marginAsset,
op.marginAssets,
address(this),
marginBefore + awardReceived,
awardReceived,
type(uint256).max
);
}
if (awardForwarded != 0) IERC20(op.marginAsset).safeTransfer(op.user, awardForwarded);
if (op.borrowAssets != 0) {
IMorphoBlue(morpho).borrow(op.market, op.borrowAssets, 0, op.user, address(this));
}
}
/// @dev Pays the vault exactly `fill` through its `takeAuction`, measures the USD3l and margin-asset shares the
/// helper received across it from `usd3lBefore` and `marginBefore`, requires at least `minCollateral` of USD3l, and
/// supplies all of it as the caller's collateral from the helper's own balance.
function _fillAndSupply(TakeOperation memory op, uint256 usd3lBefore, uint256 marginBefore)
private
returns (uint256 supplied, uint256 awardReceived)
{
IERC20(usdc).forceApprove(op.vault, op.fill);
uint256 deadline = block.timestamp; // deliberate wall-clock read
(uint256 filled,) = ILCCVault(op.vault).takeAuction(op.fill, op.minMarginAward, deadline);
_requireExactSpend(op.vault, filled == op.fill);
supplied = _usd3lBalance() - usd3lBefore;
if (supplied < op.minCollateral) revert CollateralBelowMinimum(supplied, op.minCollateral);
awardReceived = IERC20(op.marginAsset).balanceOf(address(this)) - marginBefore;
IMorphoBlue(morpho).supplyCollateral(op.market, supplied, op.user, "");
}
/// @dev Repays `repayShares` of the caller's debt by shares from the helper's flash-loaned USDC under the standing
/// allowance (Morpho pulls exactly the shares' value rounded up, which is `repayAssets`), withdraws `shares` of the
/// caller's collateral to the helper, and redeems exactly the USD3l that withdrawal delivered; the USDC received
/// from USD3 must cover `repayAssets` (`RedemptionBelowRepayment` in USDC). Any other USD3l, USD3, or USDC the
/// helper holds is never touched.
function _runUnwind(UnwindOperation memory op) private {
if (op.repayShares != 0) {
IMorphoBlue(morpho).repay(op.market, 0, op.repayShares, op.user, "");
}
uint256 usd3lBefore = _usd3lBalance();
IMorphoBlue(morpho).withdrawCollateral(op.market, op.shares, op.user, address(this));
uint256 received = _redeemCollateral(_usd3lBalance() - usd3lBefore, op.usd3Out, op.repayAssets);
if (received < op.repayAssets) revert RedemptionBelowRepayment(usdc, received, op.repayAssets);
}
/// @dev Redeems `shares` of USD3l to USD3 under the helper's cooldown bypass, then converts USD3 to USDC with zero
/// loss tolerance: all of it when `usd3Out` is false; with `usd3Out`, only `repayAssets` of USDC through USD3's
/// `withdraw`, and nothing at all when `repayAssets` is zero, so USD3's withdraw limit is then never read. Before
/// the withdraw the USD3 it needs (`previewWithdraw`) must not exceed what this redemption produced, and after it
/// the USD3 actually burned is held to the same bound, so donated USD3 is never spent (`RedemptionBelowRepayment`
/// in USD3 for both). Returns the USDC received. Every amount is a measured balance change.
function _redeemCollateral(uint256 shares, bool usd3Out, uint256 repayAssets)
private
returns (uint256 usdcReceived)
{
uint256 usd3Before = IERC20(usd3).balanceOf(address(this));
ILCCRedeemableVault(usd3l).redeem(shares, address(this), address(this), 0);
uint256 usd3AfterRedeem = IERC20(usd3).balanceOf(address(this));
uint256 usd3Received = usd3AfterRedeem - usd3Before;
if (usd3Out && repayAssets == 0) return 0;
uint256 usdcBefore = IERC20(usdc).balanceOf(address(this));
if (usd3Out) {
uint256 required = IERC4626(usd3).previewWithdraw(repayAssets);
if (required > usd3Received) revert RedemptionBelowRepayment(usd3, usd3Received, required);
ILCCRedeemableVault(usd3).withdraw(repayAssets, address(this), address(this), 0);
uint256 usd3Spent = usd3AfterRedeem - IERC20(usd3).balanceOf(address(this));
if (usd3Spent > usd3Received) revert RedemptionBelowRepayment(usd3, usd3Received, usd3Spent);
} else {
ILCCRedeemableVault(usd3).redeem(usd3Received, address(this), address(this), 0);
}
usdcReceived = IERC20(usdc).balanceOf(address(this)) - usdcBefore;
}
/* RECEIPTS & WITHDRAWALS */
/// @dev Requires the vault to have reported the requested amount (`amountMatches`) and spent the helper's exact
/// USDC approval in full (`VaultAmountMismatch`).
function _requireExactSpend(address vault, bool amountMatches) private view {
if (!amountMatches || IERC20(usdc).allowance(address(this), vault) != 0) revert VaultAmountMismatch();
}
/// @dev Withdraws exactly `assets` of USDC to the helper from `owner`'s shares of the ERC-4626 `marginAsset` and
/// returns the shares burned, measured from `sharesBefore` (`owner`'s balance the caller already read) to its
/// balance after the withdrawal. Requires, in order: the helper's USDC balance to end exactly `assets` above where
/// it started (`UnexpectedBalance`, with both balances absolute); the shares burned to be at most `maxShares`
/// (`MarginSharesExceedMax`); and at most `available`, the shares this entry made available
/// (`MarginSharesUnavailable`).
function _withdrawUsdc(
address marginAsset,
uint256 assets,
address owner,
uint256 sharesBefore,
uint256 available,
uint256 maxShares
) private returns (uint256 burned) {
uint256 usdcBefore = IERC20(usdc).balanceOf(address(this));
IERC4626(marginAsset).withdraw(assets, address(this), owner);
burned = sharesBefore - IERC20(marginAsset).balanceOf(owner);
uint256 usdcAfter = IERC20(usdc).balanceOf(address(this));
if (usdcAfter != usdcBefore + assets) revert UnexpectedBalance(usdc, usdcAfter, usdcBefore + assets);
if (burned > maxShares) revert MarginSharesExceedMax(burned, maxShares);
if (burned > available) revert MarginSharesUnavailable(burned, available);
}
/* COOLDOWN BOOK */
/// @dev Opens a cooldown for `shares` supplied in this entry, whose book the entry trimmed before supplying
/// (`_trimCooldowns`). Judged at the live USD3l duration just read, a book still full after that trim merges: when
/// the two oldest cooldowns are both matured they merge into the oldest slot and the entry's cooldown takes the
/// freed last slot; otherwise, when the youngest cooldown is not matured, the entry's shares
/// fold into it in place (see `CooldownsMerged`). The remaining case, a matured youngest cooldown while the oldest
/// pair is not both matured, is reachable only after the USD3l cooldown duration decreased between entries, which
/// the current NotificationVault cannot do; it merges the two oldest, and when only the oldest of them is matured
/// that merge delays it to the second's maturity. Never reverts for book reasons.
function _startCooldown(address user, bytes32 marketId, uint256 shares) private {
uint64 duration = ILCCNotificationVault(usd3l).cooldownDuration();
uint64 start = uint64(block.timestamp); // deliberate wall-clock read
Cooldown memory cooldown = Cooldown({shares: SafeCast.toUint128(shares), start: start, duration: duration});
Cooldown[] storage book = _cooldowns[user][marketId];
uint256 length = book.length;
if (length < MAX_COOLDOWNS) {
book.push(cooldown);
} else {
Cooldown memory merged = book[0];
Cooldown memory second = book[1];
if (
(_isMatured(merged, duration) && _isMatured(second, duration)) || _isMatured(book[length - 1], duration)
) {
merged = _merge(merged, second);
book[0] = merged;
for (uint256 i = 2; i < length; ++i) {
book[i - 1] = book[i];
}
book[length - 1] = cooldown;
} else {
merged = _merge(book[length - 1], cooldown);
book[length - 1] = merged;
}
emit CooldownsMerged(user, marketId, merged.shares, merged.start, merged.duration);
}
emit CooldownStarted(user, marketId, cooldown.shares, cooldown.start, cooldown.duration);
}
/// @dev One cooldown covering `a` and `b`: the later start, a duration running from it to the later recorded
/// maturity, and the summed shares.
function _merge(Cooldown memory a, Cooldown memory b) private pure returns (Cooldown memory merged) {
uint256 maturity = Math.max(uint256(a.start) + a.duration, uint256(b.start) + b.duration);
merged.start = a.start > b.start ? a.start : b.start;
merged.duration = uint64(maturity - merged.start);
merged.shares = a.shares + b.shares;
}
/// @dev Trims `user`'s cooldowns in `marketId` to the user's live collateral there (see `trimCooldowns`): when the
/// book total exceeds it, the excess is consumed oldest first regardless of maturity and reported as
/// `CooldownsTrimmed`. An empty book returns before Morpho is read. Returns the shares removed.
function _trimCooldowns(address user, bytes32 marketId) private returns (uint256 trimmed) {
Cooldown[] storage book = _cooldowns[user][marketId];
uint256 length = book.length;
uint256 total;
for (uint256 i; i < length; ++i) {
total += book[i].shares;
}
if (total == 0) return 0;
uint256 collateral = _positionCollateral(marketId, user);
if (total <= collateral) return 0;
trimmed = total - collateral;
_consumeCooldowns(user, marketId, trimmed, true);
emit CooldownsTrimmed(user, marketId, trimmed);
}
/// @dev Consumes `shares` from `user`'s cooldowns in `marketId`, oldest first, keeping the remaining cooldowns in
/// order and writing only cooldowns that changed or moved; once nothing remains to consume and no cooldown has
/// been removed, the rest of the book is left unread. Maturity is ignored for a `trim` and for an unwind while the
/// USD3l cooldown is waived, and then a short book is emptied without reverting; otherwise only matured cooldowns
/// are eligible and they must cover `shares` (`InsufficientMaturedShares`).
function _consumeCooldowns(address user, bytes32 marketId, uint256 shares, bool trim) private {
bool ignoreMaturity = trim;
uint256 liveDuration;
if (!trim) {
liveDuration = ILCCNotificationVault(usd3l).cooldownDuration();
ignoreMaturity = _cooldownWaived(liveDuration);
}
Cooldown[] storage book = _cooldowns[user][marketId];
uint256 length = book.length;
uint256 remaining = shares;
uint256 kept;
for (uint256 i; i < length; ++i) {
if (remaining == 0 && kept == i) return;
Cooldown memory cooldown = book[i];
bool changed;
if (remaining != 0 && (ignoreMaturity || _isMatured(cooldown, liveDuration))) {
uint256 taken = Math.min(remaining, cooldown.shares);
cooldown.shares -= uint128(taken);
remaining -= taken;
changed = true;
}
if (cooldown.shares != 0) {
if (changed || kept != i) book[kept] = cooldown;
++kept;
}
}
if (remaining != 0 && !ignoreMaturity) revert InsufficientMaturedShares(shares, shares - remaining);
for (uint256 i = kept; i < length; ++i) {
book.pop();
}
}
/// @dev Sum of `user`'s cooldown shares in `marketId` matured at `liveDuration`.
function _maturedShares(address user, bytes32 marketId, uint256 liveDuration)
private
view
returns (uint256 shares)
{
Cooldown[] storage book = _cooldowns[user][marketId];
for (uint256 i; i < book.length; ++i) {
Cooldown memory cooldown = book[i];
if (_isMatured(cooldown, liveDuration)) shares += cooldown.shares;
}
}
/// @dev A cooldown matures at its start plus the longer of its recorded and the live USD3l cooldown.
function _isMatured(Cooldown memory cooldown, uint256 liveDuration) private view returns (bool) {
uint256 currentTime = block.timestamp; // deliberate wall-clock read
return currentTime >= uint256(cooldown.start) + Math.max(cooldown.duration, liveDuration);
}
/// @dev Mirrors the USD3l vault's own waivers: no cooldown applies while its already-read `liveDuration` is zero
/// or the vault is shut down (read only when the duration is nonzero).
function _cooldownWaived(uint256 liveDuration) private view returns (bool) {
return liveDuration == 0 || ILCCNotificationVault(usd3l).isShutdown();
}
/* DEBT & LTV */
/// @dev `user`'s borrow shares, collateral, and debt in market `id` (shares valued rounding up), with the market's
/// borrow totals, from one position read and one market read.
function _debtOf(bytes32 id, address user) private view returns (DebtState memory debt) {
(, uint128 borrowShares, uint128 collateral) = IMorphoBlue(morpho).position(id, user);
(,, uint128 totalBorrowAssets, uint128 totalBorrowShares,,) = IMorphoBlue(morpho).market(id);
debt.borrowShares = borrowShares;
debt.collateral = collateral;
debt.totalBorrowAssets = totalBorrowAssets;
debt.totalBorrowShares = totalBorrowShares;
debt.assets = uint256(borrowShares).toAssetsUp(totalBorrowAssets, totalBorrowShares);
}
/// @dev `user`'s collateral in market `id` as Morpho records it.
function _positionCollateral(bytes32 id, address user) private view returns (uint256 collateral) {
(,, collateral) = IMorphoBlue(morpho).position(id, user);
}
/// @dev Values the user's whole position in `market` at that market's oracle price, rounding debt up. Runs only
/// after a nonzero borrow in this transaction: Morpho's `borrow` accrued interest, so the market totals are current
/// and the borrow shares are nonzero. A zero collateral value (an oracle reading zero) is treated as unbounded LTV.
/// Returns the position's collateral it valued.
function _checkEntryLtv(IMorphoBlue.MarketParams memory market, bytes32 id, address user, uint256 maxEntryLtv)
private
view
returns (uint256 positionCollateral)
{
DebtState memory debt = _debtOf(id, user);
positionCollateral = debt.collateral;
uint256 collateralValue = positionCollateral.mulDivDown(IOracle(market.oracle).price(), ORACLE_PRICE_SCALE);
uint256 ltv = collateralValue == 0 ? type(uint256).max : debt.assets.wDivUp(collateralValue);
if (ltv > maxEntryLtv) revert EntryLtvExceeded(ltv, maxEntryLtv);
}
/* PERMITS & AUTHORIZATION */
/// @dev True when a levered entry still needs the caller's Morpho authorization of this helper.
function _needsAuthorization(uint256 borrowAssets) private view returns (bool) {
return borrowAssets != 0 && !_isAuthorized();
}
/// @dev True when the caller has authorized this helper on Morpho.
function _isAuthorized() private view returns (bool) {
return IMorphoBlue(morpho).isAuthorized(msg.sender, address(this));
}
/// @dev Applies the caller's enabling Morpho authorization of this helper. A payload whose authorizer is not the
/// caller, whose authorized address is not this helper, or that does not enable reverts `InvalidRequest`. A
/// submission that reverts (for example because a third party already submitted it) is tolerated when the
/// authorization is then in place, and reverts `NotAuthorized` otherwise.
function _applyAuthorization(
IMorphoBlue.Authorization calldata authorization,
IMorphoBlue.Signature calldata signature
) private {
if (
authorization.authorizer != msg.sender || authorization.authorized != address(this)
|| !authorization.isAuthorized
) revert InvalidRequest();
try IMorphoBlue(morpho).setAuthorizationWithSig(authorization, signature) {} catch {}
if (!_isAuthorized()) revert NotAuthorized();
}
/// @dev Submits the permit (see `PermitSignature`), tolerating a revert such as a third party's prior submission,
/// then requires the resulting allowance to cover `required` (`InsufficientAllowance`, carrying the permit's revert
/// data, empty when the permit applied).
function _applyPermit(address token, PermitSignature calldata permit, uint256 required) private {
bytes memory permitRevert;
try IERC20Permit(token)
.permit(msg.sender, address(this), permit.value, permit.deadline, permit.v, permit.r, permit.s) {}
catch (bytes memory reason) {
permitRevert = reason;
}
_requireAllowance(token, required, permitRevert);
}
/// @dev The standing-allowance check of a nonzero USDC contribution, shared by `fund` and `takeAuction`.
function _requireContributionAllowance(uint256 contribution) private view {
if (contribution != 0) _requireAllowance(usdc, contribution, "");
}
/// @dev Reverts with `InsufficientAllowance`, carrying `permitRevert`, unless the caller's allowance of `token` to
/// this helper covers `required`.
function _requireAllowance(address token, uint256 required, bytes memory permitRevert) private view {
uint256 allowance = IERC20(token).allowance(msg.sender, address(this));
if (allowance < required) revert InsufficientAllowance(token, allowance, required, permitRevert);
}
/* VAULT WIRING */
/// @dev Returns the vault's margin asset without calling the margin asset.
function _validateVault(address vault) private view returns (address marginAsset) {
if (!ILCCVaultFactory(factory).isVault(vault)) revert UnregisteredVault();
ILCCVault.AssetConfig memory config = ILCCVault(vault).assetConfig();
if (config.fundingAsset != usdc || config.usd3 != usd3 || config.notificationVault != usd3l) {
revert InvalidConfiguration();
}
if (config.marginAsset == usd3l) revert UnsupportedMarginAsset(config.marginAsset);
return config.marginAsset;
}
/// @dev Requires `marginAsset` to be an ERC-4626 vault over USDC; checked only on entries that source margin.
function _requireUsdcVault(address marginAsset) private view {
if (marginAsset.code.length == 0) revert UnsupportedMarginAsset(marginAsset);
try IERC4626(marginAsset).asset() returns (address asset) {
if (asset == usdc) return;
} catch {}
revert UnsupportedMarginAsset(marginAsset);
}
}
lib/openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
lib/openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/IOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title IOracle
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that oracles used by Morpho must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
/// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
/// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
/// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
/// decimals of precision.
function price() external view returns (uint256);
}
src/lcc/interfaces/ILCCLeveragedFundHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.35;
import {IMorphoBlue} from "./IMorphoBlue.sol";
/// @title ILCCLeveragedFundHelper
/// @notice Levered LCC positions on canonical Morpho Blue, in three lifecycles: amortizing capital-call funding
/// (`fund`), shortfall-auction fills (`takeAuction`), and unwinds of the resulting position (`unwind`). Both entries
/// supply the USD3l the vault delivers as the caller's collateral and can borrow part of the USDC paid against it.
/// This interface is the helper's behaviour specification.
/// @dev Common shape. The helper pins the Morpho singleton, the LCC vault factory, and USD3l, and derives USD3 as
/// `usd3l.asset()` and USDC as `usd3.asset()`. Served markets: every request names a `market` (in `FundParams`,
/// `TakeParams`, and `UnwindParams` alike), which must be a market on the pinned singleton whose loan token is USDC and
/// collateral token is USD3l (`InvalidRequest` otherwise). Its oracle, IRM, and LLTV are chosen by the caller
/// among markets its curator created; the helper does not vet them. The LCC beneficiary, the Morpho `onBehalf`, and
/// the cooldown owner are always the caller. Only an entry that borrows reads the market oracle or needs Morpho
/// authorization, and after such an entry the loan-to-value of the caller's whole position in the market, valued at
/// the market oracle price with debt rounded up, must be within the caller's `maxEntryLtv`.
///
/// Flash bridge. An operation takes a Morpho flash loan only when the USDC it bridges is nonzero: `borrowAssets +
/// marginAssets` for an entry (repaid by the borrow and by USDC withdrawn from margin-asset shares), the repayment for
/// an unwind. During a bridged entry the singleton must physically hold `2 * borrowAssets + marginAssets` of USDC (the
/// flash loan, then the borrow). At most one operation is in flight: the helper records the hash of the loaned amount
/// and the payload in transient storage, the callback runs only from Morpho and only for that hash, and the record is
/// consumed before any external call. Sizing reads previews (the funding amount's `usd3.previewMint(1)` and, on a
/// `usd3Out` unwind, USD3's `previewWithdraw`), but every delivered amount is a measured balance change, never a
/// preview.
///
/// Allowances and balances. Morpho holds standing maximal USD3l and USDC allowances from the helper, granted at
/// construction for collateral supply, flash-loan repayment, and debt repayment. They expose nothing because Morpho
/// pulls only from its `msg.sender` and the helper holds no USD3l or USDC of its own between transactions. The standing
/// USDC allowance does not cap Morpho's pulls the way an exact approval would: the helper relies on canonical Morpho
/// pulling exactly the repay and flash amounts, and an unwind's end-of-entry USDC balance check catches any excess.
/// Mainnet USDC decrements even a maximal allowance by each pull, so the standing USDC allowance declines by cumulative
/// pulls from `2^256 - 1`. Each vault receives an exact USDC approval that must be spent in full
/// (`VaultAmountMismatch`). Every entrypoint requires the helper's USD3l balance to end where it started
/// (`UnexpectedBalance`), so donated USD3l is never touched.
///
/// Cooldown book. Every entry opens a `Cooldown` for the collateral it supplied, at most `MAX_COOLDOWNS` per user and
/// market, after first trimming the book to the user's live collateral (see `trimCooldowns`). A book still full after
/// the trim never merges a matured cooldown with an unmatured one unless the USD3l cooldown duration decreased between
/// entries (see `CooldownsMerged`), so a matured cooldown otherwise stays unwindable however many entries follow it
/// while the collateral covering it stays in the position, and no entry reverts for book reasons.
/// Unwinds consume cooldowns oldest first and emit no per-cooldown record: a user's matured shares are read from
/// `cooldowns()` together with the live USD3l `cooldownDuration`, and `maxUnwindable` combines them with live
/// collateral. Entries are the only way a cooldown starts, unwind consumption and the trim the only ways one is
/// reduced or removed, and the full-book merge the only other change.
///
/// Unwind. USD3l management grants the helper the USD3l cooldown bypass, which it uses only for collateral it
/// withdraws from the caller's own position and only up to the caller's matured cooldowns. The gate is waived while
/// USD3l is shut down or its cooldown is zero, mirroring the vault's own waivers; a waived unwind still consumes
/// cooldowns oldest first regardless of maturity, so outside a USD3l cooldown waiver bypass redemptions for a user
/// never exceed the USD3l the helper supplied for that user, each at least the cooldown after it was supplied, even
/// after a waiver that has ended. Under a waiver USD3l itself applies no cooldown, so a waived unwind can redeem more
/// than the book holds. Accepted residuals: collateral that leaves the position (directly or by liquidation) and is
/// re-supplied directly, with no entry or `trimCooldowns` in between, can be unwound against the departed shares'
/// matured cooldowns, which is weaker than the USD3l vault's own transfer lock on cooled shares; and cooldowns never
/// expire, because the live USD3l `withdrawalWindow` is effectively unbounded (2^63 seconds).
///
/// Surface. Entrypoints are `nonReentrant`. The helper holds no factory role, never deposits into USD3 itself (the
/// vault is the USD3 depositor and holds the supply-cap exemption), and has no owner, rescue, receiver-choice,
/// delegated-beneficiary, arbitrary-call, or upgrade surface. Accepted properties: the Morpho authorization is global
/// across the caller's Morpho positions and stays enabled until the caller revokes it; there is no entry-LTV buffer
/// below LLTV beyond the caller's own bound; entries are allowed while a USD3 loss is pending; the market's oracle,
/// LLTV, and liquidation strategy belong to its curator.
interface ILCCLeveragedFundHelper {
/// @param vault Factory-registered LCC vault whose current-epoch obligation the caller funds.
/// @param market Served market (see the interface's served-market rule) in which the caller's collateral is
/// supplied and from which `borrowAssets` is borrowed.
/// @param borrowAssets USDC borrowed from `market` on behalf of the caller; zero borrows nothing. An entry is fully
/// levered when `borrowAssets` equals `fundingAmount = max(obligation, usd3.previewMint(1))`, which includes the
/// one-share top-up; on a dust obligation `borrowAssets = obligation` with `maxContribution = 0` therefore reverts
/// `ContributionExceedsMax`.
/// @param marginAssets USDC the caller sources from the margin the vault releases to it inside `fundCall`; zero
/// uses no margin and never calls the margin asset. When nonzero, the vault's margin asset must be an ERC-4626
/// vault
/// whose `asset()` is USDC (`UnsupportedMarginAsset` otherwise). After the release the helper withdraws exactly
/// `marginAssets` of USDC from the caller's margin-asset shares (`UnexpectedBalance` unless exactly that
/// arrives); the shares burned, measured as the caller's balance change, may exceed neither `maxMarginShares`
/// (`MarginSharesExceedMax`) nor the shares the vault released to the caller in this entry
/// (`MarginSharesUnavailable`), so a pre-existing margin-asset balance is never consumed. Integrators set it to the
/// `previewRedeem` of the released shares `activeMargin * obligation / activeCommitment` (rounded down, as the
/// vault does) or just under.
/// @param maxMarginShares Maximum margin-asset shares the withdrawal may burn; must be nonzero when `marginAssets`
/// is (`InvalidRequest`). The caller's margin-asset allowance or permit must cover it.
/// @param maxContribution Maximum USDC pulled from the caller (funding amount minus `borrowAssets` and
/// `marginAssets`).
/// @param minCollateral Minimum USD3l the vault must deliver to the caller for this funding
/// (`CollateralBelowMinimum`); must be nonzero and at most `maxCollateral` (`InvalidRequest`). Integrators
/// set it just under `usd3l.previewDeposit(usd3.previewDeposit(fundingAmount))`.
/// @param maxCollateral Maximum USD3l supplied as collateral and pulled from the caller; any delivery above it
/// stays in the caller's wallet. Integrators set it at or just above the preview.
/// @param maxEntryLtv Maximum loan-to-value of the caller's whole position in `market` after a levered entry,
/// WAD-scaled like Morpho's LLTV (`EntryLtvExceeded`). Checked only when `borrowAssets` is nonzero.
/// @param maxObligation Maximum capital-call obligation the caller accepts to fund (`ObligationExceedsMax`).
/// @param deadline Last timestamp at which the call may execute (`DeadlineExpired`).
struct FundParams {
address vault;
IMorphoBlue.MarketParams market;
uint256 borrowAssets;
uint256 marginAssets;
uint256 maxMarginShares;
uint256 maxContribution;
uint256 minCollateral;
uint256 maxCollateral;
uint256 maxEntryLtv;
uint256 maxObligation;
uint256 deadline;
}
/// @param market Served market (see the interface's served-market rule) that holds the caller's position.
/// @param shares USD3l collateral shares to withdraw and redeem; nonzero (`InvalidRequest`), at most the
/// caller's live collateral in `market` (`SharesExceedCollateral`) and, unless the USD3l cooldown is waived, at
/// most the caller's matured cooldown shares there (`InsufficientMaturedShares`). While the cooldown is waived the
/// unwind consumes up to `shares` of the caller's cooldowns oldest first regardless of maturity.
/// @param full Repay the caller's whole debt in `market`, priced on-chain after accruing interest and repaid by
/// shares, leaving zero debt; `repayAssets` is then ignored.
/// @param repayAssets USDC of debt to repay when `full` is false; at most the current debt (`RepayExceedsDebt`). It
/// is converted to borrow shares rounding down (a nonzero amount buying no share reverts `RepayRoundsToZero`) and
/// repaid by shares, so the amount actually repaid is those shares' value rounded up, at most `repayAssets`. Zero
/// repays nothing.
/// @param maxRepayAssets Maximum USDC the repayment may cost (`RepayExceedsMax`).
/// @param usd3Out Deliver the remainder as USD3 instead of USDC. Only the repayment is converted to USDC (through
/// USD3's `withdraw`); with nothing to repay no USD3 is converted and USD3's withdraw limit is never read, so such
/// an unwind works during a USD3 pending loss or waUSDC pause. USD3 carries no cooldown, which lives on USD3l.
/// @param minOut Minimum amount of the output token sent to the caller, USD3 when `usd3Out` and USDC otherwise
/// (`UnwindOutputBelowMinimum`).
/// @param deadline Last timestamp at which the call may execute (`DeadlineExpired`).
struct UnwindParams {
IMorphoBlue.MarketParams market;
uint256 shares;
bool full;
uint256 repayAssets;
uint256 maxRepayAssets;
bool usd3Out;
uint256 minOut;
uint256 deadline;
}
/// @dev Every quoted amount is quoted at `maxFill`. The fill is sized on-chain as `min(maxFill, remaining
/// shortfall)` after the vault's sync, and every quoted amount is scaled by `fill / maxFill`, so a partial or
/// front-run fill keeps the caller's per-unit protections. Dust rule: the quoted contribution (`maxFill -
/// borrowAssets - marginAssets`) and `marginAssets` scale rounding down and the rounding dust goes to the borrow,
/// else the margin, else the contribution, so the scaled borrow, margin, and contribution sum to the fill, a quote
/// without a contribution pulls none, and the scaled borrow (or margin) may exceed its pro-rata share by up to two
/// base units. `minMarginAward` scales rounding down, and `minCollateral` scales rounding down with a floor of one
/// share. The contribution never exceeds the quoted one, so it carries no separate bound.
/// @param vault Factory-registered LCC vault whose live shortfall auction the caller fills.
/// @param market Served market (see the interface's served-market rule) in which the delivered USD3l is supplied as
/// the caller's collateral and from which the scaled borrow is borrowed.
/// @param maxFill USDC the caller offers and the denominator of every scaled field; must be nonzero
/// (`InvalidRequest`). Quote it near the expected remaining shortfall rather than `type(uint256).max`, or the
/// scaled amounts lose their precision.
/// @param minFill Smallest acceptable fill, at most `maxFill` (`InvalidRequest`, `FillBelowMinimum`); zero
/// accepts any nonzero fill.
/// @param borrowAssets USDC borrowed at `maxFill`; scaled to the fill, taking the rounding dust, so a nonzero quote
/// always borrows. A take with zero `borrowAssets` needs no Morpho authorization and never reads the market oracle.
/// @param marginAssets USDC sourced from the margin award at `maxFill`; scaled to the fill rounding down, or taking
/// the rounding dust when `borrowAssets` is zero. Zero forwards the whole award to the caller. When nonzero, the
/// vault's margin asset must be an ERC-4626 vault whose `asset()` is USDC (`UnsupportedMarginAsset` otherwise);
/// the helper withdraws exactly the scaled amount of USDC from the award it received (`UnexpectedBalance`) at the
/// margin asset's conversion rate at execution, and forwards the rest. The shares this burns are bounded only by
/// the award received in this take (`MarginSharesUnavailable`), with no caller-set share bound like
/// `FundParams.maxMarginShares`, so the award the caller retains depends on that rate.
/// @param minMarginAward Minimum margin award at `maxFill`, scaled to the fill rounding down (it is a floor, and
/// the vault floors its award) and passed to the vault. The award is pro-rata in the fill, so the scaled bound
/// keeps its per-unit meaning. It bounds the gross award the vault pays, before the `marginAssets` withdrawal, not
/// the remainder forwarded to the caller.
/// @param minCollateral Minimum USD3l the vault must deliver at `maxFill`; must be nonzero
/// (`InvalidRequest`). It scales rounding down with a floor of one share, because the delivery itself
/// floors twice (USD3, then USD3l). Integrators quote it at `maxFill` from
/// `usd3l.previewDeposit(usd3.previewDeposit(maxFill))` with slack, because the scaled quote and a live double
/// preview at the fill differ by rounding. All delivered USD3l is supplied as collateral; a caller who wants part
/// of it liquid withdraws unlevered collateral from Morpho afterwards.
/// @param maxEntryLtv Maximum loan-to-value of the caller's whole position in `market` after the take, WAD-scaled
/// like Morpho's LLTV (`EntryLtvExceeded`); checked only when the scaled borrow is nonzero.
/// @param deadline Last timestamp at which the call may execute (`DeadlineExpired`).
struct TakeParams {
address vault;
IMorphoBlue.MarketParams market;
uint256 maxFill;
uint256 minFill;
uint256 borrowAssets;
uint256 marginAssets;
uint256 minMarginAward;
uint256 minCollateral;
uint256 maxEntryLtv;
uint256 deadline;
}
/// @notice A cooldown for USD3l collateral one funding or take entry supplied. It matures at
/// `start + max(duration, live USD3l cooldownDuration)` and never expires.
struct Cooldown {
uint128 shares;
uint64 start;
uint64 duration;
}
/// @notice A funding or take entry started a cooldown for the collateral it supplied.
event CooldownStarted(
address indexed user, bytes32 indexed marketId, uint256 shares, uint256 start, uint256 duration
);
/// @notice A funding or take entry found the book still full after its trim and merged two cooldowns; the fields
/// are the merged cooldown. Maturity is judged at the live USD3l duration: when the two oldest cooldowns are both
/// matured they merge into the oldest slot and the entry's cooldown takes the freed last slot; otherwise, when the
/// youngest cooldown is not matured, the entry's cooldown folds into it in place. Otherwise (the youngest matured
/// while the oldest pair is not both matured, reachable only after the USD3l cooldown duration decreased between
/// entries, which the current NotificationVault cannot do) the two oldest merge, which can delay a matured oldest
/// cooldown to the second's maturity. `shares` is the inputs' sum, `start` the later of their starts, and
/// `duration` runs from that start to the later of their recorded maturities (`start + duration`), so the merged
/// cooldown matures no earlier than either input under any live duration. `CooldownStarted` still reports the
/// entry's own cooldown.
event CooldownsMerged(
address indexed user, bytes32 indexed marketId, uint256 shares, uint256 start, uint256 duration
);
/// @notice `shares` were removed from `user`'s cooldowns in `marketId` by the trim rule of `trimCooldowns`, at an
/// entry or at `trimCooldowns`. Emitted only when shares were removed.
event CooldownsTrimmed(address indexed user, bytes32 indexed marketId, uint256 shares);
/// @notice An unwind repaid `repaidAssets` of debt, redeemed `shares` of collateral (consuming that many matured
/// cooldown shares, or up to that many cooldown shares regardless of maturity while the gate was waived), and sent
/// `amountOut` of `outToken` (USDC or USD3) to the caller.
event Unwound(
address indexed user,
bytes32 indexed marketId,
address outToken,
uint256 repaidAssets,
uint256 shares,
uint256 amountOut
);
/// @notice A take filled `filled` USDC of `vault`'s live shortfall auction for `user`: `collateral` USD3l was
/// supplied as the user's collateral in market `marketId`, `borrowed` USDC was borrowed for the user, and
/// `marginAssets` USDC was withdrawn from the margin award. The vault's `AuctionFill` in the same transaction
/// records the epoch and the gross award, and the margin-asset transfer to the user records the forwarded award.
event AuctionTaken(
address indexed user,
address indexed vault,
bytes32 indexed marketId,
uint256 filled,
uint256 collateral,
uint256 borrowed,
uint256 marginAssets
);
/// @notice EIP-2612 permit signed by the caller for this helper as spender.
/// @dev Permit replacement: `fundWithSignatures` always submits the USD3l permit, the USDC permit whenever the USDC
/// contribution is nonzero, and the margin-asset permit whenever `marginAssets` is nonzero, so a permit that
/// applies replaces the caller's standing allowance to this helper with `value`. A caller whose standing allowance
/// already suffices should use `fund`, or sign for the allowance it wants to stand after the call. A submitted
/// permit cannot outlive the call to be submitted later and reset the allowance. `value` must cover the amount
/// pulled at execution. The USDC contribution is `fundingAmount - borrowAssets - marginAssets`; a fully levered
/// entry (see `FundParams.borrowAssets`) pulls no USDC, does not submit its USDC permit, and leaves the standing
/// USDC allowance untouched (`fundWithSignatures` states what an unsubmitted permit can still do). The
/// contribution depends on the obligation and the `usd3.previewMint(1)` top-up at inclusion time, which can move
/// between signing and inclusion (for example after a USD3 report), so signers should over-approve. The USD3l
/// pulled is at most `FundParams.maxCollateral` and the USD3l permit is checked against that value before any
/// funding, so signers sign it for `maxCollateral`. The margin-asset permit is checked against
/// `FundParams.maxMarginShares`, so signers sign it for that value; an entry without margin does not submit it and
/// leaves the standing margin-asset allowance untouched.
struct PermitSignature {
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// Caller bounds: a bound the caller set, or a precondition the caller controls, does not hold.
/// @notice The caller submitted the request after its `deadline`.
error DeadlineExpired();
/// @notice The caller has not authorized this helper on Morpho, or the caller's authorization signature failed to
/// leave it authorized.
error NotAuthorized();
/// @notice The caller's allowance of `token` to this helper, after any permit the caller supplied (whose revert
/// data is `permitRevert`, empty when it applied or none was submitted), is below `required`.
error InsufficientAllowance(address token, uint256 allowance, uint256 required, bytes permitRevert);
/// @notice The caller's current-epoch obligation exceeds the caller's `maxObligation`.
error ObligationExceedsMax(uint256 obligation, uint256 maximum);
/// @notice The USDC the caller would contribute exceeds the caller's `maxContribution`.
error ContributionExceedsMax(uint256 contribution, uint256 maximum);
/// @notice The caller's `borrowAssets` and `marginAssets` together exceed the funding amount or `maxFill`.
error BorrowAndMarginExceedTotal(uint256 borrowAssets, uint256 marginAssets, uint256 total);
/// @notice The vault delivered less USD3l than the caller's (scaled) `minCollateral`.
error CollateralBelowMinimum(uint256 collateral, uint256 minimum);
/// @notice Withdrawing the caller's `marginAssets` burned more margin-asset shares than the caller's
/// `maxMarginShares`.
error MarginSharesExceedMax(uint256 shares, uint256 maximum);
/// @notice Withdrawing the caller's `marginAssets` burned more margin-asset shares than this entry made available:
/// the shares the vault released to the caller in a funding, or the margin award the helper received in a take.
error MarginSharesUnavailable(uint256 burned, uint256 available);
/// @notice After a levered entry, the loan-to-value of the caller's whole position exceeds the caller's
/// `maxEntryLtv`.
error EntryLtvExceeded(uint256 ltv, uint256 maximum);
/// @notice The auction's remaining shortfall makes the fill smaller than the caller's `minFill`.
error FillBelowMinimum(uint256 fill, uint256 minFill);
/// @notice The caller asked to unwind more shares than the caller's live collateral in the market.
error SharesExceedCollateral(uint256 shares, uint256 collateral);
/// @notice The caller's matured cooldown shares in the market do not cover the shares the caller asked to unwind.
error InsufficientMaturedShares(uint256 requested, uint256 matured);
/// @notice The caller's `repayAssets` exceeds the caller's current debt in the market.
error RepayExceedsDebt(uint256 repayAssets, uint256 debt);
/// @notice The caller's nonzero `repayAssets` buys no borrow share.
error RepayRoundsToZero(uint256 repayAssets);
/// @notice The repayment would cost more than the caller's `maxRepayAssets`.
error RepayExceedsMax(uint256 repayAssets, uint256 maximum);
/// @notice The unwind's redemption leaves less than the repayment needs; `token` names the unit: USDC on the USDC
/// path (redemption proceeds against the flash-loaned repayment), USD3 on the `usd3Out` path (the USD3 the
/// redemption produced against the USD3 previewed for, or actually burned by, the repayment's withdraw).
error RedemptionBelowRepayment(address token, uint256 available, uint256 required);
/// @notice The unwind would send the caller less of the output token than the caller's `minOut`.
error UnwindOutputBelowMinimum(uint256 amountOut, uint256 minimum);
// Request, vault and timing: the caller named a malformed request, an unusable vault or market, or a vault state
// with nothing to act on.
/// @notice The caller's request is malformed: its market's loan token is not USDC or collateral token not USD3l;
/// its collateral bounds are zero or inverted; it sources margin with zero `maxMarginShares`; its `maxFill` is zero
/// or below `minFill`; it unwinds zero shares; or an authorization it submits names another authorizer, another
/// authorized address than this helper, or does not enable.
error InvalidRequest();
/// @notice The caller named a vault the factory has not registered.
error UnregisteredVault();
/// @notice The vault's margin asset is unusable for the caller's request: USD3l for any entry; USDC or USD3 for a
/// take; or, when the request sources margin, not an ERC-4626 vault whose `asset()` is USDC.
error UnsupportedMarginAsset(address marginAsset);
/// @notice After the reads (and, for a take, the vault's sync) there is nothing to fund: the vault is not in its
/// Funding phase, the caller's obligation is zero, or the vault has no live shortfall auction.
error NothingToFund();
/// @notice The vault's one-share top-up over the caller's obligation exceeds the vault's `MAX_FUNDING_TOP_UP`.
error FundingTopUpExceeded(uint256 fundingAmount, uint256 obligation);
/// @notice Raised both at construction, when the deployer passed a codeless Morpho, factory, USD3l, USD3, or USDC,
/// and on a request, when the caller named a vault whose USDC, USD3, or USD3l wiring differs from this helper's.
error InvalidConfiguration();
// Internal invariants: a dependency behaved outside what the helper relies on.
/// @notice The vault funded or filled a different amount than requested, or left part of the helper's USDC
/// allowance unused.
error VaultAmountMismatch();
/// @notice The helper's balance of `token` is `balance` where `expected` was required; both fields are absolute
/// balances of `token`. The helper's USD3l balance must end every entrypoint where it started, a `usd3Out` unwind
/// must leave the helper's USDC balance unchanged, and a margin withdrawal must leave the helper's USDC balance
/// exactly the withdrawn amount above where it started.
error UnexpectedBalance(address token, uint256 balance, uint256 expected);
/// @notice The flash-loan callback came from someone other than Morpho, with no operation in flight, or with an
/// amount and payload that do not hash to the operation in flight; or Morpho's flash loan returned without running
/// the callback.
error InvalidCallback();
/// @notice Canonical Morpho Blue singleton.
function morpho() external view returns (address);
/// @notice LCC vault factory whose registered vaults may be funded.
function factory() external view returns (address);
/// @notice USDC, derived as `usd3().asset()`: the funding asset and every served market's loan token.
function usdc() external view returns (address);
/// @notice USD3, derived as `usd3l().asset()`.
function usd3() external view returns (address);
/// @notice USD3l, the notification vault wrapping USD3 and every served market's collateral token.
function usd3l() external view returns (address);
/// @notice Maximum open cooldowns per user and market; an entry into a book still full after its trim merges two
/// cooldowns as `CooldownsMerged` describes.
function MAX_COOLDOWNS() external view returns (uint256);
/// @notice Funds the caller's current-epoch obligation in `params.vault` with amortizing push funding, borrowing
/// `params.borrowAssets` against the USD3l the funding delivers. For obligation `O` the vault pulls the funding
/// amount `F = max(O, usd3.previewMint(1))` and the caller contributes `F - borrowAssets - marginAssets` USDC
/// (`BorrowAndMarginExceedTotal` when the parts exceed `F`). The helper pays the vault through `fundCall(address)`,
/// which releases margin to the caller, measures the USD3l the caller received, supplies up to `maxCollateral` of
/// it as the caller's collateral, withdraws `marginAssets` of USDC from the released margin, and borrows
/// `borrowAssets`.
/// Requires, before any token moves: a Morpho authorization of this helper by the caller when
/// `params.borrowAssets` is nonzero (`NotAuthorized`, checked first); a registered vault (`UnregisteredVault`)
/// wired to this helper's USDC, USD3, and USD3l (`InvalidConfiguration`) whose margin asset is not USD3l
/// (`UnsupportedMarginAsset`); the vault's Funding phase and a nonzero obligation (`NothingToFund`); the one-share
/// top-up within the vault's `MAX_FUNDING_TOP_UP` (`FundingTopUpExceeded`); and the caller's allowances to this
/// helper: USDC covering the contribution only when it is nonzero, USD3l covering `params.maxCollateral`, and
/// margin-asset shares covering `params.maxMarginShares` only when `params.marginAssets` is nonzero
/// (`InsufficientAllowance`, in that order).
/// @dev The vault replays the caller's account under its bounded step limit inside `fundCall`, while the helper
/// reads the obligation through the vault's unbounded view replay, so an account stale by more than
/// `MAX_MATERIALIZE_STEPS` called epochs should call the vault's `materializeAccount` first; otherwise the entry
/// reverts `AccountMaterializationIncomplete` after the replay cost is paid. This applies to `fundWithSignatures`
/// as well.
/// @return obligation The obligation funded.
/// @return fundingAmount USDC delivered to the vault: the obligation, or USD3's one-share minimum if larger.
/// @return collateral USD3l supplied as Morpho collateral on behalf of the caller, at most `params.maxCollateral`.
function fund(FundParams calldata params)
external
returns (uint256 obligation, uint256 fundingAmount, uint256 collateral);
/// @notice `fund` that first applies the caller's signatures: the permits `PermitSignature` says it submits and,
/// when `params.borrowAssets` is nonzero and the caller has not yet authorized this helper on Morpho, an enabling
/// Morpho authorization. A signature this call does not apply is not submitted and stays unused: anyone can
/// submit a nonzero one once until its deadline, and it then restores the allowance or authorization it signs for
/// this helper, even after the caller has lowered or revoked it. Because this helper pulls tokens and borrows only
/// for `msg.sender`, that serves only the caller's own later helper calls; callers should zero a signature they do
/// not need or give it a short deadline. The resulting allowance must cover the requirement
/// (`InsufficientAllowance`, carrying the permit's revert data).
/// @dev A submitted signature that fails to apply is tolerated when the allowance or authorization it grants is
/// already in place, so a third party submitting the same signature first cannot make this call revert. An applied
/// authorization payload must name the caller as authorizer and this helper as authorized and must enable
/// (`InvalidRequest`); an authorization that is still missing after submission reverts `NotAuthorized`. The enable
/// signature is separable: a third party can submit it on its own, and the authorization then stands even if this
/// call reverts.
function fundWithSignatures(
FundParams calldata params,
PermitSignature calldata usdcPermit,
PermitSignature calldata usd3lPermit,
PermitSignature calldata marginPermit,
IMorphoBlue.Authorization calldata authorization,
IMorphoBlue.Signature calldata authorizationSignature
) external returns (uint256 obligation, uint256 fundingAmount, uint256 collateral);
/// @notice Fills the live shortfall auction of `params.vault` for the caller, supplying the USD3l the vault
/// delivers as the caller's collateral in `params.market` and borrowing the scaled `params.borrowAssets` against
/// it. Requires the caller's Morpho authorization of this helper when `params.borrowAssets` is nonzero
/// (`NotAuthorized`, checked first), then fail-fast checks with view reads only, and a margin asset other than USDC
/// or USD3 (`UnsupportedMarginAsset`). The helper then syncs the vault through a permissionless `synced`
/// entrypoint: when an auction slot is already live it pokes `finalizeEpochSlash` of that auction's epoch, whose
/// body is a no-op because the epoch is already slash-finalized; otherwise it pokes `materializeAccount(helper)`,
/// which kicks an untouched auction whose slash became eligible and leaves an inert helper account in the vault.
/// Either sync settles an expired auction or one under shutdown, and a paused vault reverts there. The helper then
/// reverts `NothingToFund` when no auction is live, sizes the fill as `min(maxFill, remaining shortfall)`
/// (`FillBelowMinimum` below `minFill`), and scales every quoted amount (see `TakeParams`). Only the caller's USDC
/// allowance covering the scaled contribution is required, and only when it is nonzero. There is no signature
/// variant. Emits `AuctionTaken`.
/// @dev The vault's filler is this helper: it pays exactly the fill through the vault's `takeAuction` with the
/// scaled `minMarginAward`, receives the USD3l delivery and the margin award, supplies all of the measured USD3l
/// (at least the scaled `minCollateral`) for the caller, withdraws the scaled `marginAssets` of USDC from the award
/// when nonzero, forwards the rest of the award, and borrows the scaled borrow. The collateral supplied opens a
/// cooldown as a funding entry does. The vault's own checks (liveness after its sync, `InsufficientMarginAward`,
/// the margin oracle) apply to the fill, a fill that completes the shortfall settles the auction inside the vault,
/// and a residual below one USD3 share is unfillable because fills get no top-up. The sync is part of this
/// transaction, so a later revert rolls it back.
/// @return filled USDC paid to the vault for the fill.
/// @return collateral USD3l supplied as Morpho collateral on behalf of the caller.
function takeAuction(TakeParams calldata params) external returns (uint256 filled, uint256 collateral);
/// @notice Withdraws `params.shares` of the caller's USD3l collateral from `params.market`, repays the requested
/// debt with a Morpho flash loan of that amount, redeems the withdrawn USD3l to USD3 under this helper's USD3l
/// cooldown bypass, converts to USDC either all of that USD3 or, with `params.usd3Out`, only the repayment, repays
/// the flash loan, and sends the rest to the caller in USDC or USD3. Requires the caller's Morpho authorization of
/// this helper (`NotAuthorized`; unlevered and margin-only funders never granted it) and, unless the USD3l cooldown
/// is waived, matured cooldowns covering `params.shares`, consumed oldest first before any state-changing external
/// call. With nothing to repay no flash loan is taken. A partial unwind leaves debt, so Morpho's health check (and
/// the market oracle) applies to the withdrawal. Every conversion has zero loss tolerance. USD3's own withdraw
/// limit (pending loss, waUSDC liquidity, ring fence, floors) and the bypass grant can make the redemption revert;
/// the whole call then reverts and the cooldowns are restored. On the USDC path, redemption proceeds below the
/// flash-loaned repayment revert `RedemptionBelowRepayment` in USDC; on the `usd3Out` path, a repayment needing
/// more USD3 than the redemption produced reverts `RedemptionBelowRepayment` in USD3, and the helper's USDC
/// balance must end unchanged (`UnexpectedBalance`). Donated USD3l, USD3, and USDC are never touched. Emits
/// `Unwound`.
/// @return repaidAssets USDC of debt repaid: the repaid shares' value rounded up, which the flash loan covers.
/// @return amountOut Amount of the output token sent to the caller: USD3 with `params.usd3Out`, USDC otherwise.
function unwind(UnwindParams calldata params) external returns (uint256 repaidAssets, uint256 amountOut);
/// @notice `unwind` that first applies the caller's enabling Morpho authorization of this helper when it is not
/// already in place, with the same tolerance as `fundWithSignatures`; otherwise the authorization is ignored.
function unwindWithAuthorization(
UnwindParams calldata params,
IMorphoBlue.Authorization calldata authorization,
IMorphoBlue.Signature calldata authorizationSignature
) external returns (uint256 repaidAssets, uint256 amountOut);
/// @notice Trims `user`'s cooldowns in market `marketId` to `user`'s live collateral there: when the book total
/// exceeds it, the excess is removed oldest first regardless of maturity (`CooldownsTrimmed`); otherwise this is a
/// no-op that emits nothing. Every funding and take entry applies the same trim to the caller's book before it
/// supplies any collateral, so an entry trims to the caller's pre-entry collateral and the book total never exceeds
/// live collateral after any entry or trim. Permissionless, and moves no tokens. Consequence: anyone can trim a
/// user who withdrew collateral directly from Morpho and later re-supplies it, so that user waits one more cooldown
/// for the re-supplied shares; a user avoids this by unwinding through the helper. A liquidation executor that
/// holds its own USD3l cooldown bypass is expected to call this in the liquidation transaction, so the liquidated
/// user's book never covers collateral that left the position.
/// @return trimmed Shares removed from the book.
function trimCooldowns(address user, bytes32 marketId) external returns (uint256 trimmed);
/// @notice `user`'s open cooldowns in market `marketId`, oldest first. With the live USD3l `cooldownDuration`
/// this is the matured-share bookkeeping: a cooldown is matured from `start + max(duration, cooldownDuration)` on.
function cooldowns(address user, bytes32 marketId) external view returns (Cooldown[] memory);
/// @notice The most shares `user` can unwind in market `marketId` by the cooldown gate and live collateral; USD3's
/// withdraw limit and Morpho's health check are not included. `marketId` is meant to be a market on the pinned
/// Morpho lending USDC against USD3l (the markets `unwind` accepts), which the view does not check: while the
/// USD3l cooldown is waived (shutdown or zero `cooldownDuration`) it returns `user`'s whole collateral for any
/// market id, including one `unwind` rejects. Outside a waiver, a market with no booked cooldowns returns zero.
function maxUnwindable(address user, bytes32 marketId) external view returns (uint256);
}
src/lcc/interfaces/ILCCNotificationVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.35;
/// @title ILCCRedeemableVault
/// @notice TokenizedStrategy redemption and withdrawal with an explicit loss bound, as exposed by USD3 and USD3l.
interface ILCCRedeemableVault {
function redeem(uint256 shares, address receiver, address owner, uint256 maxLoss) external returns (uint256 assets);
function withdraw(uint256 assets, address receiver, address owner, uint256 maxLoss)
external
returns (uint256 shares);
}
/// @title ILCCNotificationVault
/// @notice The USD3 Notification Vault (USD3l) views the leveraged funding helper reads for its cooldown gate.
interface ILCCNotificationVault is ILCCRedeemableVault {
function cooldownDuration() external view returns (uint64);
function isShutdown() external view returns (bool);
}
src/lcc/interfaces/ILCCVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.22 <0.9.0;
import {LCCAuctionLib} from "../libraries/LCCAuctionLib.sol";
/// @title ILCCVault
/// @author 3Jane
/// @custom:contact [email protected]
/// @notice Interface for the LCC vault: a per-facility callable-credit primitive (not
/// ERC-4626, no transferable shares). Depositors post one ERC20 `marginAsset` as a performance bond; the vault
/// values it through a trusted Morpho-style oracle and leverages it by `marginRatioBps` into a commitment
/// denominated in `fundingAsset`. The owner opens at most one capital call per epoch; called users fund their
/// pro-rata obligation all-or-nothing (the funding is delivered as wrapped USD3l) and get the backing margin
/// released proportionally. Unfunded obligations are slashed after the funding deadline, and the resulting
/// shortfall is offered through an epoch-shortfall Dutch auction.
/// @dev Unit convention: amount-like accounting values outside the margin family are denominated in `fundingAsset`
/// unless documented otherwise; margin amounts are in `marginAsset`; `marginValue` is margin valued in
/// `fundingAsset`; epoch fields are epoch indices; `*Bps` fields are basis points (out of 10_000). Events and
/// errors are exposed through `LCCEventsLib` and `LCCErrorsLib`. Settlement consumers read `AuctionSettled` for
/// fill totals and `SlashSurplusDisposed` for the disposal split. Scheduled sunset is modeled by `maxEpochs`: when
/// nonzero, epochs `0..maxEpochs-1` are callable and epoch `maxEpochs` starts a terminal withdraw-only phase.
/// Oracle-tolerant wind-down surplus disposal applies to shutdown-truncated epochs and the last callable epoch (or
/// later); older epochs retain going-concern terms even when first disposed during shutdown or terminal. Accounts
/// lagging more than 64 finalized calls may need permissionless `materializeAccount` batches before
/// `claimRemainingMargin` can complete. LCC vaults are deployed as BeaconProxy instances behind an UpgradeableBeacon
/// controlled by 3Jane's 7-day timelock; the beacon owner can replace logic for every beacon-backed vault after the
/// timelock delay.
/// Factory registry membership records owner-vetted provenance, not exclusive deployability: non-factory proxies can
/// point at the public beacon and remain unregistered.
interface ILCCVault {
/// @notice Thrown when a depositor still has exposure in another family vault.
error RegisteredElsewhere(address vault);
/// @notice Thrown when an exit request would create more tracked maturity buckets than the vault supports.
error ExitCapacityReached();
/// @notice Thrown when an exit cannot be assigned within the caller's maximum accepted deferral.
error ExitDeferralExceeded();
/// @notice Timestamp-derived lifecycle phase within an epoch.
/// @dev `Normal`: deposits activate immediately (until a call opens). `PreCall`: the owner may open the epoch
/// call. `Funding`: called users fund their obligations. `Closed`: funding deadline passed; slashing and the
/// shortfall auction occur.
enum Phase {
Normal,
PreCall,
Funding,
Closed
}
/// @notice Facility configuration consumed by the initializer.
/// @param marginAsset ERC20 posted as the performance bond. Must be standard (no fee-on-transfer / rebasing).
/// @param marginOracle Trusted oracle returning the margin-to-fundingAsset price scaled by ORACLE_PRICE_SCALE.
/// @param startTimestamp Epoch-zero start; the epoch clock is derived from this. Bounded to uint64.
/// @param maxEpochs Maximum callable epochs; 0 means perpetual. Bounded to uint64.
/// @param epochLength Total epoch duration in seconds (Normal + PreCall + Funding + Closed). Bounded to uint32.
/// @param normalDuration Seconds of the Normal phase. Bounded to uint32.
/// @param preCallDuration Seconds of the PreCall phase. Bounded to uint32.
/// @param fundingDuration Seconds of the Funding phase. Bounded to uint32.
/// @param marginRatioBps Leverage ratio in bps: commitment = marginValue * BPS / marginRatioBps.
/// @param protocolCommitmentCap Vault-wide cap on active+pending commitment (fundingAsset). The exit-capacity
/// denominator is the greater of this cap and aggregate live `activeCommitment`. Bounded by type(uint128).max.
/// @param userCommitmentCap Per-account cap on active+pending commitment (fundingAsset).
/// @param exitCapBps Per-epoch exit capacity as a fraction of the exit-capacity denominator, in bps; must satisfy
/// `exitCapBps * 64 >= 2 * BPS` (>= 313) and `<= BPS`.
/// @param exitDelayEpochs Minimum epochs between a Normal-phase exit request and its earliest maturity; requests
/// after Normal add one epoch to preserve prospective call exposure while another call can still open. At most 64.
/// @param minCommitmentEpochs Minimum epochs an account must be committed (counted from commitmentStartEpoch,
/// the later of its latest deposit activation and one epoch after the call that produced its latest nonzero
/// return-pool re-credit) before it can request an exit; at most 64, 0 disables the gate. Composed lockup: the
/// earliest exit request is commitmentStartEpoch + minCommitmentEpochs and the earliest maturity adds
/// exitDelayEpochs. Wind-down claims (shutdown or terminal) bypass the gate.
/// @param minDepositAssets Minimum margin deposit, in marginAsset units.
/// @param auctionStepCount Divisor used to derive the Closed-window step duration; 0 disables the auction
/// entirely, otherwise must be at least 2. Because the duration is floor-rounded and the live step index is
/// uncapped, a remainder can make live steps reach or exceed this configured count. Bounded to uint32, and its
/// derived step duration is also bounded to uint32.
/// @param auctionStepDecayRateBps Per-step decay of the protocol's retained pool share, in bps.
/// @param maxAuctionAwardBps Oracle-valued collateral award cap per fundingAsset filled, in bps; 0 disables.
/// @param slashFeeBps Fee on auction-awarded slashed margin, clamped to the unawarded surplus, in bps.
struct VaultParams {
address marginAsset;
address marginOracle;
uint256 startTimestamp;
uint256 maxEpochs;
uint256 epochLength;
uint256 normalDuration;
uint256 preCallDuration;
uint256 fundingDuration;
uint256 marginRatioBps;
uint256 protocolCommitmentCap;
uint256 userCommitmentCap;
uint256 exitCapBps;
uint256 exitDelayEpochs;
uint256 minCommitmentEpochs;
uint256 minDepositAssets;
uint256 auctionStepCount;
uint256 auctionStepDecayRateBps;
uint256 maxAuctionAwardBps;
uint256 slashFeeBps;
}
/// @notice Initializes a beacon proxy vault with per-facility configuration.
/// @param params The facility configuration.
function initialize(VaultParams calldata params) external;
/// @notice Immutable asset and integration addresses for this vault.
/// @param marginAsset ERC20 posted as the performance bond.
/// @param fundingAsset ERC20 used to fund calls and auction fills.
/// @param usd3 ERC-4626 USD3 vault.
/// @param notificationVault ERC-4626 wrapper that receives funded amounts.
/// @param marginOracle Trusted oracle for margin-to-fundingAsset pricing.
/// @param treasury Recipient of slashed margin and unsold auction collateral.
struct AssetConfig {
address marginAsset;
address fundingAsset;
address usd3;
address notificationVault;
address marginOracle;
address treasury;
}
/// @notice Immutable epoch timing and commitment derivation configuration.
/// @param startTimestamp Epoch-zero start timestamp.
/// @param maxEpochs Maximum callable epochs; 0 means perpetual.
/// @param epochLength Total epoch duration in seconds.
/// @param normalDuration Seconds of the Normal phase.
/// @param preCallDuration Seconds of the PreCall phase.
/// @param fundingDuration Seconds of the Funding phase.
/// @param marginRatioBps Leverage ratio in bps.
/// @param exitDelayEpochs Minimum epochs between exit request and earliest maturity.
/// @param minCommitmentEpochs Minimum epochs since commitmentStartEpoch (the later of the latest deposit
/// activation and one epoch after the call that produced the latest nonzero return-pool re-credit) before an
/// exit request; 0 disables the gate.
struct EpochConfig {
uint256 startTimestamp;
uint256 maxEpochs;
uint256 epochLength;
uint256 normalDuration;
uint256 preCallDuration;
uint256 fundingDuration;
uint256 marginRatioBps;
uint256 exitDelayEpochs;
uint256 minCommitmentEpochs;
}
/// @notice Immutable auction timing and decay configuration.
/// @param auctionStepCount Configured divisor used to derive the Closed-window step duration; the live index is
/// uncapped and can exceed this value when the division has a remainder.
/// @param auctionStepDecayRateBps Per-step retained-pool decay, in bps.
/// @param auctionStepDuration Derived duration of each auction price step, in seconds.
struct AuctionConfig {
uint256 auctionStepCount;
uint256 auctionStepDecayRateBps;
uint256 auctionStepDuration;
}
/// @notice Mutable risk limits used by deposits, exits, and auction awards.
/// @param protocolCommitmentCap Vault-wide cap on active+pending commitment; exit capacity uses the greater of
/// this configured cap and aggregate live `activeCommitment`.
/// @param userCommitmentCap Per-account cap on active+pending commitment.
/// @param exitCapBps Per-epoch exit capacity fraction of the configured-cap/live-utilization denominator, in bps.
/// @param minDepositAssets Minimum margin deposit.
/// @param maxAuctionAwardBps Oracle-valued auction award cap per fundingAsset filled, in bps.
/// @param slashFeeBps Fee on auction-awarded slashed margin, clamped to the unawarded surplus, in bps.
struct RiskConfig {
uint256 protocolCommitmentCap;
uint256 userCommitmentCap;
uint256 exitCapBps;
uint256 minDepositAssets;
uint256 maxAuctionAwardBps;
uint256 slashFeeBps;
}
/// @notice Packed aggregate margin/commitment totals.
/// @dev Commitment totals are cap-bounded by `protocolCommitmentCap <= type(uint128).max`; margin totals rely on
/// the aggregate deployment invariant documented on the vault and fail safely via SafeCast if exceeded.
/// @param activeMargin Total active margin across all accounts (marginAsset).
/// @param activeCommitment Total active commitment across all accounts (fundingAsset).
/// @param pendingMargin Total pending margin across all accounts (marginAsset).
/// @param pendingCommitment Total pending commitment across all accounts (fundingAsset).
struct Totals {
uint128 activeMargin;
uint128 activeCommitment;
uint128 pendingMargin;
uint128 pendingCommitment;
}
/// @notice Packed global sync cursors and live-auction slot.
/// @param lastActivationFolded Highest epoch whose pending activations have been folded.
/// @param lastMaturityFolded Highest epoch whose maturity buckets have been folded.
/// @param finalizedCallPrefix Count of leading called epochs whose slash is finalized.
/// @param pendingAuctionEpochPlusOne Live-auction slot encoded as epoch + 1 (0 means none).
struct SyncState {
uint64 lastActivationFolded;
uint64 lastMaturityFolded;
uint64 finalizedCallPrefix;
uint64 pendingAuctionEpochPlusOne;
}
/// @notice Packed emergency shutdown state.
/// @param active Whether shutdown has been triggered.
/// @param timestamp Pause-adjusted effective timestamp at which shutdown was triggered (0 if not shut down).
/// @param epoch Epoch in which shutdown was triggered (0 if not shut down).
struct ShutdownState {
bool active;
uint64 timestamp;
uint64 epoch;
}
/// @notice Materialized per-account position (the in-memory shape returned by views; storage is packed).
/// @param activeMargin Margin currently callable (marginAsset).
/// @param activeCommitment Commitment backed by `activeMargin` (fundingAsset).
/// @param pendingMargin Margin deposited but not yet activated (marginAsset).
/// @param pendingCommitment Commitment of the pending margin (fundingAsset).
/// @param pendingActivationEpoch Epoch at which the pending balance activates (0 if none).
/// @param calledEpochCursor Replay cursor: index into `calledEpochs` up to which this account is materialized.
/// @param claimableExitMargin Matured exit margin awaiting claim (marginAsset).
/// @param exitBucketMargin This account's margin contribution to its maturity bucket (marginAsset).
/// @param exitBucketCommitment This account's commitment contribution to its maturity bucket (fundingAsset).
/// @param exitRequested True once a full-account exit has been requested.
/// @param exitMaturityEpoch Epoch at which the requested exit matures (callable until then).
/// @param exitClaimed True once the exit has completed or been cleared.
/// @param exitMatured True once the exit has matured (margin moved to `claimableExitMargin`).
/// @param commitmentStartEpoch Later of the account's latest deposit activation epoch and one epoch after the
/// call that produced its latest nonzero return-pool re-credit. The latter is the first epoch in which the
/// re-credited exposure can back a new call, so settlement delay cannot extend the minCommitmentEpochs gate.
/// Funding never changes it.
struct Account {
uint256 activeMargin;
uint256 activeCommitment;
uint256 pendingMargin;
uint256 pendingCommitment;
uint256 pendingActivationEpoch;
uint256 calledEpochCursor;
uint256 claimableExitMargin;
uint256 exitBucketMargin;
uint256 exitBucketCommitment;
bool exitRequested;
uint256 exitMaturityEpoch;
bool exitClaimed;
bool exitMatured;
uint256 commitmentStartEpoch;
}
/// @notice Per-epoch capital-call accounting, finalized lazily after the funding deadline.
/// @param callOpened True once the owner has opened this epoch's call.
/// @param commitmentDenominator Total active commitment snapshotted at call open; the pro-rata base for
/// obligations (fundingAsset).
/// @param callAmount Total amount called this epoch (fundingAsset). This is the nominal base for independently
/// computed pro-rata obligations, not a strict aggregate funding cap: because each obligation is ceil-rounded,
/// `fundedAmount` can settle slightly above `callAmount`.
/// @param marginAtCallOpen Total active margin snapshotted at call open (marginAsset).
/// @param fundedAmount Cumulative funded obligations this epoch (fundingAsset). May exceed `callAmount` by up to
/// ~(number of funding accounts - 1) units of rounding dust from per-account ceil obligations.
/// @param marginReleased Cumulative margin released to funders this epoch (marginAsset).
/// @param fundedUsersRemainingMargin Margin of fully-funded users retained for settlement after this call
/// (marginAsset).
/// @param fundedUsersRemainingCommitment Settlement counter for fully-funded users' commitment net of funded
/// obligations, not a live-position aggregate (fundingAsset).
/// @param slashFinalized True once slashing for this epoch has been finalized.
/// @param slashDisabledByShutdown True if shutdown landed before/within this epoch's funding window, so no
/// slash is taken.
/// @param slashedMargin Aggregate margin slashed for this epoch (marginAsset).
/// @param returnPool Slashed surplus returned to defaulters after the treasury fee and aggregate-margin packing
/// clamp. Retained in full when backed by nonzero settlement commitment (marginAsset).
/// @param returnCommitment Callable commitment paired with `returnPool`, bounded by the call-local slashed
/// commitment and, during going concern, current protocol-cap headroom over funded call-open exposure
/// (fundingAsset).
struct EpochState {
bool callOpened;
uint256 commitmentDenominator;
uint256 callAmount;
uint256 marginAtCallOpen;
uint256 fundedAmount;
uint256 marginReleased;
uint256 fundedUsersRemainingMargin;
uint256 fundedUsersRemainingCommitment;
bool slashFinalized;
bool slashDisabledByShutdown;
uint256 slashedMargin;
uint256 returnPool;
uint256 returnCommitment;
}
/// @notice Current epoch index derived from the pause-adjusted effective timestamp.
/// @return The current epoch.
function currentEpoch() external view returns (uint256);
/// @notice Current lifecycle phase derived from the pause-adjusted effective timestamp.
/// @return The current phase.
function currentPhase() external view returns (Phase);
/// @notice Wall-clock timestamp at which a given phase ends within a given epoch.
/// @dev Projects the effective-time boundary using the pause offset accumulated when queried. It is exact for
/// current and future boundaries while unpaused, but a boundary already in the past shifts if a later pause adds
/// to the offset. While paused, it assumes the vault is unpaused at the current wall-clock timestamp.
/// @param epoch Epoch to query.
/// @param phase Phase whose end is requested.
/// @return The wall-clock phase-end timestamp.
function phaseEndsAt(uint256 epoch, Phase phase) external view returns (uint256);
/// @notice Current pause circuit-breaker state.
/// @return paused Whether synced state-transitioning entrypoints are paused.
/// @return pausedAt Wall-clock timestamp at which the current pause began, or the previous pause began if unpaused.
/// @return pausedAccumulated Total wall-clock seconds subtracted from lifecycle time by completed pauses.
function pauseState() external view returns (bool paused, uint64 pausedAt, uint64 pausedAccumulated);
/// @notice Reports whether an account is permanently clear of exposure for family-registry migration.
/// @dev Replay is intentionally bounded. An incomplete replay conservatively reports not closed so a mandatory
/// deposit authorization path cannot become unbounded; anyone may materialize the account in batches first.
/// @param user Account whose stored and replayable exposure is inspected.
/// @return True only when bounded replay completes and leaves no active, pending, exiting, or claimable exposure.
function isAccountClosed(address user) external view returns (bool);
/// @notice Deposits caller-funded margin for a beneficiary, creating a bounded leveraged commitment.
/// @dev Pulls `assets` of marginAsset from the caller and irrevocably credits `onBehalfOf`. Self-deposits require
/// no deposit-operator role; a distinct payer must hold the factory's DEPOSIT_OPERATOR_ROLE. The final factory
/// authorization is deliberately fail-late and atomic, so a rejection unwinds the token pull and all state. A
/// successful deposit can extend the beneficiary's commitment lockup and consume their cap. It activates
/// immediately during Normal (before a call opens), otherwise stages as pending for the next epoch when permitted.
/// Deposits remain available during PreCall and while an opened call is unsettled, but are unavailable while an
/// auction is live. Reverts under shutdown, when activation would reach scheduled sunset, on a pending-blocking
/// exit, on an expired wall-clock deadline, on invalid commitment bounds, on a zero/sub-minimum amount, on a zero
/// beneficiary, on a zero oracle price, or if a cap would be exceeded.
/// @param assets Margin to deposit (marginAsset).
/// @param onBehalfOf Beneficiary whose margin and commitment account is credited.
/// @param minCommitment Minimum acceptable commitment, inclusive and nonzero.
/// @param maxCommitment Maximum acceptable commitment, inclusive.
/// @param allowPendingActivation Whether the deposit may be staged for the next epoch.
/// @param deadline Wall-clock timestamp after which the deposit reverts.
/// @return commitment Commitment created (fundingAsset).
function deposit(
uint256 assets,
address onBehalfOf,
uint256 minCommitment,
uint256 maxCommitment,
bool allowPendingActivation,
uint256 deadline
) external returns (uint256 commitment);
/// @notice Requests a full-account exit within caller-supplied maturity-deferral and wall-clock bounds.
/// @dev Capacity is at least one funding-asset unit and otherwise `exitCapBps` of the greater of the configured
/// protocol cap and aggregate live `activeCommitment`. The live-utilization floor is deliberately path-dependent
/// and ensures capacity is never below the configured-cap value at request time, but capacity can decline as
/// active commitment declines through amortization or slashing. Aggregate active commitment may conservatively
/// include unattributed return commitment, which only widens capacity. The account stays callable until maturity.
/// At execution, the earliest available maturity is re-evaluated from the executing `currentEpoch` plus
/// `exitDelayEpochs` during Normal, when that epoch's call outcome is still unknown. A request during PreCall,
/// Funding, or Closed adds one epoch. While another call can still open — outside shutdown and before the last
/// callable epoch's call window has passed — this makes the request span an epoch whose call outcome was unknown
/// when it was made; at the shutdown or sunset edge, `claimRemainingMargin` supplies the withdrawal path without
/// manufacturing call exposure. The phase boundary is deliberately conservative during PreCall before a call
/// opens: the holder is already bound to that epoch's unknown outcome, but still receives the bounded one-epoch
/// shift needed to cover call-free Funding uniformly. `maxDeferralEpochs` bounds displacement from that
/// phase-aware earliest maturity: 0 accepts only that maturity and `type(uint256).max` accepts any maturity. It
/// therefore bounds displacement within the executing epoch rather than pinning an absolute maturity on its own.
/// The two bounds compose: because execution cannot occur after `deadline`, the assigned maturity never exceeds
/// the epoch containing `deadline` plus `exitDelayEpochs`, the possible one-epoch phase adjustment, and
/// `maxDeferralEpochs`. Shortening `deadline` therefore tightens the absolute guarantee as well as limiting
/// mempool staleness. A bounded vault rejects an assigned maturity at or after `maxEpochs`; therefore its last
/// request boundary is the end of Normal in epoch `maxEpochs - 1 - exitDelayEpochs`. Configurations where
/// `minCommitmentEpochs + exitDelayEpochs >= maxEpochs` deliberately provide only terminal wind-down, not an
/// in-tenor exit request.
///
/// An account whose commitment exceeds the entire per-epoch capacity uses the oversized-account escape clause
/// only inside the `assigned < capacity` guard. It takes the first bucket with any remaining room and therefore
/// cannot be guaranteed the earliest bucket. Consequently `maxDeferralEpochs == 0` is systematically most likely
/// to revert for the largest positions, contrary to the natural intuition that they receive priority. Reverts if
/// the wall-clock deadline has expired, an exit is already pending, the account holds pending margin, or it has
/// no active position. Cap-raise sequences can still fill the 128-live-bucket list. If first-fit would then need
/// a new key, the request stays within the caller's deferral window and reuses the least-loaded eligible tracked
/// maturity (earliest on ties), but only when eligible scheduled commitment plus the account fits
/// `eligibleCount * capacity`. This is the only operative aggregate bound and constrains only narrow deferral
/// windows: admission is unconditional at `ceil(BPS / exitCapBps)` eligible keys (32 at the minimum cap ratio),
/// apart from base-unit flooring. The full-list fallback deliberately softens an individual bucket's capacity
/// without splitting the account. For eligible load `S`, eligible bucket count `N`, capacity `C`, and the
/// admitted account's actual commitment `A`, the aggregate gate is `S + A <= N * C`. Least-loaded selection
/// bounds the selected bucket's post-assignment load by `S / N + A <= C + A * (1 - 1 / N)`, so its overshoot is
/// strictly less than `A`; replay can make `A` exceed the live `userCommitmentCap`. The rejected
/// earliest-eligible alternative would retain only the aggregate bound and could concentrate an overshoot
/// approaching `(N - 1) * C` in one bucket. The fallback never tracks a 129th key and otherwise reverts
/// `ExitCapacityReached`.
/// @param maxDeferralEpochs Maximum accepted epochs past the earliest available maturity.
/// @param deadline Wall-clock timestamp after which the exit request reverts.
/// @return maturityEpoch The assigned maturity epoch.
function requestExit(uint256 maxDeferralEpochs, uint256 deadline) external returns (uint256 maturityEpoch);
/// @notice Claims matured exit margin to `receiver`.
/// @param receiver Recipient of the margin.
/// @return assets Margin transferred (marginAsset).
function claimExitedMargin(address receiver) external returns (uint256 assets);
/// @notice Withdraws remaining margin after emergency shutdown or scheduled terminal sunset.
/// @dev Pays active margin, pending margin, and already-matured claimable exit margin. Like other
/// state-touching calls, this may revert with `AccountMaterializationIncomplete` until a lagging account is
/// brought within the bounded replay window by `materializeAccount`.
/// @param receiver Recipient of the margin.
/// @return assets Margin transferred (marginAsset).
function claimRemainingMargin(address receiver) external returns (uint256 assets);
/// @notice Removes part or all of a user's callable commitment and returns the paired margin to that user.
/// @dev Callable only by a factory bouncer and unavailable while slash settlement is outstanding. Removes exactly
/// the requested nominal active commitment pro rata, rounded down in the user's favor. A bouncer waits one epoch
/// for a pending deposit to fold into active state; users whose exit is in progress are left to that exit. Partial
/// removal cannot leave active margin below `minDepositAssets`. Removing the entire active commitment from an
/// account with no pending, claimable, or exit state leaves zero exposure, and its family registry entry clears
/// lazily when the user next deposits elsewhere. Margin is always pushed directly to `user`; a blacklisted holder
/// of a blacklistable margin asset therefore cannot be bounced because the transfer reverts, and the operational
/// fallback is to pause or shut down the facility. The function remains available after shutdown and scheduled
/// terminal sunset. A lagging account may first need permissionless `materializeAccount` calls to complete bounded
/// replay.
/// @param user Account whose commitment is removed and that receives returned margin.
/// @param commitment Nominal active commitment to remove.
/// @return marginReturned Margin transferred to `user` (marginAsset).
function bounceCommitment(address user, uint256 commitment) external returns (uint256 marginReturned);
/// @notice Transfers all accrued treasury margin to the treasury.
/// @dev Permissionless, unsynced, and available while paused or shut down. The accrued ledger is zeroed before the
/// transfer and restored by transaction rollback if the margin token rejects the treasury recipient.
function sweepTreasury() external;
/// @notice Margin accrued for treasury but still held by the vault (marginAsset).
function pendingTreasuryMargin() external view returns (uint256);
/// @notice Owner update of mutable risk caps; configured caps apply to future deposits, while exit capacity is
/// recomputed per request from the greater of the configured cap and live active utilization. It can decline with
/// live utilization but never below the configured-cap value at that request.
/// @dev Any protocol-cap change is blocked while finalized slash surplus awaits auction settlement. Updates to
/// the other three parameters remain available when the protocol cap is unchanged.
/// @param newProtocolCommitmentCap New vault-wide commitment cap (fundingAsset); must be in (0, uint128.max].
/// @param newUserCommitmentCap New per-account commitment cap (fundingAsset).
/// @param newExitCapBps New per-epoch exit capacity, in bps (313 <= value <= BPS).
/// @param newMinDeposit New minimum margin deposit (marginAsset).
function setRiskCaps(
uint256 newProtocolCommitmentCap,
uint256 newUserCommitmentCap,
uint256 newExitCapBps,
uint256 newMinDeposit
) external;
/// @notice Triggers emergency shutdown: blocks new deposits/calls and enables remaining-margin withdrawal.
/// @dev Callable while paused. Shutdown ends the active pause, emits `Unpaused`, and records the same frozen
/// pause-adjusted timestamp so in-flight funding windows keep their slash-disable semantics. A later pause
/// remains available as a circuit breaker for the wind-down claim path.
function shutdown() external;
/// @notice Pauses synced state-transitioning entrypoints and freezes the derived lifecycle clock.
/// @dev Callable by the owner or guardian. Pause does not run global sync, so it remains available even if a
/// sync path is blocked. While paused, every `synced` entrypoint reverts before state progression: deposits,
/// exits, funding, auctions, slash finalization, account materialization, and owner risk/auction setters. The
/// live functions are shutdown, setMarginOracle, pause/unpause, factory role management, and views. Pause
/// remains callable after shutdown so a faulty wind-down claim path can be stopped.
function pause() external;
/// @notice Owner unpauses the vault and resumes every epoch window exactly where it froze.
/// @dev The pause has no time bound: margin stays frozen until the owner unpauses or shuts the vault down;
/// shutdown ends the active pause automatically.
function unpause() external;
/// @notice Owner opens the current epoch's capital call during PreCall.
/// @dev Reverts unless in PreCall of `epoch`, if a prior call is unsettled, if already opened, or if
/// `callAmount` exceeds the active-commitment base. Reads and snapshots the current margin-oracle price, reverting
/// on zero and propagating an oracle revert. Owner guidance: `callAmount` should be meaningful relative to the
/// active-commitment base and the account distribution. Because obligations are ceil-rounded per account (see
/// `obligationOf`), a dust-sized call can force every account to owe a single funding unit, and any account that
/// does not fund then forfeits its full margin under the all-or-nothing slash.
/// @param epoch Epoch to open the call for (must be current).
/// @param callAmount Total amount to call (fundingAsset).
function openEpochCall(uint256 epoch, uint256 callAmount) external;
/// @notice Funds the caller's own current-epoch obligation, all-or-nothing.
/// @dev The Funding phase is the timing guard. A delayed transaction landing in another epoch's Funding phase
/// would need to cross epoch end, Normal, and PreCall first. With `roll = false`, funding amortizes the position
/// by releasing proportional margin and reducing callable commitment. With `roll = true`, funding pays the
/// obligation and delivers wrapped USD3l while retaining the caller's full margin and full callable commitment;
/// that exposure re-arms each epoch, the caller's pro-rata share of successive calls grows as amortizers decay,
/// and lifetime funding obligations are unbounded while rolling. A live exiter cannot roll and reverts with
/// `ExitInProgress`; a live exiter may still fund with `roll = false`. Delivery always mints at least one USD3
/// share: when the obligation itself would round to zero shares, the payer supplies at most 1,000 extra
/// funding-asset base units and the beneficiary receives the full resulting USD3l amount. Settlement accounting
/// remains based on `obligationAmount`. Payers should approve `obligationOf(epoch, user) + 1_000` base units, or
/// compute `max(obligationOf(epoch, user), usd3.previewMint(1))` client-side. Reverts `FundingTopUpExcessive`
/// above that bound and `FundingDeliveryImpossible` when USD3 reports zero assets with nonzero supply. Either
/// error signals an incident state: pause to freeze the deadline and have the owner shut down before the frozen
/// deadline to disable slashing.
/// @param roll Whether to retain full margin and commitment after paying this call.
/// @return obligationAmount Per-account obligation paid (fundingAsset), the ceil-rounded pro-rata share.
function fundCall(bool roll) external returns (uint256 obligationAmount);
/// @notice Funds `user`'s current-epoch obligation with funding supplied by the caller (push-based).
/// @dev The caller pays; released margin, wrapped USD3l delivery, and funded status accrue to `user`. The
/// Funding phase is the timing guard, as on {fundCall}. Push funding always amortizes because the payer must not
/// control whether the user's margin remains locked and callable. A push fund can front-run and deny the user's
/// intended roll for that epoch: the payer donates the obligation plus any bounded delivery top-up, the user
/// receives wrapped USD3l and released margin, and the user can restore commitment by re-depositing the released
/// margin. The delivery guarantees and degenerate-USD3 incident procedure are the same as {fundCall(bool)}.
/// @param user Account whose obligation is funded.
/// @return obligationAmount Per-account obligation paid (fundingAsset), the ceil-rounded pro-rata share.
function fundCall(address user) external returns (uint256 obligationAmount);
/// @notice Fills up to `maxFillAmount` of the live auction's shortfall in exchange for wrapped USD3l and a
/// collateral kicker.
/// @dev Targets whichever auction is live, following Yearn-take semantics. The award is the current ramped
/// pro-rata kicker, capped by `maxAuctionAwardBps` of the fill at the fill-time oracle price. `minMarginAward` is
/// an absolute minimum applied to the award for the actual fill after `maxFillAmount` is clamped to the remaining
/// shortfall, not to `maxFillAmount`. A concurrent partial fill can therefore reduce both the caller's fill and
/// award enough to revert even when the per-unit award rate is unchanged. Callers seeking execution at a rate
/// rather than an absolute total should either size `maxFillAmount` below the observed remaining shortfall to
/// leave a contention buffer, or take through an atomic contract that reads the remaining shortfall and computes
/// the floor in the same transaction. An off-chain read or simulation, even in the same block, is not atomic with
/// inclusion. The floor is deliberately not prorated by `filledAmount / maxFillAmount`: its absolute form lets a
/// taker require a minimum notional that covers fixed gas costs, which a prorated floor cannot express. The
/// wall-clock `deadline` is checked as the first statement in the function body, after the `synced` modifier
/// runs; an expired deadline reverts the modifier's sync work along with the fill. Reverts if USD3 or the
/// notification vault cannot accept delivery. If a fill leaves a residual smaller than the assets required to
/// mint one USD3 share, the remaining shortfall cannot be filled because `maxFillAmount` is a caller ceiling and
/// no top-up is taken; it settles through normal window-end disposal without rolling over.
/// @param maxFillAmount Maximum shortfall to fill (fundingAsset).
/// @param minMarginAward Minimum acceptable collateral kicker (marginAsset).
/// @param deadline Wall-clock timestamp after which the transaction reverts.
/// @return filledAmount Shortfall actually filled (fundingAsset).
/// @return marginAward Collateral kicker awarded (marginAsset).
function takeAuction(uint256 maxFillAmount, uint256 minMarginAward, uint256 deadline)
external
returns (uint256 filledAmount, uint256 marginAward);
/// @notice Owner update of the oracle-valued auction award cap.
/// @dev Reverts above BPS, when set nonzero while auctions are disabled, or while an auction is live.
/// @param newMaxAuctionAwardBps New award cap per fundingAsset filled, in bps.
function setMaxAuctionAwardBps(uint256 newMaxAuctionAwardBps) external;
/// @notice Owner update of the fee charged on auction-awarded slashed margin, clamped to unawarded surplus.
/// @param newSlashFeeBps New fee in bps.
function setSlashFeeBps(uint256 newSlashFeeBps) external;
/// @notice Owner update of the trusted margin oracle.
/// @dev Rotation is owner-trusted and reprices subsequent deposits and auction fills, but not an opened call's
/// return-pool commitment. While paused, no fills can execute and the owner may rotate even a responsive current
/// oracle before resuming the frozen auction. While unpaused, the live-auction guard blocks rotation only while
/// the current oracle still returns a nonzero price for fills; a zero-price, reverting, or otherwise unreadable
/// current oracle never blocks rotation. The new oracle must return marginAsset-to-fundingAsset (USDC) prices at
/// ORACLE_PRICE_SCALE with matching decimals; the vault can only check that the price is nonzero.
/// @param newOracle New margin oracle.
function setMarginOracle(address newOracle) external;
/// @notice Auction state for an epoch.
/// @param epoch Epoch to query.
/// @return The auction state.
function getAuctionState(uint256 epoch) external view returns (LCCAuctionLib.AuctionState memory);
/// @notice Permissionlessly finalizes an epoch's slash once eligible (also runs lazily on any state touch).
/// @param epoch Epoch to finalize.
function finalizeEpochSlash(uint256 epoch) external;
/// @notice Advances a user's lazy materialization (folds pending/matured state, records defaults).
/// @param user Account to materialize.
function materializeAccount(address user) external;
/// @notice Materialized view of an account (read-only replay; not persisted).
/// @param user Account to query.
/// @return The materialized account.
function getAccount(address user) external view returns (Account memory);
/// @notice Stored epoch-call accounting for an epoch.
/// @param epoch Epoch to query.
/// @return The epoch state.
function getEpochState(uint256 epoch) external view returns (EpochState memory);
/// @notice Current obligation a user owes for an epoch's open call (0 if none, funded, or finalized).
/// @dev Ceil-rounded and computed independently per account from the call-open commitment snapshot; another
/// account funding does not reduce or extinguish this account's obligation, so the sum of obligations across
/// accounts can exceed `callAmount`.
/// @param epoch Epoch to query.
/// @param user Account to query.
/// @return The obligation (fundingAsset).
function obligationOf(uint256 epoch, address user) external view returns (uint256);
/// @notice Margin currently claimable from a matured exit (0 if not yet claimable).
/// @param user Account to query.
/// @return The claimable margin (marginAsset).
function claimableExitedMargin(address user) external view returns (uint256);
/// @notice The epochs in which a call has been opened, in order.
/// @return The list of called epochs.
function calledEpochs() external view returns (uint256[] memory);
/// @notice Immutable asset and integration address configuration.
/// @return The asset configuration.
function assetConfig() external view returns (AssetConfig memory);
/// @notice Immutable epoch timing and leverage configuration.
/// @return The epoch configuration.
function epochConfig() external view returns (EpochConfig memory);
/// @notice Immutable auction timing and decay configuration.
/// @return The auction configuration.
function auctionConfig() external view returns (AuctionConfig memory);
/// @notice Mutable risk limits.
/// @return The risk configuration.
function riskConfig() external view returns (RiskConfig memory);
/// @notice Aggregate margin and commitment totals.
/// @return The aggregate totals.
function totals() external view returns (Totals memory);
/// @notice Global sync cursors and live-auction slot.
/// @return The sync state.
function syncState() external view returns (SyncState memory);
/// @notice Emergency shutdown state.
/// @return The shutdown state.
function shutdownState() external view returns (ShutdownState memory);
/// @notice Whether `user` fully funded their obligation for `epoch`.
/// @param epoch Epoch to query.
/// @param user Account to query.
/// @return True if funded.
function fundedEpoch(uint256 epoch, address user) external view returns (bool);
/// @notice Pending margin scheduled to activate at an epoch (marginAsset).
/// @param epoch Activation epoch to query.
/// @return The pending margin for that epoch.
function pendingMarginByActivationEpoch(uint256 epoch) external view returns (uint256);
/// @notice Pending commitment scheduled to activate at an epoch (fundingAsset).
/// @param epoch Activation epoch to query.
/// @return The pending commitment for that epoch.
function pendingCommitmentByActivationEpoch(uint256 epoch) external view returns (uint256);
/// @notice Margin scheduled to exit at a maturity epoch (marginAsset).
/// @param epoch Maturity epoch to query.
/// @return The exit-bucket margin for that epoch.
function exitBucketMarginByMaturity(uint256 epoch) external view returns (uint256);
/// @notice Commitment scheduled to exit at a maturity epoch (fundingAsset).
/// @param epoch Maturity epoch to query.
/// @return The exit-bucket commitment for that epoch.
function exitBucketCommitmentByMaturity(uint256 epoch) external view returns (uint256);
}
src/lcc/interfaces/ILCCVaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.22 <0.9.0;
/// @title ILCCVaultFactory
/// @notice Minimal family authority and admission interface consumed by LCC vault implementations.
interface ILCCVaultFactory {
/// @dev The admissions module gates only new opens and reopens, never same-vault top-ups. A RegisteredElsewhere
/// result caused by incomplete bounded replay has the permissionless remedy `materializeAccount` on that vault.
/// @param postDepositCommitment The beneficiary's complete post-credit active-plus-pending commitment, computed
/// after account replay and after crediting the current deposit. Every vault implementation must report this full
/// value so pending exposure remains subject to the non-upgradeable factory cap.
function authorizeDeposit(address payer, address beneficiary, bool hadOpenExposure, uint256 postDepositCommitment)
external;
/// @dev Boolean-returning authority views are deliberate: ABI decoding is the fail-closed guard against malformed
/// captured factories and must not be replaced with void authorization calls.
function isOwner(address account) external view returns (bool);
function isGuardian(address account) external view returns (bool);
function isBouncer(address account) external view returns (bool);
/// @notice True for a vault this factory deployed and registered.
function isVault(address vault) external view returns (bool);
}
src/lcc/interfaces/IMorphoBlue.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.35;
/// @title IMorphoBlue
/// @notice Minimal interface of the canonical Morpho Blue singleton used by the LCC leveraged funding helper.
/// @dev This is the canonical Morpho Blue ABI, not the MorphoCredit fork in `src/interfaces/IMorpho.sol`, whose market
/// parameters and entrypoints are not ABI-compatible with the canonical singleton.
interface IMorphoBlue {
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
function supplyCollateral(MarketParams calldata marketParams, uint256 assets, address onBehalf, bytes calldata data)
external;
function borrow(
MarketParams calldata marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
function repay(
MarketParams calldata marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes calldata data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
function withdrawCollateral(MarketParams calldata marketParams, uint256 assets, address onBehalf, address receiver)
external;
function accrueInterest(MarketParams calldata marketParams) external;
function flashLoan(address token, uint256 assets, bytes calldata data) external;
function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
function isAuthorized(address authorizer, address authorized) external view returns (bool);
function position(bytes32 id, address user)
external
view
returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
function market(bytes32 id)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
}
/// @notice Callback Morpho Blue invokes on the `flashLoan` caller after transferring the loaned assets and before
/// pulling the same amount back without a fee.
interface IMorphoBlueFlashLoanCallback {
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}
src/lcc/libraries/LCCAuctionLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.22 <0.9.0;
import {Math} from "../../../lib/openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "../../../lib/openzeppelin/contracts/utils/math/SafeCast.sol";
import {ORACLE_PRICE_SCALE, BPS} from "../../libraries/ConstantsLib.sol";
import {IOracle} from "../../interfaces/IOracle.sol";
import {LCCErrorsLib} from "./LCCErrorsLib.sol";
/// @title LCCAuctionLib
/// @author 3Jane
/// @custom:contact [email protected]
/// @notice Pricing math and packed fill accounting for the LCC epoch-shortfall auction.
/// @dev The auction sells the right to fill an epoch's funding-asset shortfall (wrapped into USD3 for the buyer)
/// together with a collateral kicker from the slashed margin pool. The protocol's retained share of the award reserve
/// decays by `stepDecayRateBps` every `stepDuration` seconds, so the offered kicker ramps from zero toward the maximum
/// award that leaves the configured treasury take reserved.
/// The externally linked fill path accepts the caller's auction storage slot and records checked packed counters in
/// the same delegatecall that computes the award.
library LCCAuctionLib {
using SafeCast for uint256;
uint256 internal constant RAY = 1e27;
/// @dev One whole USDC in 6-decimal funding base units. Settlement treats smaller returned commitments as
/// unattributable dust; using a non-6-decimal funding asset requires revalidating this threshold.
uint256 internal constant MIN_RETURN_COMMITMENT = 1e6;
/// @notice State of an epoch's shortfall auction.
/// @param shortfallAmount Total shortfall to be filled (fundingAsset).
/// @param filledAmount Cumulative amount filled so far (fundingAsset).
/// @param marginPool Slashed margin backing the collateral kicker (marginAsset).
/// @param marginAwarded Cumulative collateral awarded to fillers (marginAsset).
struct AuctionState {
uint128 shortfallAmount;
uint128 filledAmount;
uint128 marginPool;
uint128 marginAwarded;
}
/// @notice Computes `x**n` in fixed-point with `base` scaling.
/// @dev Overflow-checked fixed-point exponentiation by squaring (the well-known MakerDAO/Ajna implementation).
/// @param x The base, scaled by `base`.
/// @param n The integer exponent.
/// @param base The fixed-point scaling factor (e.g. RAY).
/// @return z `x**n`, scaled by `base`.
function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 { z := base }
default { z := 0 }
}
default {
switch mod(n, 2)
case 0 { z := base }
default { z := x }
let half := div(base, 2)
for { n := div(n, 2) } n { n := div(n, 2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0, 0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0, 0) }
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0, 0) }
z := div(zxRound, base)
}
}
}
}
}
/// @notice Collateral offered to fillers at `elapsed` seconds into the auction window.
/// @dev offered = target * (1 - (1 - stepDecayRateBps/BPS)^(elapsed/stepDuration)): zero before the first step
/// completes, monotonically nondecreasing in elapsed, never exceeds `rampTarget`.
/// @param rampTarget Maximum collateral approached by the decay ramp (marginAsset).
/// @param elapsed Seconds since the auction window opened.
/// @param stepDuration Seconds per price step.
/// @param stepDecayRateBps Per-step decay of the protocol's retained share, in bps.
/// @return The collateral currently offered (marginAsset).
function offeredPool(uint256 rampTarget, uint256 elapsed, uint256 stepDuration, uint256 stepDecayRateBps)
public
pure
returns (uint256)
{
if (rampTarget == 0) return 0;
uint256 steps = elapsed / stepDuration;
if (steps == 0) return 0;
uint256 rayMultiplier = RAY - stepDecayRateBps * 1e23;
uint256 retained = rpow(rayMultiplier, steps, RAY);
return rampTarget - Math.mulDiv(rampTarget, retained, RAY);
}
/// @notice Collateral award for filling `fillAmount` of the shortfall while `offered` is on the table.
/// @dev Pro-rata of the current offer against the ORIGINAL shortfall, capped by the fill-time oracle value and
/// the unawarded reserve. Conservation: each award <= maxCumulativeAward * fill / shortfall, so total awards never
/// exceed the reserve because total fills never exceed the shortfall; the reserve clamp is belt-and-suspenders.
/// @param state The auction state.
/// @param fillAmount Amount of the shortfall being filled (fundingAsset).
/// @param offered Collateral currently offered (marginAsset), from `offeredPool`.
/// @param oracleCapMargin Oracle-valued award cap for this fill (marginAsset).
/// @param maxCumulativeAward Reserved upper bound on all auction awards (marginAsset).
/// @return award Collateral awarded for this fill (marginAsset).
function fillAward(
AuctionState memory state,
uint256 fillAmount,
uint256 offered,
uint256 oracleCapMargin,
uint256 maxCumulativeAward
) public pure returns (uint256 award) {
if (state.shortfallAmount == 0) return 0;
award = Math.mulDiv(offered, fillAmount, state.shortfallAmount);
if (award > oracleCapMargin) award = oracleCapMargin;
uint256 remainingPool = maxCumulativeAward - state.marginAwarded;
if (award > remainingPool) award = remainingPool;
}
/// @notice Full award computation for a fill: the ramped pro-rata kicker, capped by `maxAwardBps` of the fill
/// valued at `price` (the trusted margin-to-fundingAsset oracle price), clamped to the unawarded pool.
/// @param state The auction state.
/// @param fillAmount Amount of the shortfall being filled (fundingAsset).
/// @param elapsed Seconds since the auction window opened.
/// @param stepDuration Seconds per price step.
/// @param stepDecayRateBps Per-step decay of the protocol's retained share, in bps.
/// @param slashFeeBps Fee charged on the settlement take basis, in bps.
/// @param maxAwardBps Award cap per fundingAsset filled, in bps.
/// @param price Margin-to-fundingAsset oracle price, scaled by ORACLE_PRICE_SCALE.
/// @return Collateral awarded for this fill (marginAsset).
function computeAward(
AuctionState memory state,
uint256 fillAmount,
uint256 elapsed,
uint256 stepDuration,
uint256 stepDecayRateBps,
uint256 slashFeeBps,
uint256 maxAwardBps,
uint256 price
) public pure returns (uint256) {
if (state.shortfallAmount == 0) return 0;
uint256 oracleCapMargin = Math.mulDiv(Math.mulDiv(fillAmount, maxAwardBps, BPS), ORACLE_PRICE_SCALE, price);
uint256 maxCumulativeAward = Math.mulDiv(state.marginPool, BPS, BPS + slashFeeBps);
uint256 offered = offeredPool(maxCumulativeAward, elapsed, stepDuration, stepDecayRateBps);
uint256 award = fillAward(state, fillAmount, offered, oracleCapMargin, maxCumulativeAward);
return Math.min(award, _remainingEligibleAward(state, fillAmount, slashFeeBps));
}
/// @dev Completed settlement floors the gross pool's filled share before reserving its fee. Mirror that ordering
/// cumulatively so awards cannot exceed the filled share's post-reserve capacity, including at base-unit dust.
function _remainingEligibleAward(AuctionState memory state, uint256 fillAmount, uint256 slashFeeBps)
private
pure
returns (uint256)
{
uint256 eligiblePool =
Math.mulDiv(state.marginPool, uint256(state.filledAmount) + fillAmount, state.shortfallAmount);
uint256 eligibleAward = Math.mulDiv(eligiblePool, BPS, BPS + slashFeeBps);
return Math.saturatingSub(eligibleAward, state.marginAwarded);
}
/// @notice Computes an auction award and records the fill against packed auction storage.
/// @dev `fillAward` clamps only the award to the unawarded pool; the caller must clamp `fillAmount` to the
/// remaining shortfall (`shortfallAmount - filledAmount`) or `filledAmount` can exceed `shortfallAmount`,
/// breaking full-fill settlement. SafeCast keeps both packed counters checked at the storage boundary.
/// @param state The auction storage updated by the fill.
/// @param fillAmount Amount of the shortfall being filled (fundingAsset).
/// @param elapsed Seconds since the auction window opened.
/// @param stepDuration Seconds per price step.
/// @param stepDecayRateBps Per-step decay of the protocol's retained share, in bps.
/// @param slashFeeBps Fee charged on the settlement take basis, in bps.
/// @param maxAwardBps Award cap per fundingAsset filled, in bps.
/// @param price Margin-to-fundingAsset oracle price, scaled by ORACLE_PRICE_SCALE.
/// @return award Collateral awarded for this fill (marginAsset).
function applyFill(
AuctionState storage state,
uint256 fillAmount,
uint256 elapsed,
uint256 stepDuration,
uint256 stepDecayRateBps,
uint256 slashFeeBps,
uint256 maxAwardBps,
uint256 price
) public returns (uint256 award) {
award = computeAward(
state, fillAmount, elapsed, stepDuration, stepDecayRateBps, slashFeeBps, maxAwardBps, price
);
state.filledAmount = (uint256(state.filledAmount) + fillAmount).toUint128();
state.marginAwarded = (uint256(state.marginAwarded) + award).toUint128();
}
/// @notice Resolves the lifecycle phase at an effective timestamp.
/// @param timestamp Effective timestamp after excluding paused wall-clock time.
/// @param packedClock The vault's packed `LCCTypesLib.ClockConfig` word, passed by value.
/// @return The numeric value of the active `ILCCVault.Phase`.
function phaseAt(uint256 timestamp, uint256 packedClock) public pure returns (uint8) {
uint256 startTimestamp = uint64(packedClock);
uint256 epochLength = uint32(packedClock >> 128);
uint256 normalDuration = uint32(packedClock >> 160);
uint256 preCallDuration = uint32(packedClock >> 192);
uint256 fundingDuration = uint32(packedClock >> 224);
uint256 elapsed = timestamp >= startTimestamp ? (timestamp - startTimestamp) % epochLength : 0;
if (elapsed < normalDuration) return 0;
if (elapsed < normalDuration + preCallDuration) return 1;
if (elapsed < normalDuration + preCallDuration + fundingDuration) return 2;
return 3;
}
/// @notice Resolves an epoch phase's effective-time end boundary.
/// @param epoch Epoch whose boundary is requested.
/// @param phase Numeric value of the requested `ILCCVault.Phase`.
/// @param packedClock The vault's packed `LCCTypesLib.ClockConfig` word, passed by value.
/// @return effectiveEnd The phase end in effective time, before any live pause offset is restored.
function phaseEndsAt(uint256 epoch, uint8 phase, uint256 packedClock) public pure returns (uint256 effectiveEnd) {
uint256 startTimestamp = uint64(packedClock);
uint256 epochLength = uint32(packedClock >> 128);
uint256 normalDuration = uint32(packedClock >> 160);
uint256 preCallDuration = uint32(packedClock >> 192);
uint256 fundingDuration = uint32(packedClock >> 224);
uint256 start = startTimestamp + epoch * epochLength;
if (phase == 0) return start + normalDuration;
if (phase == 1) return start + normalDuration + preCallDuration;
if (phase == 2) return start + normalDuration + preCallDuration + fundingDuration;
return start + epochLength;
}
/// @notice Values margin assets in funding-asset units and derives their callable commitment.
/// @param assets Margin assets to value.
/// @param price Margin-to-fundingAsset oracle price, scaled by ORACLE_PRICE_SCALE.
/// @param marginRatioBps Margin ratio used to leverage margin value into commitment, in bps.
/// @return marginValue Value of the margin assets in fundingAsset units.
/// @return commitment Callable commitment derived from the margin value.
function valueAndCommitment(uint256 assets, uint256 price, uint256 marginRatioBps)
public
pure
returns (uint256 marginValue, uint256 commitment)
{
marginValue = Math.mulDiv(assets, price, ORACLE_PRICE_SCALE);
commitment = Math.mulDiv(marginValue, BPS, marginRatioBps);
}
/// @dev Matches the exact overflow predicate used by `Math.mulDiv` for both valuation stages.
function _valuationOverflows(uint256 assets, uint256 price, uint256 marginRatioBps) private pure returns (bool) {
(uint256 valueProductHigh,) = Math.mul512(assets, price);
if (ORACLE_PRICE_SCALE <= valueProductHigh) return true;
uint256 marginValue = Math.mulDiv(assets, price, ORACLE_PRICE_SCALE);
(uint256 commitmentProductHigh,) = Math.mul512(marginValue, BPS);
return marginRatioBps <= commitmentProductHigh;
}
/// @dev Return pool for a disposed epoch's unawarded surplus. Non-eligible and shutdown-truncated epochs
/// return every unawarded unit without a take. Eligible epochs receive completed-auction treatment: the
/// unfilled share of the gross pool (surplus plus awards) goes to treasury and the slash fee comes out of the
/// filled remainder.
function _settlementReturnPool(AuctionState storage auction, uint256 surplus, uint256 settlementConfig)
private
view
returns (uint256 disposalPool)
{
// Eligibility is an explicit flag, not inferred from the record: an untouched but eligible epoch has a
// zero auction record (zero fills) and must dispose as zero, not as a full no-take return.
if (settlementConfig & (1 << 32) == 0) return surplus;
if (auction.shortfallAmount == 0) return 0;
uint256 stepDecayRateBps = settlementConfig & type(uint16).max;
uint256 slashFeeBps = (settlementConfig >> 16) & type(uint16).max;
uint256 auctionedMargin = auction.marginAwarded;
uint256 feeBasis = auctionedMargin;
uint256 grossPool = surplus + auctionedMargin;
uint256 maxCumulativeAward = Math.mulDiv(grossPool, BPS, BPS + slashFeeBps);
// The fee basis is the greater of cumulative awards and the fills' pro-rata share of the first-step offer.
// `offered1` reconstructs that offer from `stepDecayRateBps`, repricing the curve the fills actually paid
// against; the reconstruction is sound only because `auctionStepDecayRateBps` has no setter.
uint256 offered1 = maxCumulativeAward - Math.mulDiv(maxCumulativeAward, BPS - stepDecayRateBps, BPS);
feeBasis = Math.max(feeBasis, Math.mulDiv(offered1, auction.filledAmount, auction.shortfallAmount));
disposalPool = Math.mulDiv(grossPool, auction.filledAmount, auction.shortfallAmount) - auctionedMargin;
// The surplus clamp is unreachable on valid fill state (the reserved ramp keeps awards within post-fee
// capacity); it bounds the fee independently of the ramp so a future award-ramp change cannot take more
// than the surplus being disposed.
uint256 fee = Math.min(Math.mulDiv(feeBasis, slashFeeBps, BPS), surplus);
disposalPool -= fee;
}
/// @notice Values a disposed slash surplus into a return pool and returned commitment.
/// @dev Pool: derived by `_settlementReturnPool` (eligibility and fee treatment documented there), then capped
/// by the uint128 headroom over the low half of `packedHeadroom` so packed aggregate margin stays in range.
/// Price: the call-open snapshot. A missing snapshot consults the live oracle only when the fallback permission
/// bit is set; with the price-failure tolerance bit set (shutdown/terminal), an unreadable or zero price drops
/// the pool to treasury instead of reverting, so recovery can never brick. Valuation overflow at the selected
/// price is treated as oracle corruption and likewise drops the pool (guard rationale in the body).
/// Commitment: derived from the pool at the selected price, clamped to the headroom high half, and zeroed below
/// `MIN_RETURN_COMMITMENT`. A zero commitment also zeroes the pool, so the returned pair is always attributable
/// to an account; a nonzero clamp never reduces the pool.
/// @param auction Recorded auction state; a zero shortfall means no auction record was opened.
/// @param surplus Unawarded slashed margin being disposed (marginAsset).
/// @param settlementConfig Packed step decay (bits 0..15), slash fee (bits 16..31), and auction-eligibility flag
/// (bit 32). An eligible disposal always receives completed-auction treatment.
/// @param marginPriceSnapshot Margin-oracle price frozen when the call opened.
/// @param marginOracle Live margin oracle used only for an authorized missing-snapshot recovery.
/// @param valuationConfig Packed margin ratio (bits 0..15), oracle-fallback permission (bit 16), and live
/// price-failure tolerance flag (bit 17).
/// @param packedHeadroom Active-plus-pending margin in bits 0..127 and return-commitment headroom in bits 128..255.
/// @return returnPool Margin re-attributed to defaulters (marginAsset).
/// @return returnCommitment Commitment re-attributed to defaulters (fundingAsset).
function disposeValuation(
AuctionState storage auction,
uint256 surplus,
uint256 settlementConfig,
uint256 marginPriceSnapshot,
address marginOracle,
uint256 valuationConfig,
uint256 packedHeadroom
) public view returns (uint256 returnPool, uint256 returnCommitment) {
returnPool = Math.min(
_settlementReturnPool(auction, surplus, settlementConfig),
Math.saturatingSub(type(uint128).max, packedHeadroom & type(uint128).max)
);
// The oracle is consulted only when there is a return pool to value.
if (returnPool != 0) {
uint256 price = marginPriceSnapshot;
bool toleratePriceFailure = valuationConfig & (1 << 17) != 0;
if (price == 0 && valuationConfig & (1 << 16) != 0) {
if (toleratePriceFailure) {
try IOracle(marginOracle).price() returns (uint256 p) {
price = p;
} catch {}
} else {
price = IOracle(marginOracle).price();
}
}
if (!toleratePriceFailure && price == 0) revert LCCErrorsLib.OraclePriceInvalid();
// Oracle-corruption guard. It must run after snapshot/fallback selection and before valuation: call
// opening validated only `price != 0` and never proved the price could value `marginAtCallOpen`, so
// this is the only check that the selected price can value this pool. For an honest oracle it is
// unreachable — a full-uint128 pool overflows only near price 3.4e70 at the minimum margin ratio,
// ~34 orders of magnitude above an ORACLE_PRICE_SCALE-scaled price — which is why it reads as dead
// code but is not. On corrupt state, zeroing the price trades a permanent settlement brick for
// confiscation of the pool via the `price == 0` sweep below.
uint256 marginRatioBps = valuationConfig & type(uint16).max;
if (_valuationOverflows(returnPool, price, marginRatioBps)) price = 0;
if (price == 0) {
returnPool = 0;
} else {
(, uint256 rawCommitment) = valueAndCommitment(returnPool, price, marginRatioBps);
returnCommitment = Math.min(rawCommitment, packedHeadroom >> 128);
if (returnCommitment < MIN_RETURN_COMMITMENT) returnCommitment = 0;
if (returnCommitment == 0) returnPool = 0;
}
}
if (returnPool == 0) returnCommitment = 0;
}
}
src/lcc/libraries/LCCErrorsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.22 <0.9.0;
/// @title LCCErrorsLib
/// @author 3Jane
/// @custom:contact [email protected]
/// @notice Library exposing LCC vault errors.
library LCCErrorsLib {
/// @notice Thrown when a required address argument is the zero address.
error ZeroAddress();
/// @notice Thrown when an input parameter is outside its valid range.
error InvalidParams();
/// @notice Thrown when a wall-clock transaction deadline has expired.
error DeadlineExpired();
/// @notice Thrown when an action is attempted that is blocked by emergency shutdown.
error ShutdownActive();
/// @notice Thrown when a state-transitioning action is attempted while the vault is paused.
error Paused();
/// @notice Thrown when pausing a vault that is already paused.
error AlreadyPaused();
/// @notice Thrown when unpausing a vault that is not paused.
error NotPaused();
/// @notice Thrown when a caller is not authorized for the action.
error Unauthorized();
/// @notice Thrown when a third-party deposit payer lacks the factory deposit-operator role.
error UnauthorizedDepositOperator(address payer);
/// @notice Thrown when the optional admissions module rejects a deposit.
error AdmissionsModuleRejected(address user, address vault);
/// @notice Thrown when the sole factory owner attempts to renounce its role.
error CannotRenounceOwnerRole();
/// @notice Thrown when a deposit authorization caller is not a factory-registered vault.
error NotVault();
/// @notice Thrown when a depositor still has exposure in another family vault.
error RegisteredElsewhere(address vault);
/// @notice Thrown when a new call, deposit, or exit request is attempted after scheduled sunset, or would only
/// take effect at or after scheduled sunset.
error VaultTerminal();
/// @notice Thrown when an exit request would create more tracked maturity buckets than the vault supports.
error ExitCapacityReached();
/// @notice Thrown when an exit cannot be assigned within the caller's maximum accepted deferral.
error ExitDeferralExceeded();
/// @notice Thrown when depositing while the account has a pending or unclaimed exit.
error ExitInProgress();
/// @notice Thrown when a deposit would exceed the protocol-wide or per-account commitment cap.
error CapExceeded();
/// @notice Thrown when an action is attempted in the wrong lifecycle phase.
error InvalidPhase();
/// @notice Thrown when the supplied epoch is not the current epoch, or the call is closed/finalized.
error InvalidEpoch();
/// @notice Thrown when opening a call for an epoch that already has one.
error CallAlreadyOpened();
/// @notice Thrown when opening a call while an earlier call remains unsettled.
error PriorCallUnsettled();
/// @notice Thrown when an amount argument is zero or otherwise invalid for the operation.
error InvalidAmount();
/// @notice Thrown when the margin oracle returns a zero (unusable) price.
error OraclePriceInvalid();
/// @notice Thrown when funding an obligation that the user has already funded this epoch.
error AlreadyFunded();
/// @notice Thrown when minting one USD3 share would require more than the permitted funding top-up.
error FundingTopUpExcessive();
/// @notice Thrown when USD3 cannot mint any shares because it reports zero assets with supply outstanding.
error FundingDeliveryImpossible();
/// @notice Thrown when there is nothing to claim for the caller.
error NothingToClaim();
/// @notice Thrown when claiming an exit that was never requested (or already claimed).
error NoExitRequested();
/// @notice Thrown when claiming an exit before its maturity epoch.
error ExitNotMature();
/// @notice Thrown when requesting an exit before the minimum commitment period has elapsed.
error CommitmentNotMature();
/// @notice Thrown when finalizing a slash for an epoch that is not yet slash-eligible.
error SlashNotEligible();
/// @notice Thrown when a wind-down withdrawal is attempted before shutdown or terminal sunset.
error NotWithdrawable();
/// @notice Thrown when taking an auction that is not currently live.
error AuctionNotLive();
/// @notice Thrown when an auction fill awards less margin than the caller requires.
error InsufficientMarginAward();
/// @notice Thrown when requesting an exit while the account still holds a pending (not-yet-active) deposit.
error PendingDepositExists();
/// @notice Thrown when an account cannot be fully materialized within the per-call step bound.
error AccountMaterializationIncomplete();
}
src/libraries/ConstantsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @dev The maximum fee a market can have (25%).
uint256 constant MAX_FEE = 0.25e18;
/// @dev Oracle price scale.
uint256 constant ORACLE_PRICE_SCALE = 1e36;
/// @dev Basis points denominator (100%).
uint256 constant BPS = 10_000;
/// @dev Liquidation cursor.
uint256 constant LIQUIDATION_CURSOR = 0.3e18;
/// @dev Max liquidation incentive factor.
uint256 constant MAX_LIQUIDATION_INCENTIVE_FACTOR = 1.15e18;
/// @dev The EIP-712 typeHash for EIP712Domain.
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
/// @dev The EIP-712 typeHash for Authorization.
bytes32 constant AUTHORIZATION_TYPEHASH =
keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");
src/libraries/MathLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
uint256 constant WAD = 1e18;
/// @title MathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
/// @dev Returns (`x` * `y`) / `WAD` rounded down.
function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD);
}
/// @dev Returns (`x` * `WAD`) / `y` rounded down.
function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y);
}
/// @dev Returns (`x` * `WAD`) / `y` rounded up.
function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y);
}
/// @dev Returns (`x` * `y`) / `d` rounded down.
function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
return (x * y) / d;
}
/// @dev Returns (`x` * `y`) / `d` rounded up.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
return (x * y + (d - 1)) / d;
}
/// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
/// continuous compound interest rate.
function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
uint256 firstTerm = x * n;
uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);
return firstTerm + secondTerm + thirdTerm;
}
/// @dev Computes the inverse of wTaylorCompounded, finding the rate that produces the given growth factor.
/// Uses a 3-term Taylor series approximation of ln(x) to solve for rate in the compound interest formula.
/// Formula: rate = ln(x) / n ≈ [(x-1) - (x-1)²/2 + (x-1)³/3] / n
///
/// Accuracy notes:
/// - The Taylor approximation of ln(x) is most accurate for x close to 1
/// - At growth factor x = 1.69*WAD (69% growth), approximation error < 2%
/// - At growth factor x = 2*WAD (100% growth, where ln(2) ≈ 0.69), approximation error < 5%
/// - Accuracy decreases for larger growth factors; not recommended for x > 2.5*WAD (150% growth)
///
/// Example: If debt grew from 1000 to 1105 over 1 year (10.5% growth):
/// - x = 1.105*WAD (growth factor)
/// - n = 365 days (time period)
/// - Returns ~10% APR as rate per second
///
/// @param x The growth factor scaled by WAD (e.g., 1.1*WAD for 10% growth). Must be >= WAD.
/// @param n The time period over which the growth occurred (in seconds)
/// @return The continuously compounded rate per second that would produce this growth (scaled by WAD)
function wInverseTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
require(x >= WAD, "ln undefined");
uint256 firstTerm = x - WAD;
uint256 secondTerm = wMulDown(firstTerm, firstTerm);
uint256 thirdTerm = wMulDown(secondTerm, firstTerm);
uint256 series = firstTerm - secondTerm / 2 + thirdTerm / 3;
return series / n;
}
}
src/libraries/SharesMathLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {MathLib} from "./MathLib.sol";
/// @title SharesMathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
using MathLib for uint256;
/// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
/// high precision computations.
/// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
/// stays low enough not to inflate these assets to a significant value.
/// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
uint256 internal constant VIRTUAL_SHARES = 1e6;
/// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
/// empty.
uint256 internal constant VIRTUAL_ASSETS = 1;
/// @dev Calculates the value of `assets` quoted in shares, rounding down.
function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding down.
function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
/// @dev Calculates the value of `assets` quoted in shares, rounding up.
function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding up.
function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 150,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
"@tokenized-strategy/=lib/tokenized-strategy/src/",
"@periphery/=lib/tokenized-strategy-periphery/src/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/lib/openzeppelin-contracts/",
"lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/tokenized-strategy/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/createx-forge/lib/forge-std/:ds-test/=lib/createx-forge/lib/forge-std/lib/ds-test/src/",
"lib/createx-forge/lib/forge-std/:ds-test/=lib/createx-forge/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/forge-std/:ds-test/=lib/tokenized-strategy-periphery/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:erc4626-tests/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:tokenized-strategy/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/",
"lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/:tokenized-strategy/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/lib/tokenized-strategy/",
"lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy/lib/forge-std/:ds-test/=lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/tokenized-strategy/lib/openzeppelin-contracts/:erc4626-tests/=lib/tokenized-strategy/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/forge-std/:ds-test/=lib/forge-std/lib/ds-test/src/",
"lib/forge-std/:ds-test/=lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin/:erc4626-tests/=lib/openzeppelin/lib/erc4626-tests/",
"lib/openzeppelin/:erc4626-tests/=lib/openzeppelin/lib/erc4626-tests/",
"lib/tokenized-strategy-periphery/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/:openzeppelin-contracts/=lib/tokenized-strategy-periphery/lib/openzeppelin-contracts/",
"lib/tokenized-strategy-periphery/:tokenized-strategy/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/",
"lib/tokenized-strategy-periphery/:tokenized-strategy/=lib/tokenized-strategy-periphery/lib/tokenized-strategy/",
"lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy/:erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
"lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy/lib/openzeppelin-contracts/",
"lib/tokenized-strategy/:openzeppelin-contracts/=lib/tokenized-strategy/lib/openzeppelin-contracts/",
"@openzeppelin/=lib/tokenized-strategy/lib/openzeppelin-contracts/",
"@yearn-vaults/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/contracts/",
"createx-forge/=lib/createx-forge/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin/lib/erc4626-tests/",
"openzeppelin-contracts/=lib/tokenized-strategy/lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin/",
"tokenized-strategy-periphery/=lib/tokenized-strategy-periphery/",
"tokenized-strategy/=lib/tokenized-strategy/",
"yearn-vaults-v3/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.