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/DelegatedDualBot.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {IERC20} from "../lib/openzeppelin-contracts/contracts/interfaces/IERC20.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, Position, MarketParams, Id} from "../lib/morpho-blue/src/interfaces/IMorpho.sol";
import {
IMorphoFlashLoanCallback,
IMorphoSupplyCollateralCallback
} from "../lib/morpho-blue/src/interfaces/IMorphoCallbacks.sol";
import {ISwapper} from "../src/interfaces/ISwapper.sol";
import {IMorphoReader, MarketDataExt, PositionExt} from "../src/interfaces/IMorphoReader.sol";
contract DelegatedDualBot is AccessControl, IMorphoFlashLoanCallback, IMorphoSupplyCollateralCallback {
using SafeERC20 for IERC20;
error AccountNotDelegated(address account);
error InvalidAccount(address account);
error EmptyPosition(Id marketId, address account);
error MarketAlreadyAdded();
error MarketUnknown();
error SlippageCap();
error SlippageBounds();
error MinOutput();
event Wind(address indexed account, Id indexed marketId, uint256 borrowedAssets, uint256 collateralSupplied);
event Unwind(address indexed account, Id indexed marketId, uint256 repaidAssets, uint256 collateralWithdrawn);
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 public maxSlippage = 5; // basis points
uint256 internal constant SLIPPAGE_FACTOR = 10_000;
uint256 internal immutable ORACLE_FACTOR = 1e36;
uint256 internal minExpected;
bytes internal constant NULL_DATA = "";
bool internal constant WIND = true;
bool internal constant UNWIND = false;
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);
_grantRole(CALLBACK_ROLE, address(morpho));
_setRoleAdmin(OPERATOR_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(CALLBACK_ROLE, DEFAULT_ADMIN_ROLE);
}
// === configuration ===
function setSwapper(ISwapper newSwapper) external onlyRole(DEFAULT_ADMIN_ROLE) {
swapper = newSwapper;
}
function setMaxSlippage(uint256 maxSlippageBps) external onlyRole(OPERATOR_ROLE) {
if (maxSlippageBps > 5) revert SlippageCap();
maxSlippage = maxSlippageBps;
}
function setMaxSlippageForce(uint256 maxSlippageBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (maxSlippageBps > SLIPPAGE_FACTOR) revert SlippageBounds();
maxSlippage = maxSlippageBps;
}
function addMarket(Id marketId) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (marketsMap[marketId]) revert MarketAlreadyAdded();
markets.push(marketId);
marketsMap[marketId] = true;
}
function deleteMarket(Id marketId) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (!marketsMap[marketId]) revert MarketUnknown();
uint256 len = markets.length;
for (uint256 i = 0; i < len; i++) {
if (Id.unwrap(markets[i]) == Id.unwrap(marketId)) {
markets[i] = markets[len - 1];
markets.pop();
delete marketsMap[marketId];
return;
}
}
revert MarketUnknown();
}
// === primary actions ===
function wind(Id marketId, uint256 cash) external onlyRole(OPERATOR_ROLE) {
_wind(marketId, cash, msg.sender, 0);
}
function wind(Id marketId, uint256 cash, uint256 minAssets) external onlyRole(OPERATOR_ROLE) {
_wind(marketId, cash, msg.sender, minAssets);
}
function windFor(Id marketId, uint256 cash, address account) external onlyRole(OPERATOR_ROLE) {
_wind(marketId, cash, account, 0);
}
function windFor(Id marketId, uint256 cash, uint256 minAssets, address account) external onlyRole(OPERATOR_ROLE) {
_wind(marketId, cash, account, minAssets);
}
function unwind(Id marketId, uint256 assets) external onlyRole(OPERATOR_ROLE) {
_unwind(marketId, assets, msg.sender, 0);
}
function unwind(Id marketId, uint256 assets, uint256 minCash) external onlyRole(OPERATOR_ROLE) {
_unwind(marketId, assets, msg.sender, minCash);
}
function unwindFor(Id marketId, uint256 assets, address account) external onlyRole(OPERATOR_ROLE) {
_unwind(marketId, assets, account, 0);
}
function unwindFor(Id marketId, uint256 assets, uint256 minCash, address account)
external
onlyRole(OPERATOR_ROLE)
{
_unwind(marketId, assets, account, minCash);
}
function unwindAll(Id marketId) external onlyRole(OPERATOR_ROLE) {
_unwindAll(marketId, msg.sender, 0);
}
function unwindAll(Id marketId, uint256 minCash) external onlyRole(OPERATOR_ROLE) {
_unwindAll(marketId, msg.sender, minCash);
}
function unwindAllFor(Id marketId, address account) external onlyRole(OPERATOR_ROLE) {
_unwindAll(marketId, account, 0);
}
function unwindAllFor(Id marketId, address account, uint256 minCash) external onlyRole(OPERATOR_ROLE) {
_unwindAll(marketId, account, minCash);
}
function shiftCollateral(Id marketFrom, Id marketTo, uint256 assets, address account)
external
onlyRole(OPERATOR_ROLE)
{
_checkMarket(marketFrom);
_checkMarket(marketTo);
address target = _prepareAccount(account);
_withdrawCollateral(marketFrom, assets, target, address(this));
_supplyCollateral(marketTo, assets, target);
}
function shiftCurrency(Id marketFrom, Id marketTo, uint256 cash, address account)
external
onlyRole(OPERATOR_ROLE)
{
_checkMarket(marketFrom);
_checkMarket(marketTo);
address target = _prepareAccount(account);
_borrow(marketFrom, cash, target, address(this));
_repay(marketTo, cash, target);
uint256 surplus = currency.balanceOf(address(this));
if (surplus > 0) currency.safeTransfer(target, surplus);
}
function shiftPosition(Id marketFrom, Id marketTo, uint256 assets, uint256 cash, address account)
external
onlyRole(OPERATOR_ROLE)
{
_checkMarket(marketFrom);
_checkMarket(marketTo);
address target = _prepareAccount(account);
morpho.supplyCollateral(
morpho.idToMarketParams(marketTo), assets, target, abi.encode(marketFrom, marketTo, cash, target)
);
}
// === callback hooks ===
function onMorphoFlashLoan(uint256 amount, bytes calldata data) external onlyRole(CALLBACK_ROLE) {
(Id marketId, address account, bool doWind) = abi.decode(data, (Id, address, bool));
if (doWind) {
uint256 collateralReceived = _swapToCollateral(amount);
uint256 supplied = _supplyCollateral(marketId, collateralReceived, account);
uint256 borrowed = _borrow(marketId, amount, account, address(this));
currency.forceApprove(address(morpho), amount);
emit Wind(account, marketId, borrowed, supplied);
} else {
uint256 cash = _swapToCurrency(amount);
(uint256 repaid,) = _repayCurrencyFallbackShares(marketId, cash, account);
uint256 withdrawn = _withdrawCollateral(marketId, amount, account, address(this));
collateral.forceApprove(address(morpho), amount);
uint256 surplus = currency.balanceOf(address(this));
if (surplus > 0) currency.safeTransfer(account, surplus);
emit Unwind(account, marketId, repaid, withdrawn);
}
}
function onMorphoSupplyCollateral(uint256 assets, bytes calldata data) external onlyRole(CALLBACK_ROLE) {
(Id marketFrom, Id marketTo, uint256 cash, address account) = abi.decode(data, (Id, Id, uint256, address));
_borrow(marketTo, cash, account, address(this));
_repay(marketFrom, cash, account);
_withdrawCollateral(marketFrom, assets, account, address(this));
collateral.forceApprove(address(morpho), assets);
uint256 surplus = currency.balanceOf(address(this));
if (surplus > 0) currency.safeTransfer(account, surplus);
}
// === account-aware wrappers ===
function borrow(Id marketId, uint256 cash, address account, address receiver) external onlyRole(OPERATOR_ROLE) {
_borrow(marketId, cash, _prepareAccount(account), receiver == address(0) ? _prepareAccount(account) : receiver);
}
function repay(Id marketId, uint256 cash, address account) external onlyRole(OPERATOR_ROLE) {
_repay(marketId, cash, _prepareAccount(account));
}
function repayShares(Id marketId, uint256 shares, address account) external onlyRole(OPERATOR_ROLE) {
_repayShares(marketId, shares, _prepareAccount(account));
}
function supplyCollateral(Id marketId, uint256 assets, address account) external onlyRole(OPERATOR_ROLE) {
_supplyCollateral(marketId, assets, _prepareAccount(account));
}
function withdrawCollateral(Id marketId, uint256 assets, address account, address receiver)
external
onlyRole(OPERATOR_ROLE)
{
address target = _prepareAccount(account);
_withdrawCollateral(marketId, assets, target, receiver == address(0) ? target : receiver);
}
function withdrawAllCollateral(Id marketId, address account, address receiver) external onlyRole(OPERATOR_ROLE) {
address target = _prepareAccount(account);
Position memory position = morpho.position(marketId, target);
_withdrawCollateral(marketId, position.collateral, target, receiver == address(0) ? target : receiver);
}
function swapToCurrency(uint256 assets) external onlyRole(OPERATOR_ROLE) {
if (assets == 0) assets = collateral.balanceOf(address(this));
_swapToCurrency(assets);
}
function swapToCollateral(uint256 cash) external onlyRole(OPERATOR_ROLE) {
if (cash == 0) cash = currency.balanceOf(address(this));
_swapToCollateral(cash);
}
// === views ===
function equity(Id marketId, address account) external view returns (uint256) {
PositionExt memory position = morphoReader.getPosition(marketId, _defaultAccount(account));
return position.collateralValue - position.borrowedAssets;
}
function priceCollateralInCurrency(uint256 assets) external view returns (uint256) {
return (assets * oracle.price()) / ORACLE_FACTOR;
}
// === internal helpers ===
function _wind(Id marketId, uint256 cash, address account, uint256 minAssets) internal {
_checkMarket(marketId);
address target = _prepareAccount(account);
uint256 previous = minExpected;
if (minAssets != 0) minExpected = minAssets;
morpho.flashLoan(address(currency), cash, abi.encode(marketId, target, WIND));
minExpected = previous;
}
function _unwind(Id marketId, uint256 assets, address account, uint256 minCash) internal {
_checkMarket(marketId);
address target = _prepareAccount(account);
uint256 previous = minExpected;
if (minCash != 0) minExpected = minCash;
morpho.flashLoan(address(collateral), assets, abi.encode(marketId, target, UNWIND));
minExpected = previous;
}
function _unwindAll(Id marketId, address account, uint256 minCash) internal {
address target = _prepareAccount(account);
Position memory position = morpho.position(marketId, target);
if (position.collateral == 0 && position.borrowShares == 0) revert EmptyPosition(marketId, target);
_unwind(marketId, uint256(position.collateral), target, minCash);
}
function _borrow(Id marketId, uint256 cash, address account, address receiver)
internal
returns (uint256 assetsBorrowed)
{
_ensureDelegation(account);
(assetsBorrowed,) = morpho.borrow(
morpho.idToMarketParams(marketId), cash, 0, account, receiver == address(0) ? account : receiver
);
}
function _repay(Id marketId, uint256 cash, address account)
internal
returns (uint256 assetsRepaid, uint256 sharesRepaid)
{
_ensureDelegation(account);
if (cash == 0) return (0, 0);
currency.forceApprove(address(morpho), cash);
(assetsRepaid, sharesRepaid) = morpho.repay(morpho.idToMarketParams(marketId), cash, 0, account, NULL_DATA);
currency.forceApprove(address(morpho), 0);
}
function _repayShares(Id marketId, uint256 shares, address account)
internal
returns (uint256 assetsRepaid, uint256 sharesRepaid)
{
_ensureDelegation(account);
if (shares == 0) return (0, 0);
currency.forceApprove(address(morpho), type(uint256).max);
(assetsRepaid, sharesRepaid) = morpho.repay(morpho.idToMarketParams(marketId), 0, shares, account, NULL_DATA);
currency.forceApprove(address(morpho), 0);
}
function _repayCurrencyFallbackShares(Id marketId, uint256 cash, address account)
internal
returns (uint256 assetsRepaid, uint256 sharesRepaid)
{
_ensureDelegation(account);
MarketParams memory params = morpho.idToMarketParams(marketId);
currency.forceApprove(address(morpho), cash);
try morpho.repay(params, cash, 0, account, NULL_DATA) returns (uint256 assets, uint256 shares) {
assetsRepaid = assets;
sharesRepaid = shares;
} catch {
currency.forceApprove(address(morpho), 0);
Position memory position = morpho.position(marketId, account);
if (position.borrowShares > 0) {
currency.forceApprove(address(morpho), type(uint256).max);
(assetsRepaid, sharesRepaid) = morpho.repay(params, 0, position.borrowShares, account, NULL_DATA);
currency.forceApprove(address(morpho), 0);
}
}
currency.forceApprove(address(morpho), 0);
}
function _supplyCollateral(Id marketId, uint256 assets, address account)
internal
returns (uint256 assetsSupplied)
{
_ensureDelegation(account);
if (assets == 0) return 0;
collateral.forceApprove(address(morpho), assets);
morpho.supplyCollateral(morpho.idToMarketParams(marketId), assets, account, NULL_DATA);
collateral.forceApprove(address(morpho), 0);
assetsSupplied = assets;
}
function _withdrawCollateral(Id marketId, uint256 assets, address account, address receiver)
internal
returns (uint256 assetsWithdrawn)
{
_ensureDelegation(account);
morpho.withdrawCollateral(
morpho.idToMarketParams(marketId), assets, account, receiver == address(0) ? account : receiver
);
assetsWithdrawn = assets;
}
function _swapToCurrency(uint256 assets) internal returns (uint256 cash) {
collateral.forceApprove(address(swapper), assets);
cash = swapper.sell(collateral, currency, assets);
uint256 minOut = _minCurrency(assets);
if (cash < minOut) revert MinOutput();
}
function _swapToCollateral(uint256 cash) internal returns (uint256 assets) {
currency.forceApprove(address(swapper), cash);
assets = swapper.sell(currency, collateral, cash);
uint256 minOut = _minCollateral(cash);
if (assets < minOut) revert MinOutput();
}
function _checkMarket(Id marketId) internal view {
if (!marketsMap[marketId]) revert MarketUnknown();
}
function _defaultAccount(address account) internal view returns (address) {
return account == address(0) ? msg.sender : account;
}
function _prepareAccount(address account) internal view returns (address resolved) {
resolved = _defaultAccount(account);
if (resolved == address(0)) revert InvalidAccount(resolved);
_ensureDelegation(resolved);
}
function _ensureDelegation(address account) internal view {
if (account == address(0)) revert InvalidAccount(account);
if (account != address(this) && !morpho.isAuthorized(account, address(this))) {
revert AccountNotDelegated(account);
}
}
function _min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
// === recovery ===
function recover(IERC20 token, address recipient, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.safeTransfer(recipient, amount);
}
function recoverETH(address recipient, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
(bool ok,) = payable(recipient).call{value: amount}("");
require(ok, "eth transfer failed");
}
function _minCollateral(uint256 cash) internal view returns (uint256) {
if (minExpected > 0) return minExpected;
return (cash * ORACLE_FACTOR * (SLIPPAGE_FACTOR - maxSlippage)) / (oracle.price() * SLIPPAGE_FACTOR);
}
function _minCurrency(uint256 assets) internal view returns (uint256) {
if (minExpected > 0) return minExpected;
return (assets * oracle.price() * (SLIPPAGE_FACTOR - maxSlippage)) / (ORACLE_FACTOR * SLIPPAGE_FACTOR);
}
}
"
},
"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/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
/// markets combined, plus donations).
/// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
/// - `flashFee` is zero.
/// - `maxFlashLoan` is the token's balance of this contract.
/// - The receiver of `assets` is the caller.
/// @param token The token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
/// @param authorized The authorized address.
/// @param newIsAuthorized The new authorization status.
function setAuthorization(address authorized, bool newIsAuthorized) external;
/// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
/// @dev Warning: Reverts if the signature has already been submitted.
/// @dev The signature is malleable, but it has no impact on the security here.
/// @dev The nonce is passed as argument to be able to revert with a different error message.
/// @param authorization The `Authorization` struct.
/// @param signature The signature.
function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
/// @notice Accrues interest for the given market `marketParams`.
function accrueInterest(MarketParams memory marketParams) external;
/// @notice Returns the data stored on the different `slots`.
function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
}
/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoStaticTyping is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user)
external
view
returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
/// @notice The state of the market corresponding to `id`.
/// @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 accrued shares by `feeRecipient` since the last interest
/// accrual.
function market(Id id)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id)
external
view
returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
}
/// @title IMorpho
/// @author Morpho Labs
/// @custom:contact security@morpho.org
/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
interface IMorpho is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user) external view returns (Position memory p);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
/// interest accrual.
function market(Id id) external view returns (Market memory m);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id) external view returns (MarketParams memory);
}
"
},
"lib/morpho-blue/src/interfaces/IMorphoCallbacks.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title IMorphoLiquidateCallback
/// @notice Interface that liquidators willing to use `liquidate`'s callback must implement.
interface IMorphoLiquidateCallback {
/// @notice Callback called when a liquidation occurs.
/// @dev The callback is called only if data is not empty.
/// @param repaidAssets The amount of repaid assets.
/// @param data Arbitrary data passed to the `liquidate` function.
function onMorphoLiquidate(uint256 repaidAssets, bytes calldata data) external;
}
/// @title IMorphoRepayCallback
/// @notice Interface that users willing to use `repay`'s callback must implement.
interface IMorphoRepayCallback {
/// @notice Callback called when a repayment occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of repaid assets.
/// @param data Arbitrary data passed to the `repay` function.
function onMorphoRepay(uint256 assets, bytes calldata data) external;
}
/// @title IMorphoSupplyCallback
/// @notice Interface that users willing to use `supply`'s callback must implement.
interface IMorphoSupplyCallback {
/// @notice Callback called when a supply occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of supplied assets.
/// @param data Arbitrary data passed to the `supply` function.
function onMorphoSupply(uint256 assets, bytes calldata data) external;
}
/// @title IMorphoSupplyCollateralCallback
/// @notice Interface that users willing to use `supplyCollateral`'s callback must implement.
interface IMorphoSupplyCollateralCallback {
/// @notice Callback called when a supply of collateral occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of supplied collateral.
/// @param data Arbitrary data passed to the `supplyCollateral` function.
function onMorphoSupplyCollateral(uint256 assets, bytes calldata data) external;
}
/// @title IMorphoFlashLoanCallback
/// @notice Interface that users willing to use `flashLoan`'s callback must implement.
interface IMorphoFlashLoanCallback {
/// @notice Callback called when a flash loan occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of assets that was flash loaned.
/// @param data Arbitrary data passed to the `flashLoan` function.
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}
"
},
"src/interfaces/ISwapper.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
interface ISwapper {
/**
* @notice Sell from tokenFrom to tokenTo, need to approuve first
* @param amountIn number of token to sell (tokenFrom), 0 means sell all
*/
function sell(
IERC20 tokenFrom,
IERC20 tokenTo,
uint256 amountIn
) external returns (uint256);
/**
* @notice Preview from tokenFrom to tokenTo and return the amount you would get
* @param amountIn number of token to sell (tokenFrom), 0 means sell all
*/
function previewSell(
IERC20 tokenFrom,
IERC20 tokenTo,
uint256 amountIn
) external returns (uint256);
}
"
},
"src/interfaces/IMorphoReader.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {Id} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
struct MarketDataExt {
uint256 totalSupplyAssets;
uint256 totalSupplyShares;
uint256 totalBorrowAssets;
uint256 totalBorrowShares;
uint256 fee;
uint256 utilization;
uint256 supplyRate;
uint256 borrowRate;
}
struct PositionExt {
uint256 suppliedShares;
uint256 suppliedAssets;
uint256 borrowedShares;
uint256 borrowedAssets;
uint256 collateral;
uint256 collateralValue;
uint256 ltv;
uint256 healthFactor;
}
interface IMorphoReader {
function getMarketData(Id id) external view returns (MarketDataExt memory);
function getPosition(
Id id,
address user
) external view returns (PositionExt memory);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 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/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**\
Submitted on: 2025-11-05 18:55:54
Comments
Log in to comment.
No comments yet.