Skip to content
Verified contractExactMIT

SusdsLooper

Address0x10ae1671a38cd93985928fe9c083faf6cfdea3f7
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,428,934
Creation transaction
0x9990b3a79f…0c55686b57

susdsoseroloop.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

type Id is bytes32;

struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

struct Position {
    uint256 supplyShares;
    uint128 borrowShares;
    uint128 collateral;
}

struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
    function allowance(address, address) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}

interface IOracle {
    function price() external view returns (uint256);
}

interface IMorphoFlashLoanCallback {
    function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}

interface IMorpho {
    function idToMarketParams(Id id) external view returns (MarketParams memory);
    function position(Id id, address user) external view returns (Position memory);
    function market(Id id) external view returns (Market memory);
    function isAuthorized(address authorizer, address authorized) external view returns (bool);
    function setAuthorization(address authorized, bool newIsAuthorized) external;
    function accrueInterest(MarketParams memory marketParams) external;
    function flashLoan(address token, uint256 assets, bytes calldata data) external;
    function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
        external;
    function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
        external;
    function borrow(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver)
        external
        returns (uint256, uint256);
    function repay(MarketParams memory marketParams, uint256 assets, uint256 shares, address onBehalf, bytes memory data)
        external
        returns (uint256, uint256);
}

interface ISUsds {
    function deposit(uint256 assets, address receiver, uint16 referral) external returns (uint256 shares);
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);
    function previewDeposit(uint256 assets) external view returns (uint256 shares);
}

interface IUsdsPsmWrapper {
    function sellGem(address usr, uint256 gemAmt) external returns (uint256 usdsOutWad);
    function buyGem(address usr, uint256 gemAmt) external returns (uint256 usdsInWad);
    function tout() external view returns (uint256);
}

interface ISwapRouter02 {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
}

// ===================================================================== CONTRAT

