SmartFarmingManager

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "settings": {
    "evmVersion": "cancun",
    "metadata": {
      "bytecodeHash": "ipfs",
      "useLiteralContent": true
    },
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  },
  "sources": {
    "contracts/SmartFarmingManager.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import {SafeERC20} from "./dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol";
import {Math} from "./dependencies/openzeppelin/utils/math/Math.sol";
import {IERC20} from "./dependencies/openzeppelin/token/ERC20/IERC20.sol";
import {Initializable} from "./dependencies/openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import {IStargateReceiver} from "./dependencies/stargate-protocol/interfaces/IStargateReceiver.sol";
import {Manageable} from "./access/Manageable.sol";
import {ReentrancyGuardDeprecated} from "./utils/ReentrancyGuardDeprecated.sol";
import {ReentrancyGuardTransient} from "./utils/ReentrancyGuardTransient.sol";
import {WadRayMath} from "./lib/WadRayMath.sol";
import {CrossChainLib} from "./lib/CrossChainLib.sol";
import {ISyntheticToken} from "./interfaces/ISyntheticToken.sol";
import {IDepositToken} from "./interfaces/IDepositToken.sol";
import {IPool} from "./interfaces/IPool.sol";
import {IDebtToken} from "./interfaces/IDebtToken.sol";
import {ICrossChainDispatcher} from "./interfaces/ICrossChainDispatcher.sol";
import {ISwapper} from "./interfaces/external/ISwapper.sol";
import {SmartFarmingManagerStorageV1} from "./storage/SmartFarmingManagerStorage.sol";

error SyntheticDoesNotExist();
error PoolIsNull();
error FlashRepaySlippageTooHigh();
error LeverageTooLow();
error LeverageTooHigh();
error LeverageSlippageTooHigh();
error PositionIsNotHealthy();
error AmountIsZero();
error AmountIsTooHigh();
error DepositTokenDoesNotExist();
error AddressIsNull();
error NewValueIsSameAsCurrent();
error CrossChainRequestInvalidKey();
error SenderIsNotCrossChainDispatcher();
error CrossChainRequestCompletedAlready();
error TokenInIsNull();
error BridgeTokenIsNull();
error CrossChainFlashRepayInactive();

/**
 * @title SmartFarmingManager contract
 */
contract SmartFarmingManager is
    Initializable,
    ReentrancyGuardDeprecated,
    ReentrancyGuardTransient,
    Manageable,
    SmartFarmingManagerStorageV1
{
    using SafeERC20 for IERC20;
    using SafeERC20 for ISyntheticToken;
    using WadRayMath for uint256;

    string public constant VERSION = "1.3.2";

    /// @notice Emitted when a cross-chain leverage request is finalized
    event CrossChainLeverageFinished(uint256 indexed id);

    /// @notice Emitted when a cross-chain leverage request is created
    event CrossChainLeverageStarted(uint256 indexed id);

    /// @notice Emitted when a cross-chain flash repay request is finalized
    event CrossChainFlashRepayFinished(uint256 indexed id);

    /// @notice Emitted when a cross-chain flash repay request is created
    event CrossChainFlashRepayStarted(uint256 indexed id);

    /// @notice Emitted when debt is flash repaid
    event FlashRepaid(
        ISyntheticToken indexed syntheticToken,
        IDepositToken indexed depositToken,
        uint256 withdrawn,
        uint256 repaid
    );

    /// @notice Emitted when deposit is leveraged
    event Leveraged(
        IERC20 indexed tokenIn,
        IDepositToken indexed depositToken,
        ISyntheticToken indexed syntheticToken,
        uint256 leverage,
        uint256 amountIn,
        uint256 issued,
        uint256 deposited
    );

    /**
     * @dev Throws if sender isn't a valid ProxyOFT contract
     */
    modifier onlyIfCrossChainDispatcher() {
        if (_msgSender() != address(crossChainDispatcher())) revert SenderIsNotCrossChainDispatcher();
        _;
    }

    /**
     * @dev Throws if deposit token doesn't exist
     */
    modifier onlyIfDepositTokenExists(IDepositToken depositToken_) {
        if (!pool.doesDepositTokenExist(depositToken_)) revert DepositTokenDoesNotExist();
        _;
    }

    /**
     * @dev Throws if synthetic token doesn't exist
     */
    modifier onlyIfSyntheticTokenExists(ISyntheticToken syntheticToken_) {
        if (!pool.doesSyntheticTokenExist(syntheticToken_)) revert SyntheticDoesNotExist();
        _;
    }

    constructor() {
        _disableInitializers();
    }

    function initialize(IPool pool_) public initializer {
        if (address(pool_) == address(0)) revert PoolIsNull();
        __Manageable_init(pool_);
    }

    /**
     * @notice Get the Cross-chain dispatcher contract
     */
    function crossChainDispatcher() public view returns (ICrossChainDispatcher _crossChainDispatcher) {
        return pool.poolRegistry().crossChainDispatcher();
    }

    /***
     * @notice Cross-chain flash debt repayment
     * @dev Not calling `whenNotShutdown` here because nested function already does it
     * @param syntheticToken_ The debt token to repay
     * @param depositToken_ The collateral to withdraw
     * @param withdrawAmount_ The amount to withdraw
     * @param bridgeToken_ The asset that will be bridged out and used to swap for msAsset
     * @param bridgeTokenAmountMin_ The minimum amount out when converting collateral for bridgeToken if they aren't the same (slippage check)
     * @param swapAmountOutMin_ The minimum amount out from the bridgeToken->msAsset swap (slippage check)
     * @param repayAmountMin_ The minimum amount to repay (slippage check)
     * @param lzArgs_ The LayerZero params (See: `Quoter.getFlashRepaySwapAndCallbackLzArgs()`)
     */
    function crossChainFlashRepay(
        ISyntheticToken syntheticToken_,
        IDepositToken depositToken_,
        uint256 withdrawAmount_,
        IERC20 bridgeToken_,
        uint256 bridgeTokenAmountMin_,
        uint256 swapAmountOutMin_,
        uint256 repayAmountMin_,
        bytes calldata lzArgs_
    )
        external
        payable
        override
        nonReentrant
        onlyIfDepositTokenExists(depositToken_)
        onlyIfSyntheticTokenExists(syntheticToken_)
    {
        if (withdrawAmount_ == 0) revert AmountIsZero();
        if (!pool.poolRegistry().isCrossChainFlashRepayActive()) revert CrossChainFlashRepayInactive();

        ICrossChainDispatcher _crossChainDispatcher;
        {
            IDebtToken _debtToken = pool.debtTokenOf(syntheticToken_);
            _debtToken.accrueInterest();
            if (repayAmountMin_ > _debtToken.balanceOf(_msgSender())) revert AmountIsTooHigh();

            _crossChainDispatcher = crossChainDispatcher();
        }

        uint256 _amountIn;
        {
            // 1. withdraw collateral
            // Note: No need to check healthy because this function ensures withdrawing only from unlocked balance
            (_amountIn, ) = depositToken_.withdrawFrom(_msgSender(), withdrawAmount_);

            // 2. swap collateral for bridge token
            _amountIn = _swap({
                swapper_: swapper(),
                tokenIn_: _collateralOf(depositToken_),
                tokenOut_: bridgeToken_,
                amountIn_: _amountIn,
                amountOutMin_: bridgeTokenAmountMin_,
                to_: address(_crossChainDispatcher)
            });
        }

        // 3. store request and trigger swap
        _triggerFlashRepaySwap({
            crossChainDispatcher_: _crossChainDispatcher,
            swapTokenIn_: bridgeToken_,
            swapTokenOut_: syntheticToken_,
            swapAmountIn_: _amountIn,
            swapAmountOutMin_: swapAmountOutMin_,
            repayAmountMin_: repayAmountMin_,
            lzArgs_: lzArgs_
        });
    }

    /**
     * @dev Stores flash repay cross-chain request and triggers swap on the destination chain
     */
    function _triggerFlashRepaySwap(
        ICrossChainDispatcher crossChainDispatcher_,
        IERC20 swapTokenIn_,
        ISyntheticToken swapTokenOut_,
        uint256 swapAmountIn_,
        uint256 swapAmountOutMin_,
        uint256 repayAmountMin_,
        bytes calldata lzArgs_
    ) private {
        uint256 _id = _nextCrossChainRequestId();

        (uint16 _dstChainId, , ) = CrossChainLib.decodeLzArgs(lzArgs_);

        address _msgSender = _msgSender();

        crossChainFlashRepays[_id] = CrossChainFlashRepay({
            dstChainId: _dstChainId,
            syntheticToken: swapTokenOut_,
            repayAmountMin: repayAmountMin_,
            account: _msgSender,
            finished: false
        });

        crossChainDispatcher_.triggerFlashRepaySwap{value: msg.value}({
            id_: _id,
            account_: payable(_msgSender),
            tokenIn_: address(swapTokenIn_),
            tokenOut_: address(swapTokenOut_),
            amountIn_: swapAmountIn_,
            amountOutMin_: swapAmountOutMin_,
            lzArgs_: lzArgs_
        });

        emit CrossChainFlashRepayStarted(_id);
    }

    /**
     * @notice Finalize cross-chain flash debt repayment process
     * @dev Receives msAsset from L1 and use it to repay
     * @param id_ The id of the request
     * @param swapAmountOut_ The msAsset amount received from L1 swap
     * @return _repaid The debt amount repaid
     */
    function crossChainFlashRepayCallback(
        uint256 id_,
        uint256 swapAmountOut_
    ) external override whenNotShutdown nonReentrant onlyIfCrossChainDispatcher returns (uint256 _repaid) {
        CrossChainFlashRepay memory _request = crossChainFlashRepays[id_];

        if (_request.account == address(0)) revert CrossChainRequestInvalidKey();
        if (_request.finished) revert CrossChainRequestCompletedAlready();

        // 1. update state
        crossChainFlashRepays[id_].finished = true;

        // 2. transfer synthetic token
        swapAmountOut_ = _safeTransferFrom(_request.syntheticToken, _msgSender(), swapAmountOut_);

        // 3. repay debt
        IDebtToken _debtToken = pool.debtTokenOf(_request.syntheticToken);
        (uint256 _maxRepayAmount, ) = _debtToken.quoteRepayIn(_debtToken.balanceOf(_request.account));
        uint256 _repayAmount = Math.min(swapAmountOut_, _maxRepayAmount);
        if (_repayAmount > 0) (_repaid, ) = _debtToken.repay(_request.account, _repayAmount);
        if (_repaid < _request.repayAmountMin) revert FlashRepaySlippageTooHigh();

        // 4. refund synthetic token in excess
        if (swapAmountOut_ > _repayAmount) {
            _request.syntheticToken.safeTransfer(_request.account, swapAmountOut_ - _repayAmount);
        }

        emit CrossChainFlashRepayFinished(id_);
    }

    /***
     * @notice Cross-chain Leverage
     * @dev Not calling `whenNotShutdown` here because nested function already does it
     * @param tokenIn_ The token to transfer
     * @param syntheticToken_ The msAsset to mint
     * @param bridgeToken_ The asset that will be used to swap from msAsset and bridged back
     * @param depositToken_ The collateral to deposit
     * @param amountIn_ The amount to deposit
     * @param leverage_ The leverage X param (e.g. 1.5e18 for 1.5X)
     * @param swapAmountOutMin_ The minimum amount out from msAsset->bridgeToken swap (slippage check)
     * @param depositAmountMin_ The minimum final amount to deposit (slippage check)
     * @param lzArgs_ The LayerZero params (See: `Quoter.getLeverageSwapAndCallbackLzArgs()`)
     */
    function crossChainLeverage(
        IERC20 tokenIn_,
        ISyntheticToken syntheticToken_,
        IERC20 bridgeToken_,
        IDepositToken depositToken_,
        uint256 amountIn_,
        uint256 leverage_,
        uint256 swapAmountOutMin_,
        uint256 depositAmountMin_,
        bytes calldata lzArgs_
    )
        external
        payable
        override
        nonReentrant
        onlyIfDepositTokenExists(depositToken_)
        onlyIfSyntheticTokenExists(syntheticToken_)
    {
        IERC20 _tokenIn = tokenIn_; // stack too deep

        if (amountIn_ == 0) revert AmountIsZero();
        if (leverage_ <= 1e18) revert LeverageTooLow();
        if (leverage_ > uint256(1e18).wadDiv(1e18 - depositToken_.collateralFactor())) revert LeverageTooHigh();
        if (address(_tokenIn) == address(0)) revert TokenInIsNull();
        if (address(bridgeToken_) == address(0)) revert BridgeTokenIsNull();

        uint256 _debtAmount;
        uint256 _issued;
        {
            // 1. transfer tokenIn
            amountIn_ = _safeTransferFrom(_tokenIn, _msgSender(), amountIn_);

            // 2. mint synth
            _debtAmount = _calculateLeverageDebtAmount(_tokenIn, syntheticToken_, amountIn_, leverage_);
            (_issued, ) = pool.debtTokenOf(syntheticToken_).flashIssue(address(crossChainDispatcher()), _debtAmount);
        }

        bytes memory _swapArgs = abi.encode(syntheticToken_, bridgeToken_, _issued, swapAmountOutMin_); // stack too deep
        IDepositToken _depositToken = depositToken_; // stack too deep

        // 3. store request and trigger swap
        _triggerCrossChainLeverageSwap({
            tokenIn_: _tokenIn,
            amountIn_: amountIn_,
            debtAmount_: _debtAmount,
            swapArgs_: _swapArgs,
            depositToken_: _depositToken,
            depositAmountMin_: depositAmountMin_,
            lzArgs_: lzArgs_
        });
    }

    /**
     * @dev Stores leverage cross-chain request and triggers swap on the destination chain
     */
    function _triggerCrossChainLeverageSwap(
        IERC20 tokenIn_,
        uint256 amountIn_,
        uint256 debtAmount_,
        bytes memory swapArgs_,
        IDepositToken depositToken_,
        uint256 depositAmountMin_,
        bytes calldata lzArgs_
    ) private {
        uint256 _id = _nextCrossChainRequestId();

        (ISyntheticToken _swapTokenIn, IERC20 _swapTokenOut, uint256 _swapAmountIn, uint256 _swapAmountOutMin) = abi
            .decode(swapArgs_, (ISyntheticToken, IERC20, uint256, uint256));

        {
            (uint16 _dstChainId, , ) = CrossChainLib.decodeLzArgs(lzArgs_);

            crossChainLeverages[_id] = CrossChainLeverage({
                dstChainId: _dstChainId,
                tokenIn: tokenIn_,
                syntheticToken: _swapTokenIn,
                bridgeToken: _swapTokenOut,
                depositToken: depositToken_,
                amountIn: amountIn_,
                debtAmount: debtAmount_,
                depositAmountMin: depositAmountMin_,
                account: _msgSender(),
                finished: false
            });
        }

        crossChainDispatcher().triggerLeverageSwap{value: msg.value}({
            id_: _id,
            account_: payable(_msgSender()),
            tokenIn_: address(_swapTokenIn),
            tokenOut_: address(_swapTokenOut),
            amountIn_: _swapAmountIn,
            amountOutMin: _swapAmountOutMin,
            lzArgs_: lzArgs_
        });

        emit CrossChainLeverageStarted(_id);
    }

    /**
     * @notice Finalize cross-chain leverage process
     * @dev Receives bridged token (aka naked token) use it to deposit
     * @param id_ The id of the request
     * @param swapAmountOut_ The amount received from swap
     * @return _deposited The amount deposited
     */
    function crossChainLeverageCallback(
        uint256 id_,
        uint256 swapAmountOut_
    ) external override whenNotShutdown nonReentrant onlyIfCrossChainDispatcher returns (uint256 _deposited) {
        CrossChainLeverage memory _request = crossChainLeverages[id_];

        if (_request.account == address(0)) revert CrossChainRequestInvalidKey();
        if (_request.finished) revert CrossChainRequestCompletedAlready();
        IERC20 _collateral = _collateralOf(_request.depositToken);

        // 1. update state
        crossChainLeverages[id_].finished = true;

        // 2. transfer swap's tokenOut (aka bridged token)
        swapAmountOut_ = _safeTransferFrom(_request.bridgeToken, _msgSender(), swapAmountOut_);

        // 3. swap received tokens for collateral if needed
        // Note: The internal `_swap()` doesn't swap if `tokenIn` and `tokenOut` are the same
        uint256 _depositAmount;
        if (_request.tokenIn == _request.bridgeToken) {
            _depositAmount = _swap(swapper(), _request.tokenIn, _collateral, _request.amountIn + swapAmountOut_, 0);
        } else {
            ISwapper _swapper = swapper();
            _depositAmount = _swap(_swapper, _request.tokenIn, _collateral, _request.amountIn, 0);
            _depositAmount += _swap(_swapper, _request.bridgeToken, _collateral, swapAmountOut_, 0);
        }

        if (_depositAmount < _request.depositAmountMin) revert LeverageSlippageTooHigh();

        // 4. deposit collateral
        _collateral.safeApprove(address(_request.depositToken), 0);
        _collateral.safeApprove(address(_request.depositToken), _depositAmount);
        (_deposited, ) = _request.depositToken.deposit(_depositAmount, _request.account);

        // 5. mint debt
        IPool _pool = pool;
        _pool.debtTokenOf(_request.syntheticToken).mint(_request.account, _request.debtAmount);

        // 6. check the health of the outcome position
        (bool _isHealthy, , , , ) = _pool.debtPositionOf(_request.account);
        if (!_isHealthy) revert PositionIsNotHealthy();

        emit CrossChainLeverageFinished(id_);
    }

    /**
     * @notice Flash debt repayment
     * @param syntheticToken_ The debt token to repay
     * @param depositToken_ The collateral to withdraw
     * @param withdrawAmount_ The amount to withdraw
     * @param swapAmountOutMin_ The minimum amount to repay (slippage check)
     */
    function flashRepay(
        ISyntheticToken syntheticToken_,
        IDepositToken depositToken_,
        uint256 withdrawAmount_,
        uint256 swapAmountOutMin_
    )
        external
        override
        whenNotShutdown
        nonReentrant
        onlyIfDepositTokenExists(depositToken_)
        onlyIfSyntheticTokenExists(syntheticToken_)
        returns (uint256 _withdrawn, uint256 _repaid)
    {
        ISyntheticToken _syntheticToken = syntheticToken_; // stack too deep

        address _msgSender = _msgSender();
        if (withdrawAmount_ == 0) revert AmountIsZero();
        if (withdrawAmount_ > depositToken_.balanceOf(_msgSender)) revert AmountIsTooHigh();
        IPool _pool = pool;
        IDebtToken _debtToken = _pool.debtTokenOf(_syntheticToken);
        if (swapAmountOutMin_ > _debtToken.balanceOf(_msgSender)) revert AmountIsTooHigh();

        // 1. withdraw collateral
        (_withdrawn, ) = depositToken_.flashWithdraw(_msgSender, withdrawAmount_);

        // 2. swap it for synth
        uint256 _swapAmountOut = _swap(swapper(), _collateralOf(depositToken_), _syntheticToken, _withdrawn, 0);
        if (_swapAmountOut < swapAmountOutMin_) revert FlashRepaySlippageTooHigh();

        (uint256 _maxRepayAmount, ) = _debtToken.quoteRepayIn(_debtToken.balanceOf(_msgSender));
        uint256 _amountToRepay = Math.min(_swapAmountOut, _maxRepayAmount);

        // 3. repay debt
        (_repaid, ) = _debtToken.repay(_msgSender, _amountToRepay);

        // 4. refund synthetic token in excess
        if (_swapAmountOut > _amountToRepay) {
            _syntheticToken.safeTransfer(_msgSender, _swapAmountOut - _amountToRepay);
        }

        // 5. check the health of the outcome position
        (bool _isHealthy, , , , ) = _pool.debtPositionOf(_msgSender);
        if (!_isHealthy) revert PositionIsNotHealthy();

        emit FlashRepaid(_syntheticToken, depositToken_, _withdrawn, _repaid);
    }

    /**
     * @notice Leverage yield position
     * @param tokenIn_ The token to transfer
     * @param depositToken_ The collateral to deposit
     * @param syntheticToken_ The msAsset to mint
     * @param amountIn_ The amount to deposit
     * @param leverage_ The leverage X param (e.g. 1.5e18 for 1.5X)
     * @param depositAmountMin_ The min final deposit amount (slippage)
     */
    function leverage(
        IERC20 tokenIn_,
        IDepositToken depositToken_,
        ISyntheticToken syntheticToken_,
        uint256 amountIn_,
        uint256 leverage_,
        uint256 depositAmountMin_
    )
        external
        override
        whenNotShutdown
        nonReentrant
        onlyIfDepositTokenExists(depositToken_)
        onlyIfSyntheticTokenExists(syntheticToken_)
        returns (uint256 _deposited, uint256 _issued)
    {
        if (amountIn_ == 0) revert AmountIsZero();
        if (leverage_ <= 1e18) revert LeverageTooLow();
        if (leverage_ > uint256(1e18).wadDiv(1e18 - depositToken_.collateralFactor())) revert LeverageTooHigh();

        address _msgSender = _msgSender();
        ISwapper _swapper = swapper();

        // 1. transfer collateral
        IERC20 _collateral = _collateralOf(depositToken_);
        if (address(tokenIn_) == address(0)) tokenIn_ = _collateral;
        amountIn_ = _safeTransferFrom(tokenIn_, _msgSender, amountIn_);
        if (tokenIn_ != _collateral) {
            // Note: `amountOutMin_` is `0` because slippage will be checked later on
            amountIn_ = _swap(_swapper, tokenIn_, _collateral, amountIn_, 0);
        }

        {
            // 2. mint synth + debt
            uint256 _debtAmount = _calculateLeverageDebtAmount(_collateral, syntheticToken_, amountIn_, leverage_);
            IDebtToken _debtToken = pool.debtTokenOf(syntheticToken_);
            (_issued, ) = _debtToken.flashIssue(address(this), _debtAmount);
            _debtToken.mint(_msgSender, _debtAmount);
        }

        {
            // 3. swap synth for collateral
            uint256 _depositAmount = amountIn_ + _swap(_swapper, syntheticToken_, _collateral, _issued, 0);
            if (_depositAmount < depositAmountMin_) revert LeverageSlippageTooHigh();

            // 4. deposit collateral
            _collateral.safeApprove(address(depositToken_), 0);
            _collateral.safeApprove(address(depositToken_), _depositAmount);
            (_deposited, ) = depositToken_.deposit(_depositAmount, _msgSender);
        }

        // 5. check the health of the outcome position
        (bool _isHealthy, , , , ) = pool.debtPositionOf(_msgSender);
        if (!_isHealthy) revert PositionIsNotHealthy();

        emit Leveraged(tokenIn_, depositToken_, syntheticToken_, leverage_, amountIn_, _issued, _deposited);
    }

    /**
     * @notice Retry cross-chain flash repay callback
     * @dev This function is used to recover from callback failures due to slippage
     * @param srcChainId_ The source chain of failed tx
     * @param srcAddress_ The source path of failed tx
     * @param nonce_ The nonce of failed tx
     * @param amount_ The amount of failed tx
     * @param payload_ The payload of failed tx
     * @param newRepayAmountMin_ If repayment failed due to slippage, caller may send lower newRepayAmountMin_
     */
    function retryCrossChainFlashRepayCallback(
        uint16 srcChainId_,
        bytes calldata srcAddress_,
        uint64 nonce_,
        uint256 amount_,
        bytes calldata payload_,
        uint256 newRepayAmountMin_
    ) external {
        (, , uint256 _requestId) = CrossChainLib.decodeFlashRepayCallbackPayload(payload_);

        CrossChainFlashRepay memory _request = crossChainFlashRepays[_requestId];

        if (_request.account == address(0)) revert CrossChainRequestInvalidKey();
        if (_request.finished) revert CrossChainRequestCompletedAlready();

        // Note: Only user can change slippage param
        if (_msgSender() == _request.account) {
            crossChainFlashRepays[_requestId].repayAmountMin = newRepayAmountMin_;
        }

        ICrossChainDispatcher _crossChainDispatcher = crossChainDispatcher();
        bytes memory _from = abi.encodePacked(_crossChainDispatcher.crossChainDispatcherOf(srcChainId_));

        _request.syntheticToken.proxyOFT().retryOFTReceived({
            _srcChainId: srcChainId_,
            _srcAddress: srcAddress_,
            _nonce: nonce_,
            _from: _from,
            _to: address(_crossChainDispatcher),
            _amount: amount_,
            _payload: payload_
        });
    }

    /**
     * @notice Retry cross-chain leverage callback
     * @dev This function is used to recover from callback failures due to slippage
     * @param srcChainId_ The source chain of failed tx
     * @param srcAddress_ The source path of failed tx
     * @param nonce_ The nonce of failed tx
     * @param token_ The token of failed tx
     * @param amount_ The amountIn of failed tx
     * @param payload_ The payload of failed tx
     * @param newDepositAmountMin_ If deposit failed due to slippage, caller may send lower newDepositAmountMin_
     */
    function retryCrossChainLeverageCallback(
        uint16 srcChainId_,
        bytes calldata srcAddress_,
        uint64 nonce_,
        address token_,
        uint256 amount_,
        bytes calldata payload_,
        uint256 newDepositAmountMin_
    ) external {
        (, uint256 _requestId) = CrossChainLib.decodeLeverageCallbackPayload(payload_);

        CrossChainLeverage memory _request = crossChainLeverages[_requestId];

        if (_request.account == address(0)) revert CrossChainRequestInvalidKey();
        if (_request.finished) revert CrossChainRequestCompletedAlready();

        // Note: Only user can change slippage param
        if (_msgSender() == _request.account) {
            crossChainLeverages[_requestId].depositAmountMin = newDepositAmountMin_;
        }

        ICrossChainDispatcher _crossChainDispatcher = crossChainDispatcher();

        address _from = _crossChainDispatcher.crossChainDispatcherOf(srcChainId_);
        bytes memory _sgReceiveCallData = abi.encodeWithSelector(
            IStargateReceiver.sgReceive.selector,
            srcChainId_,
            abi.encodePacked(_from),
            nonce_,
            token_,
            amount_,
            payload_
        );

        _crossChainDispatcher.stargateComposer().clearCachedSwap(
            srcChainId_,
            srcAddress_,
            nonce_,
            address(_crossChainDispatcher),
            _sgReceiveCallData
        );
    }

    /**
     * @notice Get the swapper contract
     */
    function swapper() public view returns (ISwapper _swapper) {
        return pool.poolRegistry().swapper();
    }

    /**
     * @notice Calculate debt to issue for a leverage operation
     * @param collateral_ The collateral to deposit
     * @param syntheticToken_ The msAsset to mint
     * @param amountIn_ The amount to deposit
     * @param leverage_ The leverage X param (e.g. 1.5e18 for 1.5X)
     * @return _debtAmount The debt issue
     */
    function _calculateLeverageDebtAmount(
        IERC20 collateral_,
        ISyntheticToken syntheticToken_,
        uint256 amountIn_,
        uint256 leverage_
    ) private view returns (uint256 _debtAmount) {
        return
            pool.masterOracle().quote(
                address(collateral_),
                address(syntheticToken_),
                (leverage_ - 1e18).wadMul(amountIn_)
            );
    }

    /**
     * @dev `collateral` is a better name than `underlying`
     * See more: https://github.com/autonomoussoftware/metronome-synth/issues/905
     */
    function _collateralOf(IDepositToken depositToken_) private view returns (IERC20) {
        return depositToken_.underlying();
    }

    /**
     * @dev Generates cross-chain request id by hashing `chainId`+`requestId` in order to avoid
     * having same id across supported chains
     * Note: The cross-chain code mostly uses LZ chain ids but in this case, we're using native id.
     */
    function _nextCrossChainRequestId() private returns (uint256 _id) {
        return uint256(keccak256(abi.encode(block.chainid, address(this), ++crossChainRequestsLength)));
    }

    /**
     * @notice Transfer token and check actual amount transferred
     * @param token_ The token to transfer
     * @param from_ The account to get tokens from
     * @param amount_ The amount to transfer
     * @return _transferred The actual transferred amount
     */
    function _safeTransferFrom(IERC20 token_, address from_, uint256 amount_) private returns (uint256 _transferred) {
        uint256 _before = token_.balanceOf(address(this));
        token_.safeTransferFrom(from_, address(this), amount_);
        return token_.balanceOf(address(this)) - _before;
    }

    /**
     * @notice Swap assets using Swapper contract
     * @dev Use `address(this)` as amount out receiver
     * @param swapper_ The Swapper contract
     * @param tokenIn_ The token to swap from
     * @param tokenOut_ The token to swap to
     * @param amountIn_ The amount in
     * @param amountOutMin_ The minimum amount out (slippage check)
     * @return _amountOut The actual amount out
     */
    function _swap(
        ISwapper swapper_,
        IERC20 tokenIn_,
        IERC20 tokenOut_,
        uint256 amountIn_,
        uint256 amountOutMin_
    ) private returns (uint256 _amountOut) {
        return _swap(swapper_, tokenIn_, tokenOut_, amountIn_, amountOutMin_, address(this));
    }

    /**
     * @notice Swap assets using Swapper contract
     * @param swapper_ The Swapper contract
     * @param tokenIn_ The token to swap from
     * @param tokenOut_ The token to swap to
     * @param amountIn_ The amount in
     * @param amountOutMin_ The minimum amount out (slippage check)
     * @param to_ The amount out receiver
     * @return _amountOut The actual amount out
     */
    function _swap(
        ISwapper swapper_,
        IERC20 tokenIn_,
        IERC20 tokenOut_,
        uint256 amountIn_,
        uint256 amountOutMin_,
        address to_
    ) private returns (uint256 _amountOut) {
        if (tokenIn_ != tokenOut_) {
            tokenIn_.safeApprove(address(swapper_), 0);
            tokenIn_.safeApprove(address(swapper_), amountIn_);
            uint256 _tokenOutBefore = tokenOut_.balanceOf(to_);
            swapper_.swapExactInput(address(tokenIn_), address(tokenOut_), amountIn_, amountOutMin_, to_);
            return tokenOut_.balanceOf(to_) - _tokenOutBefore;
        } else if (to_ != address(this)) {
            tokenIn_.safeTransfer(to_, amountIn_);
        }
        return amountIn_;
    }
}
"
    },
    "contracts/access/Manageable.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import {Initializable} from "../dependencies/openzeppelin-upgradeable/proxy/utils/Initializable.sol";
