Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/DualBot.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {IERC20} from "../lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import {IERC20Metadata} from "../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC4626} from "../lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
import {SafeERC20} from "../lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import "../lib/openzeppelin-contracts/contracts/access/AccessControl.sol";
import {IOracle} from "../lib/morpho-blue/src/interfaces/IOracle.sol";
import {IMorpho, Market, Position, MarketParams, Id} from "../lib/morpho-blue/src/interfaces/IMorpho.sol";
import {IMorphoFlashLoanCallback, IMorphoSupplyCollateralCallback} from "../lib/morpho-blue/src/interfaces/IMorphoCallbacks.sol";
import {MathLib} from "../lib/morpho-blue/src/libraries/MathLib.sol";
import {MorphoBalancesLib} from "../lib/morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol";
import {IChainlinkOracle} from "../src/interfaces/IChainlinkOracle.sol";
import {ISwapper} from "../src/interfaces/ISwapper.sol";
import {IMorphoReader, MarketDataExt, PositionExt} from "../src/interfaces/IMorphoReader.sol";
import {IWsteth} from "../src/interfaces/IWsteth.sol";
/**
* @title Bot that leverage borrows cash (of type currency) against assets (of type collateral)
*/
contract DualBot is
AccessControl,
IMorphoFlashLoanCallback,
IMorphoSupplyCollateralCallback
{
using SafeERC20 for IERC20;
event Wind(uint256 equity, uint256 exposure, uint256 toBorrow);
event Unwind(
uint256 borrowShares,
uint256 borrowAmount,
uint256 collateral
);
// Create a new role identifier for the minter role
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant CALLBACK_ROLE = keccak256("CALLBACK_ROLE");
IERC20 public immutable currency;
IERC20 public immutable collateral;
IOracle public immutable oracle;
IMorpho public immutable morpho =
IMorpho(0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb);
IMorphoReader public immutable morphoReader;
ISwapper public swapper;
Id[] public markets;
mapping(Id => bool) internal marketsMap;
uint256 internal immutable WEI_FACTOR = 10 ** 18;
/// @notice Max allowed slippage in bps
uint256 public maxSlippage = 5; // in bps
uint256 internal constant SLIPPAGE_FACTOR = 10000; // in bps so 100%
uint256 internal minExpected = 0 ether; // MEV protection where sender can say how much min after swaps
uint256 internal constant DUST = 10 ** 12;
bytes internal constant NULL_DATA = "";
uint256 internal immutable ORACLE_FACTOR = 10 ** 36;
bool internal constant WIND = true;
bool internal constant UNWIND = false;
MarketParams public marketParams;
constructor(
address owner,
IERC20 currency_,
IERC20 collateral_,
IOracle oracle_,
ISwapper swapper_,
IMorphoReader reader_
) {
currency = currency_;
collateral = collateral_;
oracle = oracle_;
swapper = swapper_;
morphoReader = reader_;
_grantRole(DEFAULT_ADMIN_ROLE, owner);
_grantRole(OPERATOR_ROLE, msg.sender);
// Only Morpho and DssFlashLoan can call the callback
_grantRole(CALLBACK_ROLE, address(morpho));
// Grant admin to change permissions
_setRoleAdmin(OPERATOR_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(CALLBACK_ROLE, DEFAULT_ADMIN_ROLE);
}
/// @notice Updates the swapper contract used for token swaps
/// @param _swapper The new swapper contract address
function setSwapper(ISwapper _swapper) external onlyRole(DEFAULT_ADMIN_ROLE) {
swapper = _swapper;
}
/// @notice Borrow cash currency, swap in collateral in market id and use it as collateral
/// @param marketId Market Id to use
/// @param cash currency amount to be borrowed
function wind(Id marketId, uint256 cash) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
morpho.flashLoan(address(currency), cash, abi.encode(marketId, WIND));
}
/// @notice remove collateral on market id, swap to currency, repay the loan
/// @param marketId Market Id to use
/// @param assets Amount of collateral to sell to repay the loan
function unwind(
Id marketId,
uint256 assets
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
morpho.flashLoan(
address(collateral),
assets,
abi.encode(marketId, UNWIND)
);
}
/// @notice Borrow cash currency, swap in collateral in market id and use it as collateral
/// @param marketId Market Id to use
/// @param cash currency amount to be borrowed
/// @param minAssets_ Revert if we don't get at least minAssets_ collateral from the sale
function wind(
Id marketId,
uint256 cash,
uint256 minAssets_
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
minExpected = minAssets_; // Revert if we don't get at least minCollateral_
morpho.flashLoan(address(currency), cash, abi.encode(marketId, WIND));
minExpected = 0;
}
/// @notice remove collateral on market id, swap to currency, repay the loan
/// @param marketId Market Id to use
/// @param minCash_ Revert if we don't get at least minCash_ currency from the sale
function unwind(
Id marketId,
uint256 assets,
uint256 minCash_
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
minExpected = minCash_; // Revert if we don't get at least minAssets_
morpho.flashLoan(
address(collateral),
assets,
abi.encode(marketId, UNWIND)
);
minExpected = 0;
}
/// @notice Moves collateral from marketFrom to marketTo
/// @param marketFrom From which market
/// @param marketTo To which market
/// @param assets Amount of collateral to move
function shiftCollateral(
Id marketFrom,
Id marketTo,
uint256 assets
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketFrom);
_checkMarket(marketTo);
_withdrawCollateral(marketFrom, assets);
_supplyCollateral(marketTo, assets);
}
/// @notice Borrow cash on marketFrom to repay a loan on marketTo
/// @param marketFrom From which market
/// @param marketTo To which market
/// @param cash Amount of currency to move (will be borrowed)
function shiftCurrency(
Id marketFrom,
Id marketTo,
uint256 cash
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketFrom);
_checkMarket(marketTo);
_borrow(marketFrom, cash);
_repay(marketTo, cash);
}
/// @notice Moves collateral from marketFrom to marketTo, borrow cash from marketTo to repay marketFrom
function shiftPosition(
Id marketFrom,
Id marketTo,
uint256 assets,
uint256 cash
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketFrom);
_checkMarket(marketTo);
morpho.supplyCollateral(
morpho.idToMarketParams(marketTo),
assets,
address(this),
abi.encode(marketFrom, marketTo, cash)
);
}
function onMorphoFlashLoan(
uint256 amount,
bytes calldata data
) external onlyRole(CALLBACK_ROLE) {
(Id marketId, bool doWind) = abi.decode(data, (Id, bool));
if (doWind) {
// Floashloaned currency
uint256 collateralAmount = _swapToCollateral(amount);
_supplyCollateral(marketId, collateralAmount);
_borrow(marketId, amount);
currency.forceApprove(address(morpho), amount);
} else {
// Unwind, we flashloaded collateral
uint256 cash = _swapToCurrency(amount);
_repayCurrencyFallbackShares(marketId, cash);
_withdrawCollateral(marketId, amount);
collateral.forceApprove(address(morpho), amount);
}
}
/// @notice Callback called when we shift a position
function onMorphoSupplyCollateral(
uint256 assets,
bytes calldata data
) external onlyRole(CALLBACK_ROLE) {
(Id marketFrom, Id marketTo, uint256 cash) = abi.decode(
data,
(Id, Id, uint256)
);
_borrow(marketTo, cash);
_repay(marketFrom, cash);
_withdrawCollateral(marketFrom, assets);
collateral.forceApprove(address(morpho), assets);
}
/// @notice change the max slippage allowed with 1 ether = 100% sippage
function setMaxSlippage(
uint256 maxSlippage_
) external onlyRole(OPERATOR_ROLE) {
require(maxSlippage_ <= 5, "Max slippage should be at max 0.05%");
maxSlippage = maxSlippage_;
}
/// @notice change the max slippage allowed with 1 ether = 100% sippage
function setMaxSlippageForce(
uint256 maxSlippage_
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(maxSlippage_ <= 10000, "Max slippage should be at max 100%");
maxSlippage = maxSlippage_;
}
function addMarket(Id marketId) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(marketsMap[marketId] == false, "Market already added");
markets.push(marketId);
marketsMap[marketId] = true;
}
function deleteMarket(Id marketId) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(marketsMap[marketId] == true, "Market isn't added yet");
uint i = 0;
for (; Id.unwrap(markets[i]) != Id.unwrap(marketId); i++) {}
markets[i] = markets[markets.length - 1];
markets.pop();
delete marketsMap[marketId];
}
////////////////////////////////
// VIEW FUNCTIONS
////////////////////////////////
/// @notice Returns the equity (collateral - debt) for a market
function equity() public view returns (uint256) {
uint256 _equity = 0;
for (uint i = 0; i < markets.length; i++) {
_equity += equity(markets[i]);
}
return _equity;
}
/// @notice Returns the equity (collateral - debt) for a market
function equityAsCollateral() public view returns (uint256) {
uint256 _equity = 0;
for (uint i = 0; i < markets.length; i++) {
_equity += equity(markets[i]);
}
return (_equity * ORACLE_FACTOR) / oracle.price();
}
/// @notice Returns the equity (collateral - debt) for a market
function equity(Id marketId) public view returns (uint256) {
PositionExt memory p = morphoReader.getPosition(
marketId,
address(this)
);
return p.collateralValue - p.borrowedAssets;
}
/// @notice Returns the equity expressed in collateral units
function equityAsCollateral(Id marketId) public view returns (uint256) {
return (equity(marketId) * ORACLE_FACTOR) / oracle.price();
}
/// @notice Returns the amount of collateral to be sale to repay a loan
/// include the worth case allowed slippage
function collateralNeeded(uint256 cash) public view returns (uint256) {
return
(cash * ORACLE_FACTOR * SLIPPAGE_FACTOR) /
(oracle.price() * (SLIPPAGE_FACTOR - maxSlippage));
}
/// @notice returen the price of cash collateral in the currency
function priceCollateralInCurrency(
uint256 assets
) public view returns (uint256 cash) {
return (assets * oracle.price()) / ORACLE_FACTOR;
}
/// @notice Returns the minimal collateral expected from the swap of cash currency
function minCollateral(uint256 cash) public view returns (uint256) {
return
(minExpected > 0)
? minExpected
: (cash * ORACLE_FACTOR * (SLIPPAGE_FACTOR - maxSlippage)) /
(oracle.price() * SLIPPAGE_FACTOR);
}
/// @notice Returns the minimal cash expected from the swap of collateral
function minCurrency(uint256 assets) public view returns (uint256) {
return
(minExpected > 0)
? minExpected
: (assets * oracle.price() * (SLIPPAGE_FACTOR - maxSlippage)) /
(ORACLE_FACTOR * SLIPPAGE_FACTOR);
}
function isUnwinded(Id marketId) public view returns (bool) {
Position memory position = morpho.position(marketId, address(this));
return position.borrowShares == 0;
}
function sharesBorrowed(Id marketId) public view returns (uint256) {
Position memory position = morpho.position(marketId, address(this));
return position.borrowShares;
}
/// @notice Returns the available market liquidity
function availableLiqudidity(Id marketId) public view returns (uint256) {
MarketDataExt memory m = morphoReader.getMarketData(marketId);
return m.totalSupplyAssets - m.totalBorrowAssets;
}
/// @notice Returns how much would be winded
function availableToBorrow(Id marketId) public view returns (uint256) {
uint256 _liquidity = availableLiqudidity(marketId);
PositionExt memory p = morphoReader.getPosition(
marketId,
address(this)
);
// We assume we can borrow up to 95% LTV
MarketParams memory params = morpho.idToMarketParams(marketId);
uint256 _equity = p.collateralValue - p.borrowedAssets;
uint256 maxExposure = _equity +
((_equity * (1 ether)) / (1 ether - params.lltv));
if (maxExposure < p.borrowedAssets) return 0;
return _min(_liquidity, maxExposure - p.borrowedAssets);
}
///////////////////////////////////////////
// EXPOSE LOW LEVEL FUNCTIONS
///////////////////////////////////////////
function borrow(
Id marketId,
uint256 cash
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
_borrow(marketId, cash);
}
function repay(Id marketId, uint256 cash) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
_repay(marketId, cash);
}
function repayShares(
Id marketId,
uint256 shares
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
_repayShares(marketId, shares);
}
function supplyCollateral(
Id marketId,
uint256 assets
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
if (assets == 0) assets = collateral.balanceOf(address(this));
_supplyCollateral(marketId, assets);
}
function withdrawCollateral(
Id marketId,
uint256 assets
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
_withdrawCollateral(marketId, assets);
}
function withdrawAllCollateral(
Id marketId
) external onlyRole(OPERATOR_ROLE) {
// Check that the market is already added
_checkMarket(marketId);
Position memory pos = morpho.position(marketId, address(this));
_withdrawCollateral(marketId, pos.collateral);
}
/// @notice Allows a slippage-checked swap from wstETH to WETH
/// @param assets Collateral to swap, if 0 use balance of wstETH in the contract
function swapToCurrency(uint256 assets) external onlyRole(OPERATOR_ROLE) {
if (assets == 0) assets = collateral.balanceOf(address(this));
_swapToCurrency(assets);
}
/// @notice Allows a slippage-checked from currency to collateral
/// @param cash Amount of currency to swap, if 0 use balance of currency in the contract
function swapToCollateral(uint256 cash) external onlyRole(OPERATOR_ROLE) {
if (cash == 0) cash = currency.balanceOf(address(this));
_swapToCollateral(cash);
}
///////////////////////////////////////////
// LOW LEVEL FUNCTIONS
///////////////////////////////////////////
function _checkMarket(Id marketId) internal view {
require(marketsMap[marketId] == true, "Market is not allowed");
}
/// @param cash Amount of currency to borrow
function _borrow(Id marketId, uint256 cash) internal {
morpho.borrow(
morpho.idToMarketParams(marketId),
cash,
0,
address(this),
address(this)
);
}
/// @param cash Amount of currency to repay
function _repay(Id marketId, uint256 cash) internal {
currency.forceApprove(address(morpho), cash);
morpho.repay(
morpho.idToMarketParams(marketId),
cash,
0,
address(this),
NULL_DATA
);
}
/// @param shares 18 decimals
function _repayShares(Id marketId, uint256 shares) internal {
currency.forceApprove(address(morpho), type(uint256).max);
morpho.repay(
morpho.idToMarketParams(marketId),
0,
shares,
address(this),
NULL_DATA
);
currency.forceApprove(address(morpho), 0);
}
/// @notice will repay amount as asset of it doesn't work will repay all the borrow shares
/// @param cash 18 decimals
function _repayCurrencyFallbackShares(Id marketId, uint256 cash) internal {
MarketParams memory currentMarketParams = morpho.idToMarketParams(marketId);
currency.forceApprove(address(morpho), cash);
try
morpho.repay(currentMarketParams, cash, 0, address(this), NULL_DATA)
returns (uint256, uint256) {} catch {
Position memory p = morpho.position(marketId, address(this));
if (p.borrowShares > 0)
morpho.repay(
currentMarketParams,
0,
p.borrowShares,
address(this),
NULL_DATA
);
// If there is some remain we put it back as collateral
uint256 dust = currency.balanceOf(address(this));
minExpected = 0; // Disable expectation and fallback on maxSlippage
uint256 dustCollateral = _swapToCollateral(dust);
_supplyCollateral(marketId, dustCollateral);
}
}
/// @param marketId market to use
/// @param assets in collateral term
function _supplyCollateral(Id marketId, uint256 assets) internal {
collateral.forceApprove(address(morpho), assets);
morpho.supplyCollateral(
morpho.idToMarketParams(marketId),
assets,
address(this),
NULL_DATA
);
}
/// @param marketId market to use
/// @param assets in collateral term
function _withdrawCollateral(Id marketId, uint256 assets) internal {
morpho.withdrawCollateral(
morpho.idToMarketParams(marketId),
assets,
address(this),
address(this)
);
}
/// @notice Swap assets collateral in the contract for currency. Check for slippage.
/// @param assets Quantity of collateral to sell
/// @return cash Quantity of currency obtained
function _swapToCurrency(uint256 assets) internal returns (uint256 cash) {
collateral.forceApprove(address(swapper), assets);
cash = swapper.sell(collateral, currency, assets);
require(
cash > minCurrency(assets),
"Less assets generated than expected"
);
return cash;
}
/// @notice Swap the WETH in the contract to wstETH. Check for slippage.
function _swapToCollateral(uint256 cash) internal returns (uint256 assets) {
currency.forceApprove(address(swapper), cash);
assets = swapper.sell(currency, collateral, cash);
require(
assets > minCollateral(cash),
"Less collateral generated than expected"
);
return assets;
}
function _max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function _min(uint256 a, uint256 b) internal pure returns (uint256) {
return a <= b ? a : b;
}
///////////////////////////////////////////
// RECOVER AND UNSTUCK FUNCTION
///////////////////////////////////////////
function recoverLost(
IERC20 token,
address where,
uint256 amount
) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.safeTransfer(where, amount);
}
function recover(
IERC20 token,
address where
) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.safeTransfer(where, token.balanceOf(address(this)));
}
function recoverETH() external payable onlyRole(DEFAULT_ADMIN_ROLE) {
(bool os, ) = payable(msg.sender).call{value: address(this).balance}(
""
);
require(os);
}
function approve(
IERC20 token,
address where,
uint256 amount
) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.forceApprove(where, amount);
}
}
"
},
"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol": {
"content": "// 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/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC20 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/contracts/interfaces/IERC4626.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC4626 "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 redeemption 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/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 {
using Address for address;
/**
* @dev An operation with an ERC20 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 Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
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.
*/
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.
*/
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 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).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
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 silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
"
},
"lib/openzeppelin-contracts/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"lib/morpho-blue/src/interfaces/IOracle.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title IOracle
/// @author Morpho Labs
/// @custom:contact security@morpho.org
/// @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);
}
"
},
"lib/morpho-blue/src/interfaces/IMorpho.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
type Id is bytes32;
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
uint256 supplyShares;
uint128 borrowShares;
uint128 collateral;
}
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
uint128 totalSupplyAssets;
uint128 totalSupplyShares;
uint128 totalBorrowAssets;
uint128 totalBorrowShares;
uint128 lastUpdate;
uint128 fee;
}
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
/// @notice The EIP-712 domain separator.
/// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on another chain sharing
/// the same chain id because the domain separator would be the same.
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice The owner of the contract.
/// @dev It has the power to change the owner.
/// @dev It has the power to set fees on markets and set the fee recipient.
/// @dev It has the power to enable but not disable IRMs and LLTVs.
function owner() external view returns (address);
/// @notice The fee recipient of all markets.
/// @dev The recipient receives the fees of a given market through a supply position on that market.
function feeRecipient() external view returns (address);
/// @notice Whether the `irm` is enabled.
function isIrmEnabled(address irm) external view returns (bool);
/// @notice Whether the `lltv` is enabled.
function isLltvEnabled(uint256 lltv) external view returns (bool);
/// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
/// @dev Anyone is authorized to modify their own positions, regardless of this variable.
function isAuthorized(address authorizer, address authorized) external view returns (bool);
/// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
function nonce(address authorizer) external view returns (uint256);
/// @notice Sets `newOwner` as `owner` of the contract.
/// @dev Warning: No two-step transfer ownership.
/// @dev Warning: The owner can be set to the zero address.
function setOwner(address newOwner) external;
/// @notice Enables `irm` as a possible IRM for market creation.
/// @dev Warning: It is not possible to disable an IRM.
function enableIrm(address irm) external;
/// @notice Enables `lltv` as a possible LLTV for market creation.
/// @dev Warning: It is not possible to disable a LLTV.
function enableLltv(uint256 lltv) external;
/// @notice Sets the `newFee` for the given market `marketParams`.
/// @param newFee The new fee, scaled by WAD.
/// @dev Warning: The recipient can be the zero address.
function setFee(MarketParams memory marketParams, uint256 newFee) external;
/// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
/// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
/// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
/// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Creates the market `marketParams`.
/// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
/// Morpho behaves as expected:
/// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
/// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
/// burn functions are not supported.
/// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
/// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
/// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
/// - The IRM should not re-enter Morpho.
/// - The oracle should return a price with the correct scaling.
/// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties
/// (funds could get stuck):
/// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
/// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
/// `toSharesDown` overflow.
/// - The IRM can revert on `borrowRate`.
/// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
/// overflow.
/// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
/// `liquidate` from being used under certain market conditions.
/// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
/// the computation of `assetsRepaid` in `liquidate` overflow.
/// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
/// the point where `totalBorrowShares` is very large and borrowing overflows.
function createMarket(MarketParams memory marketParams) external;
/// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupply` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
/// amount of shares is given for full compatibility and precision.
/// @dev Supplying a large amount can revert for overflow.
/// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to supply assets to.
/// @param assets The amount of assets to supply.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased supply position.
/// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
/// @return assetsSupplied The amount of assets supplied.
/// @return sharesSupplied The amount of shares minted.
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
/// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
/// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
/// conversion roundings between shares and assets.
/// @param marketParams The market to withdraw assets from.
/// @param assets The amount of assets to withdraw.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the supply position.
/// @param receiver The address that will receive the withdrawn assets.
/// @return assetsWithdrawn The amount of assets withdrawn.
/// @return sharesWithdrawn The amount of shares burned.
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
/// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
/// given for full compatibility and precision.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Borrowing a large amount can revert for overflow.
/// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to borrow assets from.
/// @param assets The amount of assets to borrow.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased borrow position.
/// @param receiver The address that will receive the borrowed assets.
/// @return assetsBorrowed The amount of assets borrowed.
/// @return sharesBorrowed The amount of shares minted.
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
/// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoReplay` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
/// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
/// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
/// roundings between shares and assets.
/// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
/// @param marketParams The market to repay assets to.
/// @param assets The amount of assets to repay.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the debt position.
/// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
/// @return assetsRepaid The amount of assets repaid.
/// @return sharesRepaid The amount of shares burned.
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
/// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupplyCollateral` function with the given `data`.
/// @dev Interest are not accrued since it's not required and it saves gas.
/// @dev Supplying a large amount can revert for overflow.
/// @param marketParams The market to supply collateral to.
/// @param assets The amount of collateral to supply.
/// @param onBehalf The address that will own the increased collateral position.
/// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
external;
/// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
/// @param marketParams The market to withdraw collateral from.
/// @param assets The amount of collateral to withdraw.
/// @param onBehalf The address of the owner of the collateral position.
/// @param receiver The address that will receive the collateral assets.
function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
external;
/// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
/// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
/// `onMorphoLiquidate` function with the given `data`.
/// @dev Either `seizedAssets` or `repaidShares` should be zero.
/// @dev Seizing more than the collateral balance will underflow and revert without any error message.
/// @dev Repaying more than the borrow balance will underflow and revert without any error message.
/// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
/// @param marketParams The market of the position.
/// @param borrower The owner of the position.
/// @param seizedAssets The amount of collateral to seize.
/// @param repaidShares The amount of shares to repay.
/// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
/// @return The amount of assets seized.
/// @return The amount of assets repaid.
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
/// @notice Executes a flash loan.
/// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
//
Submitted on: 2025-11-04 09:48:51
Comments
Log in to comment.
No comments yet.