contract SusdsLooper is IMorphoFlashLoanCallback {

    IMorpho public constant MORPHO = IMorpho(0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb);
    IERC20 public constant USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
    IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
    IERC20 public constant USDS = IERC20(0xdC035D45d973E3EC169d2276DDab16f1e407384F);
    IERC20 public constant SUSDS = IERC20(0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD);

    uint256 internal constant WAD = 1e18;
    uint256 internal constant BPS = 10_000;
    uint256 public constant MAX_SLIPPAGE_BPS = 100; 
    uint256 internal constant ORACLE_PRICE_SCALE = 1e36;
    uint256 internal constant VIRTUAL_SHARES = 1e6;
    uint256 internal constant VIRTUAL_ASSETS = 1;

    address public owner;
    Id public marketId;
    uint16 public referral;
    uint24 public uniFee;
    ISwapRouter02 public router;
    IUsdsPsmWrapper public psm;

    enum Action {
        LEVERAGE,
        DELEVERAGE,
        UNWIND,
        REMINT
    }

    address private transient _activeUser;

    // --------------------------------------------------------------- events / errors
    event Leveraged(address indexed user, uint256 borrowed, uint256 collateralAdded, uint256 healthFactor);
    event Reminted(address indexed user, uint256 susdsReminted, uint256 healthFactor);
    event Deleveraged(address indexed user, uint256 repaid, uint256 collateralRemoved, uint256 healthFactor);
    event Unwound(address indexed user, uint256 debtRepaid, uint256 susdsReturned);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event MarketSet(Id indexed marketId);
    event ReferralSet(uint16 referral);
    event UniFeeSet(uint24 fee);
    event RouterSet(address router);
    event PsmSet(address psm);

    error NotOwner();
    error NotMorpho();
    error NoActiveLoop();
    error BadMarket();
    error BadParams();
    error NothingToDo();
    error UseUnwind();
    error HealthFactorTooLow(uint256 hf, uint256 minHf);
    error ERC20CallFailed(address token);

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    constructor(Id _marketId, uint16 _referral) {
        owner = msg.sender;
        emit OwnershipTransferred(address(0), msg.sender);

        _setMarket(_marketId);
        referral = _referral;
        uniFee = 100; 

        _forceApprove(USDT, address(MORPHO), type(uint256).max); 
        _forceApprove(USDS, address(SUSDS), type(uint256).max); 
        _forceApprove(SUSDS, address(MORPHO), type(uint256).max); 

        _setRouter(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45); 
        _setPsm(0xA188EEC8F81263234dA3622A406892F3D630f98c); 
    }

    function leverage(
        uint256 usdtIn,
        uint256 usdcIn,
        uint256 susdsIn,
        uint256 targetHf,
        uint256 minHf,
        uint256 slippageBps
    ) external returns (uint256 borrowed, uint256 finalHf) {
        _checkParams(targetHf, minHf, slippageBps);

        if (usdtIn > 0) _safeTransferFrom(USDT, msg.sender, address(this), usdtIn);
        if (usdcIn > 0) _safeTransferFrom(USDC, msg.sender, address(this), usdcIn);
        if (susdsIn > 0) _safeTransferFrom(SUSDS, msg.sender, address(this), susdsIn);

        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        MORPHO.accrueInterest(mp);
        uint256 collBefore = MORPHO.position(marketId, msg.sender).collateral;

        borrowed = _borrowForTarget(mp, msg.sender, usdtIn + usdcIn, susdsIn, targetHf, slippageBps);
        if (borrowed == 0) revert NothingToDo();

        _flash(Action.LEVERAGE, borrowed, slippageBps);

        finalHf = healthFactor(msg.sender);
        if (finalHf < minHf) revert HealthFactorTooLow(finalHf, minHf);
        _sweep(msg.sender);

        emit Leveraged(msg.sender, borrowed, MORPHO.position(marketId, msg.sender).collateral - collBefore, finalHf);
    }

    function deleverage(uint256 targetHf, uint256 minHf, uint256 slippageBps)
        external
        returns (uint256 repaid, uint256 finalHf)
    {
        _checkParams(targetHf, minHf, slippageBps);

        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        MORPHO.accrueInterest(mp);
        uint256 collBefore = MORPHO.position(marketId, msg.sender).collateral;

        repaid = _repayForTarget(mp, msg.sender, targetHf, slippageBps);
        if (repaid == 0) revert NothingToDo();

        _flash(Action.DELEVERAGE, repaid, slippageBps);

        finalHf = healthFactor(msg.sender);
        if (finalHf < minHf) revert HealthFactorTooLow(finalHf, minHf);
        _sweep(msg.sender); 

        emit Deleveraged(msg.sender, repaid, collBefore - MORPHO.position(marketId, msg.sender).collateral, finalHf);
    }

    function unwind(uint256 slippageBps) external {
        if (slippageBps > MAX_SLIPPAGE_BPS) revert BadParams();

        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        MORPHO.accrueInterest(mp);
        Position memory pos = MORPHO.position(marketId, msg.sender);
        uint256 debt = _toAssetsUp(pos.borrowShares, MORPHO.market(marketId));

        if (debt > 0) {
            _flash(Action.UNWIND, debt, slippageBps);
        } else if (pos.collateral > 0) {
            MORPHO.withdrawCollateral(mp, pos.collateral, msg.sender, address(this));
        } else {
            revert NothingToDo();
        }

        uint256 susdsOut = SUSDS.balanceOf(address(this));
        _sweep(msg.sender);
        emit Unwound(msg.sender, debt, susdsOut);
    }

    function remint(uint256 susdsAmount) external returns (uint256 finalHf) {
        if (susdsAmount == 0) revert BadParams();
        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        MORPHO.accrueInterest(mp);
        Position memory pos = MORPHO.position(marketId, msg.sender);
        if (pos.collateral == 0) revert NothingToDo();
        if (susdsAmount > pos.collateral) susdsAmount = pos.collateral;

        uint256 debt = _toAssetsUp(pos.borrowShares, MORPHO.market(marketId));
        uint256 hfBefore = healthFactor(msg.sender);

        if (debt == 0) {
            MORPHO.withdrawCollateral(mp, susdsAmount, msg.sender, address(this));
            MORPHO.supplyCollateral(mp, _remintTo(msg.sender, susdsAmount), msg.sender, "");
        } else {
            uint256 flash = susdsAmount == pos.collateral ? debt : debt * susdsAmount / pos.collateral + 1;
            if (flash > debt) flash = debt;
            _flash(Action.REMINT, flash, susdsAmount);
        }

        finalHf = healthFactor(msg.sender);
        if (debt > 0 && finalHf + 1e14 < hfBefore) revert HealthFactorTooLow(finalHf, hfBefore);
        _sweep(msg.sender);
        emit Reminted(msg.sender, susdsAmount, finalHf);
    }

    function onMorphoFlashLoan(uint256 assets, bytes calldata data) external {
        if (msg.sender != address(MORPHO)) revert NotMorpho();
        (Action action, address user, uint256 slip) = abi.decode(data, (Action, address, uint256));
        if (user == address(0) || user != _activeUser) revert NoActiveLoop();

        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        if (action == Action.LEVERAGE) _onLeverage(mp, user, assets, slip);
        else if (action == Action.DELEVERAGE) _onDeleverage(mp, user, assets, slip);
        else if (action == Action.UNWIND) _onUnwind(mp, user, assets, slip);
        else _onRemint(mp, user, assets, slip); 
    }

    function _onLeverage(MarketParams memory mp, address user, uint256 assets, uint256 slip) internal {
        uint256 usdtBal = USDT.balanceOf(address(this));
        router.exactInputSingle(
            ISwapRouter02.ExactInputSingleParams({
                tokenIn: address(USDT),
                tokenOut: address(USDC),
                fee: uniFee,
                recipient: address(this),
                amountIn: usdtBal,
                amountOutMinimum: usdtBal * (BPS - slip) / BPS,
                sqrtPriceLimitX96: 0
            })
        );
        uint256 usds = psm.sellGem(address(this), USDC.balanceOf(address(this)));
        uint256 minted = ISUsds(address(SUSDS)).deposit(usds, user, referral);
        _safeTransferFrom(SUSDS, user, address(this), minted);
        MORPHO.supplyCollateral(mp, SUSDS.balanceOf(address(this)), user, "");
        MORPHO.borrow(mp, assets, 0, user, address(this));
    }

    function _onRemint(MarketParams memory mp, address user, uint256 assets, uint256 amount) internal {
        Position memory pos = MORPHO.position(marketId, user);
        if (amount >= pos.collateral) {
            amount = pos.collateral;
            MORPHO.repay(mp, 0, pos.borrowShares, user, "");
        } else {
            MORPHO.repay(mp, assets, 0, user, "");
        }
        MORPHO.withdrawCollateral(mp, amount, user, address(this));
        MORPHO.supplyCollateral(mp, _remintTo(user, amount), user, "");
        MORPHO.borrow(mp, assets, 0, user, address(this));
    }

    function _remintTo(address user, uint256 susdsAmount) internal returns (uint256 minted) {
        uint256 usds = ISUsds(address(SUSDS)).redeem(susdsAmount, address(this), address(this));
        minted = ISUsds(address(SUSDS)).deposit(usds, user, referral);
        _safeTransferFrom(SUSDS, user, address(this), minted);
    }

    function _onDeleverage(MarketParams memory mp, address user, uint256 assets, uint256 slip) internal {
        MORPHO.repay(mp, assets, 0, user, "");
        uint256 usdsNeeded = _usdsNeeded(assets, slip);
        uint256 shares = ISUsds(address(SUSDS)).previewWithdraw(usdsNeeded);
        MORPHO.withdrawCollateral(mp, shares, user, address(this));
        _sellSusdsForUsdt(assets, slip, usdsNeeded);
    }

    function _onUnwind(MarketParams memory mp, address user, uint256 assets, uint256 slip) internal {
        Position memory pos = MORPHO.position(marketId, user);
        MORPHO.repay(mp, 0, pos.borrowShares, user, "");
        MORPHO.withdrawCollateral(mp, pos.collateral, user, address(this));
        _sellSusdsForUsdt(assets, slip, _usdsNeeded(assets, slip));
    }

    function _sellSusdsForUsdt(uint256 usdtOut, uint256 slip, uint256 usdsNeeded) internal {
        uint256 usdcMax = _usdcMax(usdtOut, slip);
        ISUsds(address(SUSDS)).withdraw(usdsNeeded, address(this), address(this));
        psm.buyGem(address(this), usdcMax);
        router.exactOutputSingle(
            ISwapRouter02.ExactOutputSingleParams({
                tokenIn: address(USDC),
                tokenOut: address(USDT),
                fee: uniFee,
                recipient: address(this),
                amountOut: usdtOut,
                amountInMaximum: usdcMax,
                sqrtPriceLimitX96: 0
            })
        );
    }

    function setMarket(Id newMarketId) external onlyOwner {
        _setMarket(newMarketId);
    }

    function setReferral(uint16 newReferral) external onlyOwner {
        referral = newReferral;
        emit ReferralSet(newReferral);
    }

    function setUniFee(uint24 fee) external onlyOwner {
        if (fee != 100 && fee != 500) revert BadParams();
        uniFee = fee;
        emit UniFeeSet(fee);
    }

    function setRouter(address newRouter) external onlyOwner {
        _setRouter(newRouter);
    }

    function setPsm(address newPsm) external onlyOwner {
        _setPsm(newPsm);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert BadParams();
        emit OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }

    function rescue(IERC20 token, uint256 amount) external onlyOwner {
        _safeTransfer(token, owner, amount);
    }

    function healthFactor(address user) public view returns (uint256) {
        (,, uint256 debt, uint256 hf,) = getPosition(user);
        return debt == 0 ? type(uint256).max : hf;
    }

    function getPosition(address user)
        public
        view
        returns (uint256 collateral, uint256 collateralValue, uint256 debt, uint256 hf, uint256 ltv)
    {
        MarketParams memory mp = MORPHO.idToMarketParams(marketId);
        Position memory pos = MORPHO.position(marketId, user);
        collateral = pos.collateral;
        collateralValue = collateral * IOracle(mp.oracle).price() / ORACLE_PRICE_SCALE;
        debt = _toAssetsUp(pos.borrowShares, MORPHO.market(marketId));
        if (debt > 0) {
            hf = collateralValue * mp.lltv / debt;
            ltv = collateralValue == 0 ? type(uint256).max : debt * WAD / collateralValue;
        }
    }

    function previewLeverage(
        address user,
        uint256 usdtIn,
        uint256 usdcIn,
        uint256 susdsIn,
        uint256 targetHf,
        uint256 slippageBps
    ) external view returns (uint256 borrow, uint256 susdsApproval) {
        borrow = _borrowForTarget(
            MORPHO.idToMarketParams(marketId), user, usdtIn + usdcIn, susdsIn, targetHf, slippageBps
        );
        uint256 minted = ISUsds(address(SUSDS)).previewDeposit((borrow + usdtIn + usdcIn) * 1e12);
        susdsApproval = susdsIn + minted * 10_050 / BPS;
    }

    function previewDeleverage(address user, uint256 targetHf, uint256 slippageBps) external view returns (uint256) {
        return _repayForTarget(MORPHO.idToMarketParams(marketId), user, targetHf, slippageBps);
    }

    function _borrowForTarget(
        MarketParams memory mp,
        address user,
        uint256 stableIn,
        uint256 susdsIn,
        uint256 targetHf,
        uint256 slip
    ) internal view returns (uint256) {
        uint256 e = WAD * (BPS - slip) / BPS;
        uint256 lltvE = mp.lltv * e / WAD;
        if (targetHf <= lltvE) revert BadParams();

        Position memory pos = MORPHO.position(marketId, user);
        uint256 c = (uint256(pos.collateral) + susdsIn) * IOracle(mp.oracle).price() / ORACLE_PRICE_SCALE
            + stableIn * e / WAD;

        uint256 num1 = mp.lltv * c;
        uint256 num2 = targetHf * _toAssetsUp(pos.borrowShares, MORPHO.market(marketId));
        if (num1 <= num2) return 0;
        return (num1 - num2) / (targetHf - lltvE);
    }

    function _repayForTarget(MarketParams memory mp, address user, uint256 targetHf, uint256 slip)
        internal
        view
        returns (uint256 r)
    {
        uint256 lltvOverE = mp.lltv * BPS / (BPS - slip);
        if (targetHf <= lltvOverE) revert BadParams();

        Position memory pos = MORPHO.position(marketId, user);
        uint256 debt = _toAssetsUp(pos.borrowShares, MORPHO.market(marketId));
        uint256 c = uint256(pos.collateral) * IOracle(mp.oracle).price() / ORACLE_PRICE_SCALE;

        uint256 num1 = targetHf * debt;
        uint256 num2 = mp.lltv * c;
        if (num1 <= num2) return 0;
        r = (num1 - num2) / (targetHf - lltvOverE) + 1;
        if (r >= debt) revert UseUnwind();
    }

    function _usdcMax(uint256 usdtOut, uint256 slip) internal pure returns (uint256) {
        return usdtOut * (BPS + slip) / BPS + 1;
    }

    function _usdsNeeded(uint256 usdtOut, uint256 slip) internal view returns (uint256 usds) {
        usds = _usdcMax(usdtOut, slip) * 1e12;
        usds += usds * psm.tout() / WAD;
    }

    function _toAssetsUp(uint256 shares, Market memory m) internal pure returns (uint256) {
        uint256 num = shares * (uint256(m.totalBorrowAssets) + VIRTUAL_ASSETS);
        uint256 den = uint256(m.totalBorrowShares) + VIRTUAL_SHARES;
        return (num + den - 1) / den;
    }

    function _checkParams(uint256 targetHf, uint256 minHf, uint256 slip) internal pure {
        if (minHf <= WAD || targetHf < minHf || slip > MAX_SLIPPAGE_BPS) revert BadParams();
    }

    function _flash(Action action, uint256 amount, uint256 slip) internal {
        _activeUser = msg.sender;
        MORPHO.flashLoan(address(USDT), amount, abi.encode(action, msg.sender, slip));
        _activeUser = address(0);
    }

    function _setMarket(Id id) internal {
        MarketParams memory mp = MORPHO.idToMarketParams(id);
        if (mp.loanToken != address(USDT) || mp.collateralToken != address(SUSDS)) revert BadMarket();
        marketId = id;
        emit MarketSet(id);
    }

    function _setRouter(address newRouter) internal {
        if (newRouter == address(0)) revert BadParams();
        if (address(router) != address(0)) {
            _forceApprove(USDT, address(router), 0);
            _forceApprove(USDC, address(router), 0);
        }
        router = ISwapRouter02(newRouter);
        _forceApprove(USDT, newRouter, type(uint256).max);
        _forceApprove(USDC, newRouter, type(uint256).max);
        emit RouterSet(newRouter);
    }

    function _setPsm(address newPsm) internal {
        if (newPsm == address(0)) revert BadParams();
        if (address(psm) != address(0)) {
            _forceApprove(USDC, address(psm), 0);
            _forceApprove(USDS, address(psm), 0);
        }
        psm = IUsdsPsmWrapper(newPsm);
        _forceApprove(USDC, newPsm, type(uint256).max);
        _forceApprove(USDS, newPsm, type(uint256).max);
        emit PsmSet(newPsm);
    }

    function _sweep(address to) internal {
        uint256 b;
        if ((b = USDT.balanceOf(address(this))) > 0) _safeTransfer(USDT, to, b);
        if ((b = USDC.balanceOf(address(this))) > 0) _safeTransfer(USDC, to, b);
        if ((b = USDS.balanceOf(address(this))) > 0) _safeTransfer(USDS, to, b);
        if ((b = SUSDS.balanceOf(address(this))) > 0) _safeTransfer(SUSDS, to, b);
    }

    // --------------------------------------------------------------- safe ERC20 (compatible USDT)

    function _call(IERC20 token, bytes memory data) private {
        (bool ok, bytes memory ret) = address(token).call(data);
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert ERC20CallFailed(address(token));
    }

    function _safeTransfer(IERC20 token, address to, uint256 amount) internal {
        _call(token, abi.encodeCall(IERC20.transfer, (to, amount)));
    }

    function _safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
        _call(token, abi.encodeCall(IERC20.transferFrom, (from, to, amount)));
    }

    function _forceApprove(IERC20 token, address spender, uint256 amount) internal {
        _call(token, abi.encodeCall(IERC20.approve, (spender, 0)));
        if (amount > 0) _call(token, abi.encodeCall(IERC20.approve, (spender, amount)));
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.