import {SynthContext} from "../utils/SynthContext.sol";
import {IGovernable} from "../interfaces/IGovernable.sol";
import {IManageable} from "../interfaces/IManageable.sol";
import {IPool} from "../interfaces/IPool.sol";
import {IPoolRegistry} from "../interfaces/IPoolRegistry.sol";

error SenderIsNotPool();
error SenderIsNotGovernor();
error IsPaused();
error IsShutdown();
error PoolAddressIsNull();

/**
 * @title Reusable contract that handles accesses
 */
abstract contract Manageable is IManageable, SynthContext, Initializable {
    /**
     * @notice Pool contract
     */
    IPool public pool;

    /**
     * @dev Throws if `_msgSender()` isn't the pool
     */
    modifier onlyPool() {
        if (_msgSender() != address(pool)) revert SenderIsNotPool();
        _;
    }

    /**
     * @dev Throws if `_msgSender()` isn't the governor
     */
    modifier onlyGovernor() {
        if (_msgSender() != governor()) revert SenderIsNotGovernor();
        _;
    }

    /**
     * @dev Throws if contract is paused
     */
    modifier whenNotPaused() {
        if (pool.paused()) revert IsPaused();
        _;
    }

    /**
     * @dev Throws if contract is shutdown
     */
    modifier whenNotShutdown() {
        if (pool.everythingStopped()) revert IsShutdown();
        _;
    }

    // solhint-disable-next-line func-name-mixedcase
    function __Manageable_init(IPool pool_) internal onlyInitializing {
        if (address(pool_) == address(0)) revert PoolAddressIsNull();
        pool = pool_;
    }

    /**
     * @notice Get the governor
     * @return _governor The governor
     */
    function governor() public view returns (address _governor) {
        _governor = IGovernable(address(pool)).governor();
    }

    /// @inheritdoc SynthContext
    function poolRegistry() public view override returns (IPoolRegistry) {
        return pool.poolRegistry();
    }

    uint256[49] private __gap;
}
"
    },
    "contracts/dependencies/@layerzerolabs/solidity-examples/contracts-upgradeable/token/oft/IOFTCoreUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.2;

import "../../../../../openzeppelin-upgradeable/utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Interface of the IOFT core standard
 */
interface IOFTCoreUpgradeable is IERC165Upgradeable {
    /**
     * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
     * _dstChainId - L0 defined chain id to send tokens too
     * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
     * _amount - amount of the tokens to transfer
     * _useZro - indicates to use zro to pay L0 fees
     * _adapterParam - flexible bytes array to indicate messaging adapter services in L0
     */
    function estimateSendFee(
        uint16 _dstChainId,
        bytes calldata _toAddress,
        uint _amount,
        bool _useZro,
        bytes calldata _adapterParams
    ) external view returns (uint nativeFee, uint zroFee);

    /**
     * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
     * `_from` the owner of token
     * `_dstChainId` the destination chain identifier
     * `_toAddress` can be any size depending on the `dstChainId`.
     * `_amount` the quantity of tokens in wei
     * `_refundAddress` the address LayerZero refunds if too much message fee is sent
     * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
     * `_adapterParams` is a flexible bytes array to indicate messaging adapter services
     */
    function sendFrom(
        address _from,
        uint16 _dstChainId,
        bytes calldata _toAddress,
        uint _amount,
        address payable _refundAddress,
        address _zroPaymentAddress,
        bytes calldata _adapterParams
    ) external payable;

    /**
     * @dev returns the circulating amount of tokens on current chain
     */
    function circulatingSupply() external view returns (uint);

    /**
     * @dev returns the address of the ERC20 token
     */
    function token() external view returns (address);

    /**
     * @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`)
     * `_nonce` is the outbound nonce
     */
    event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint _amount);

    /**
     * @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain.
     * `_nonce` is the inbound nonce.
     */
    event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint _amount);

    event SetUseCustomAdapterParams(bool _useCustomAdapterParams);
}
"
    },
    "contracts/dependencies/@layerzerolabs/solidity-examples/contracts-upgradeable/token/oft/composable/IComposableOFTCoreUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity >=0.5.0;

import "../IOFTCoreUpgradeable.sol";

/**
 * @dev Interface of the composable OFT core standard
 */
interface IComposableOFTCoreUpgradeable is IOFTCoreUpgradeable {
    function estimateSendAndCallFee(
        uint16 _dstChainId,
        bytes calldata _toAddress,
        uint _amount,
        bytes calldata _payload,
        uint64 _dstGasForCall,
        bool _useZro,
        bytes calldata _adapterParams
    ) external view returns (uint nativeFee, uint zroFee);

    function sendAndCall(
        address _from,
        uint16 _dstChainId,
        bytes calldata _toAddress,
        uint _amount,
        bytes calldata _payload,
        uint64 _dstGasForCall,
        address payable _refundAddress,
        address _zroPaymentAddress,
        bytes calldata _adapterParams
    ) external payable;

    function retryOFTReceived(
        uint16 _srcChainId,
        bytes calldata _srcAddress,
        uint64 _nonce,
        bytes calldata _from,
        address _to,
        uint _amount,
        bytes calldata _payload
    ) external;

    event CallOFTReceivedFailure(
        uint16 indexed _srcChainId,
        bytes _srcAddress,
        uint64 _nonce,
        bytes _from,
        address indexed _to,
        uint _amount,
        bytes _payload,
        bytes _reason
    );

    event CallOFTReceivedSuccess(uint16 indexed _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _hash);

    event RetryOFTReceivedSuccess(bytes32 _messageHash);

    event NonContractAddress(address _address);
}
"
    },
    "contracts/dependencies/@layerzerolabs/solidity-examples/contracts-upgradeable/token/oft/composable/IOFTReceiverUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity >=0.5.0;

interface IOFTReceiverUpgradeable {
    /**
     * @dev Called by the OFT contract when tokens are received from source chain.
     * @param _srcChainId The chain id of the source chain.
     * @param _srcAddress The address of the OFT token contract on the source chain.
     * @param _nonce The nonce of the transaction on the source chain.
     * @param _from The address of the account who calls the sendAndCall() on the source chain.
     * @param _amount The amount of tokens to transfer.
     * @param _payload Additional data with no specified format.
     */
    function onOFTReceived(
        uint16 _srcChainId,
        bytes calldata _srcAddress,
        uint64 _nonce,
        bytes calldata _from,
        uint _amount,
        bytes calldata _payload
    ) external;
}
"
    },
    "contracts/dependencies/openzeppelin-upgradeable/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = _setInitializedVersion(1);
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
     * initialization step. This is essential to configure modules that are added through upgrades and that require
     * initialization.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     */
    modifier reinitializer(uint8 version) {
        bool isTopLevelCall = _setInitializedVersion(version);
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(version);
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     */
    function _disableInitializers() internal virtual {
        _setInitializedVersion(type(uint8).max);
    }

    function _setInitializedVersion(uint8 version) private returns (bool) {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
        // of initializers, because in other contexts the contract may have been reentered.
        if (_initializing) {
            require(
                version == 1 && !AddressUpgradeable.isContract(address(this)),
                "Initializable: contract is already initialized"
            );
            return false;
        } else {
            require(_initialized < version, "Initializable: contract is already initialized");
            _initialized = version;
            return true;
        }
    }
}
"
    },
    "contracts/dependencies/openzeppelin-upgradeable/utils/AddressUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
"
    },
    "contracts/dependencies/openzeppelin-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}
"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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);
}
"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../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;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @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, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
"
    },
    "contracts/dependencies/openzeppelin/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirem

Tags:
ERC20, ERC165, Proxy, Mintable, Burnable, Swap, Yield, Upgradeable, Factory|addr:0xb8d187ce5c5b172984cd1544d1679eacaf107aec|verified:true|block:23726548|tx:0x52d6b0bd6634d9e67f3d38c9d2581324007d951cfb67606a4c1097932b72a98e|first_check:1762270086

Submitted on: 2025-11-04 16:28:08

Comments

Log in to comment.

No comments yet.