File size: 87,023 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
{
  "language": "Solidity",
  "settings": {
    "evmVersion": "london",
    "libraries": {},
    "metadata": {
      "bytecodeHash": "ipfs",
      "useLiteralContent": true
    },
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  },
  "sources": {
    "contracts/Pool.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"./dependencies/openzeppelin/security/ReentrancyGuard.sol\";\nimport \"./storage/PoolStorage.sol\";\nimport \"./lib/WadRayMath.sol\";\nimport \"./utils/Pauseable.sol\";\n\n/**\n * @title Pool contract\n */\ncontract Pool is ReentrancyGuard, Pauseable, PoolStorageV1 {\n    using SafeERC20 for IERC20;\n    using WadRayMath for uint256;\n    using EnumerableSet for EnumerableSet.AddressSet;\n    using MappedEnumerableSet for MappedEnumerableSet.AddressSet;\n\n    string public constant VERSION = \"1.0.0\";\n\n    /// @notice Emitted when protocol liquidation fee is updated\n    event DebtFloorUpdated(uint256 oldDebtFloorInUsd, uint256 newDebtFloorInUsd);\n\n    /// @notice Emitted when debt token is enabled\n    event DebtTokenAdded(IDebtToken indexed debtToken);\n\n    /// @notice Emitted when debt token is disabled\n    event DebtTokenRemoved(IDebtToken indexed debtToken);\n\n    /// @notice Emitted when deposit fee is updated\n    event DepositFeeUpdated(uint256 oldDepositFee, uint256 newDepositFee);\n\n    /// @notice Emitted when deposit token is enabled\n    event DepositTokenAdded(address indexed depositToken);\n\n    /// @notice Emitted when deposit token is disabled\n    event DepositTokenRemoved(IDepositToken indexed depositToken);\n\n    /// @notice Emitted when issue fee is updated\n    event IssueFeeUpdated(uint256 oldIssueFee, uint256 newIssueFee);\n\n    /// @notice Emitted when liquidator liquidation fee is updated\n    event LiquidatorLiquidationFeeUpdated(uint256 oldLiquidatorLiquidationFee, uint256 newLiquidatorLiquidationFee);\n\n    /// @notice Emitted when maxLiquidable (liquidation cap) is updated\n    event MaxLiquidableUpdated(uint256 oldMaxLiquidable, uint256 newMaxLiquidable);\n\n    /// @notice Emitted when a position is liquidated\n    event PositionLiquidated(\n        address indexed liquidator,\n        address indexed account,\n        ISyntheticToken indexed syntheticToken,\n        uint256 amountRepaid,\n        uint256 depositSeized,\n        uint256 fee\n    );\n\n    /// @notice Emitted when protocol liquidation fee is updated\n    event ProtocolLiquidationFeeUpdated(uint256 oldProtocolLiquidationFee, uint256 newProtocolLiquidationFee);\n\n    /// @notice Emitted when repay fee is updated\n    event RepayFeeUpdated(uint256 oldRepayFee, uint256 newRepayFee);\n\n    /// @notice Emitted when rewards distributor contract is added\n    event RewardsDistributorAdded(IRewardsDistributor _distributor);\n\n    /// @notice Emitted when rewards distributor contract is removed\n    event RewardsDistributorRemoved(IRewardsDistributor _distributor);\n\n    /// @notice Emitted when swap fee is updated\n    event SwapFeeUpdated(uint256 oldSwapFee, uint256 newSwapFee);\n\n    /// @notice Emitted when the swap active flag is updated\n    event SwapActiveUpdated(bool newActive);\n\n    /// @notice Emitted when synthetic token is swapped\n    event SyntheticTokenSwapped(\n        address indexed account,\n        ISyntheticToken indexed syntheticTokenIn,\n        ISyntheticToken indexed syntheticTokenOut,\n        uint256 amountIn,\n        uint256 amountOut,\n        uint256 fee\n    );\n\n    /// @notice Emitted when treasury contract is updated\n    event TreasuryUpdated(ITreasury indexed oldTreasury, ITreasury indexed newTreasury);\n\n    /// @notice Emitted when withdraw fee is updated\n    event WithdrawFeeUpdated(uint256 oldWithdrawFee, uint256 newWithdrawFee);\n\n    /**\n     * @dev Throws if deposit token doesn't exist\n     */\n    modifier onlyIfDepositTokenExists(IDepositToken depositToken_) {\n        require(isDepositTokenExists(depositToken_), \"collateral-inexistent\");\n        _;\n    }\n\n    /**\n     * @dev Throws if synthetic token doesn't exist\n     */\n    modifier onlyIfSyntheticTokenExists(ISyntheticToken syntheticToken_) {\n        require(isSyntheticTokenExists(syntheticToken_), \"synthetic-inexistent\");\n        _;\n    }\n\n    /**\n     * @dev Throws if `msg.sender` isn't a debt token\n     */\n    modifier onlyIfMsgSenderIsDebtToken() {\n        require(isDebtTokenExists(IDebtToken(msg.sender)), \"caller-is-not-debt-token\");\n        _;\n    }\n\n    function initialize(IPoolRegistry poolRegistry_) public initializer {\n        require(address(poolRegistry_) != address(0), \"pool-registry-is-null\");\n        __ReentrancyGuard_init();\n        __Pauseable_init();\n\n        poolRegistry = poolRegistry_;\n        isSwapActive = true;\n\n        repayFee = 3e15; // 0.3%\n        liquidationFees = LiquidationFees({\n            liquidatorFee: 1e17, // 10%\n            protocolFee: 8e16 // 8%\n        });\n        maxLiquidable = 0.5e18; // 50%\n        swapFee = 6e15; // 0.6%\n    }\n\n    /**\n     * @notice Add a debt token to the per-account list\n     * @dev This function is called from `DebtToken` when user's balance changes from `0`\n     * @dev The caller should ensure to not pass `address(0)` as `_account`\n     * @param account_ The account address\n     */\n    function addToDebtTokensOfAccount(address account_) external onlyIfMsgSenderIsDebtToken {\n        require(debtTokensOfAccount.add(account_, msg.sender), \"debt-token-exists\");\n    }\n\n    /**\n     * @notice Add a deposit token to the per-account list\n     * @dev This function is called from `DepositToken` when user's balance changes from `0`\n     * @dev The caller should ensure to not pass `address(0)` as `_account`\n     * @param account_ The account address\n     */\n    function addToDepositTokensOfAccount(address account_) external {\n        require(depositTokens.contains(msg.sender), \"caller-is-not-deposit-token\");\n        require(depositTokensOfAccount.add(account_, msg.sender), \"deposit-token-exists\");\n    }\n\n    /**\n     * @notice Get account's debt by querying latest prices from oracles\n     * @param account_ The account to check\n     * @return _debtInUsd The debt value in USD\n     */\n    function debtOf(address account_) public view override returns (uint256 _debtInUsd) {\n        IMasterOracle _masterOracle = masterOracle();\n        uint256 _length = debtTokensOfAccount.length(account_);\n        for (uint256 i; i < _length; ++i) {\n            IDebtToken _debtToken = IDebtToken(debtTokensOfAccount.at(account_, i));\n            _debtInUsd += _masterOracle.quoteTokenToUsd(\n                address(_debtToken.syntheticToken()),\n                _debtToken.balanceOf(account_)\n            );\n        }\n    }\n\n    /**\n     * @notice Get if the debt position from an account is healthy\n     * @param account_ The account to check\n     * @return _isHealthy Whether the account's position is healthy\n     * @return _depositInUsd The total collateral deposited in USD\n     * @return _debtInUsd The total debt in USD\n     * @return _issuableLimitInUsd The max amount of debt (is USD) that can be created (considering collateralization ratios)\n     * @return _issuableInUsd The amount of debt (is USD) that is free (i.e. can be used to issue synthetic tokens)\n     */\n    function debtPositionOf(address account_)\n        public\n        view\n        override\n        returns (\n            bool _isHealthy,\n            uint256 _depositInUsd,\n            uint256 _debtInUsd,\n            uint256 _issuableLimitInUsd,\n            uint256 _issuableInUsd\n        )\n    {\n        _debtInUsd = debtOf(account_);\n        (_depositInUsd, _issuableLimitInUsd) = depositOf(account_);\n        _isHealthy = _debtInUsd <= _issuableLimitInUsd;\n        _issuableInUsd = _debtInUsd < _issuableLimitInUsd ? _issuableLimitInUsd - _debtInUsd : 0;\n    }\n\n    /**\n     * @notice Get account's total collateral deposited by querying latest prices from oracles\n     * @param account_ The account to check\n     * @return _depositInUsd The total deposit value in USD among all collaterals\n     * @return _issuableLimitInUsd The max value in USD that can be used to issue synthetic tokens\n     */\n    function depositOf(address account_)\n        public\n        view\n        override\n        returns (uint256 _depositInUsd, uint256 _issuableLimitInUsd)\n    {\n        IMasterOracle _masterOracle = masterOracle();\n        uint256 _length = depositTokensOfAccount.length(account_);\n        for (uint256 i; i < _length; ++i) {\n            IDepositToken _depositToken = IDepositToken(depositTokensOfAccount.at(account_, i));\n            uint256 _amountInUsd = _masterOracle.quoteTokenToUsd(\n                address(_depositToken.underlying()),\n                _depositToken.balanceOf(account_)\n            );\n            _depositInUsd += _amountInUsd;\n            _issuableLimitInUsd += _amountInUsd.wadMul(_depositToken.collateralizationRatio());\n        }\n    }\n\n    /**\n     * @inheritdoc Pauseable\n     */\n    function everythingStopped() public view override(IPauseable, Pauseable) returns (bool) {\n        return super.everythingStopped() || poolRegistry.everythingStopped();\n    }\n\n    /**\n     * @notice Returns fee collector address\n     */\n    function feeCollector() external view returns (address) {\n        return poolRegistry.feeCollector();\n    }\n\n    /**\n     * @notice Get all debt tokens\n     * @dev WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees.\n     */\n    function getDebtTokens() external view override returns (address[] memory) {\n        return debtTokens.values();\n    }\n\n    /**\n     * @notice Get all debt tokens\n     * @dev WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees.\n     */\n    function getDebtTokensOfAccount(address account_) external view override returns (address[] memory) {\n        return debtTokensOfAccount.values(account_);\n    }\n\n    /**\n     * @notice Get all deposit tokens\n     * @dev WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees.\n     */\n    function getDepositTokens() external view override returns (address[] memory) {\n        return depositTokens.values();\n    }\n\n    /**\n     * @notice Get deposit tokens of an account\n     * @dev WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees.\n     */\n    function getDepositTokensOfAccount(address account_) external view override returns (address[] memory) {\n        return depositTokensOfAccount.values(account_);\n    }\n\n    /**\n     * @notice Get all rewards distributors\n     */\n    function getRewardsDistributors() external view override returns (IRewardsDistributor[] memory) {\n        return rewardsDistributors;\n    }\n\n    /**\n     * @notice Check if token is part of the debt offerings\n     * @param debtToken_ Asset to check\n     * @return true if exist\n     */\n    function isDebtTokenExists(IDebtToken debtToken_) public view override returns (bool) {\n        return debtTokens.contains(address(debtToken_));\n    }\n\n    /**\n     * @notice Check if collateral is supported\n     * @param depositToken_ Asset to check\n     * @return true if exist\n     */\n    function isDepositTokenExists(IDepositToken depositToken_) public view override returns (bool) {\n        return depositTokens.contains(address(depositToken_));\n    }\n\n    /**\n     * @notice Check if token is part of the synthetic offerings\n     * @param syntheticToken_ Asset to check\n     * @return true if exist\n     */\n    function isSyntheticTokenExists(ISyntheticToken syntheticToken_) public view override returns (bool) {\n        return address(debtTokenOf[syntheticToken_]) != address(0);\n    }\n\n    /**\n     * @notice Burn synthetic token, unlock deposit token and send liquidator liquidation fee\n     * @param syntheticToken_ The msAsset to use for repayment\n     * @param account_ The account with an unhealthy position\n     * @param amountToRepay_ The amount to repay in synthetic token\n     * @param depositToken_ The collateral to seize from\n     */\n    function liquidate(\n        ISyntheticToken syntheticToken_,\n        address account_,\n        uint256 amountToRepay_,\n        IDepositToken depositToken_\n    ) external override whenNotShutdown nonReentrant onlyIfDepositTokenExists(depositToken_) {\n        require(amountToRepay_ > 0, \"amount-is-zero\");\n        require(msg.sender != account_, \"can-not-liquidate-own-position\");\n\n        IDebtToken _debtToken = debtTokenOf[syntheticToken_];\n        _debtToken.accrueInterest();\n\n        (bool _isHealthy, , , , ) = debtPositionOf(account_);\n\n        require(!_isHealthy, \"position-is-healthy\");\n\n        uint256 _debtTokenBalance = _debtToken.balanceOf(account_);\n\n        require(amountToRepay_.wadDiv(_debtTokenBalance) <= maxLiquidable, \"amount-gt-max-liquidable\");\n\n        IMasterOracle _masterOracle = masterOracle();\n\n        if (debtFloorInUsd > 0) {\n            uint256 _newDebtInUsd = _masterOracle.quoteTokenToUsd(\n                address(syntheticToken_),\n                _debtTokenBalance - amountToRepay_\n            );\n            require(_newDebtInUsd == 0 || _newDebtInUsd >= debtFloorInUsd, \"remaining-debt-lt-floor\");\n        }\n\n        uint256 _amountToRepayInCollateral = _masterOracle.quote(\n            address(syntheticToken_),\n            address(depositToken_.underlying()),\n            amountToRepay_\n        );\n\n        LiquidationFees memory _fees = liquidationFees;\n\n        uint256 _toProtocol = _fees.protocolFee > 0 ? _amountToRepayInCollateral.wadMul(_fees.protocolFee) : 0;\n        uint256 _toLiquidator = _amountToRepayInCollateral.wadMul(1e18 + _fees.liquidatorFee);\n        uint256 _depositToSeize = _toProtocol + _toLiquidator;\n\n        require(_depositToSeize <= depositToken_.balanceOf(account_), \"amount-too-high\");\n\n        syntheticToken_.burn(msg.sender, amountToRepay_);\n        _debtToken.burn(account_, amountToRepay_);\n        depositToken_.seize(account_, msg.sender, _toLiquidator);\n\n        if (_toProtocol > 0) {\n            depositToken_.seize(account_, poolRegistry.feeCollector(), _toProtocol);\n        }\n\n        emit PositionLiquidated(msg.sender, account_, syntheticToken_, amountToRepay_, _depositToSeize, _toProtocol);\n    }\n\n    /**\n     * @notice Get MasterOracle contract\n     */\n    function masterOracle() public view override returns (IMasterOracle) {\n        return poolRegistry.masterOracle();\n    }\n\n    /**\n     * @inheritdoc Pauseable\n     */\n    function paused() public view override(IPauseable, Pauseable) returns (bool) {\n        return super.paused() || poolRegistry.paused();\n    }\n\n    /**\n     * @notice Remove a debt token from the per-account list\n     * @dev This function is called from `DebtToken` when user's balance changes to `0`\n     * @dev The caller should ensure to not pass `address(0)` as `_account`\n     * @param account_ The account address\n     */\n    function removeFromDebtTokensOfAccount(address account_) external onlyIfMsgSenderIsDebtToken {\n        require(debtTokensOfAccount.remove(account_, msg.sender), \"debt-token-doesnt-exist\");\n    }\n\n    /**\n     * @notice Remove a deposit token from the per-account list\n     * @dev This function is called from `DepositToken` when user's balance changes to `0`\n     * @dev The caller should ensure to not pass `address(0)` as `_account`\n     * @param account_ The account address\n     */\n    function removeFromDepositTokensOfAccount(address account_) external {\n        require(depositTokens.contains(msg.sender), \"caller-is-not-deposit-token\");\n        require(depositTokensOfAccount.remove(account_, msg.sender), \"deposit-token-doesnt-exist\");\n    }\n\n    /**\n     * @notice Swap synthetic tokens\n     * @param syntheticTokenIn_ Synthetic token to sell\n     * @param syntheticTokenOut_ Synthetic token to buy\n     * @param amountIn_ Amount to swap\n     */\n    function swap(\n        ISyntheticToken syntheticTokenIn_,\n        ISyntheticToken syntheticTokenOut_,\n        uint256 amountIn_\n    )\n        external\n        override\n        whenNotShutdown\n        nonReentrant\n        onlyIfSyntheticTokenExists(syntheticTokenIn_)\n        onlyIfSyntheticTokenExists(syntheticTokenOut_)\n        returns (uint256 _amountOut)\n    {\n        require(isSwapActive, \"swap-is-off\");\n        require(amountIn_ > 0 && amountIn_ <= syntheticTokenIn_.balanceOf(msg.sender), \"amount-in-is-invalid\");\n        syntheticTokenIn_.burn(msg.sender, amountIn_);\n\n        _amountOut = poolRegistry.masterOracle().quote(\n            address(syntheticTokenIn_),\n            address(syntheticTokenOut_),\n            amountIn_\n        );\n\n        uint256 _feeAmount;\n        if (swapFee > 0) {\n            _feeAmount = _amountOut.wadMul(swapFee);\n            syntheticTokenOut_.mint(poolRegistry.feeCollector(), _feeAmount);\n            _amountOut -= _feeAmount;\n        }\n\n        syntheticTokenOut_.mint(msg.sender, _amountOut);\n\n        emit SyntheticTokenSwapped(\n            msg.sender,\n            syntheticTokenIn_,\n            syntheticTokenOut_,\n            amountIn_,\n            _amountOut,\n            _feeAmount\n        );\n    }\n\n    /**\n     * @notice Add debt token to offerings\n     * @dev Must keep `debtTokenOf` mapping updated\n     */\n    function addDebtToken(IDebtToken debtToken_) external override onlyGovernor {\n        require(address(debtToken_) != address(0), \"address-is-null\");\n        ISyntheticToken _syntheticToken = debtToken_.syntheticToken();\n        require(address(_syntheticToken) != address(0), \"synthetic-is-null\");\n        require(address(debtTokenOf[_syntheticToken]) == address(0), \"synth-in-use\");\n\n        require(debtTokens.add(address(debtToken_)), \"debt-exists\");\n\n        debtTokenOf[_syntheticToken] = debtToken_;\n\n        emit DebtTokenAdded(debtToken_);\n    }\n\n    /**\n     * @notice Add deposit token (i.e. collateral) to Synth\n     */\n    function addDepositToken(address depositToken_) external override onlyGovernor {\n        require(depositToken_ != address(0), \"address-is-null\");\n        IERC20 _underlying = IDepositToken(depositToken_).underlying();\n        require(address(depositTokenOf[_underlying]) == address(0), \"underlying-in-use\");\n\n        require(depositTokens.add(depositToken_), \"deposit-token-exists\");\n\n        depositTokenOf[_underlying] = IDepositToken(depositToken_);\n\n        emit DepositTokenAdded(depositToken_);\n    }\n\n    /**\n     * @notice Add a RewardsDistributor contract\n     */\n    function addRewardsDistributor(IRewardsDistributor distributor_) external override onlyGovernor {\n        require(address(distributor_) != address(0), \"address-is-null\");\n\n        uint256 _length = rewardsDistributors.length;\n        for (uint256 i; i < _length; ++i) {\n            require(distributor_ != rewardsDistributors[i], \"contract-already-added\");\n        }\n\n        rewardsDistributors.push(distributor_);\n        emit RewardsDistributorAdded(distributor_);\n    }\n\n    /**\n     * @notice Remove debt token from offerings\n     * @dev Must keep `debtTokenOf` mapping updated\n     */\n    function removeDebtToken(IDebtToken debtToken_) external override onlyGovernor {\n        require(debtToken_.totalSupply() == 0, \"supply-gt-0\");\n        require(debtTokens.remove(address(debtToken_)), \"debt-doesnt-exist\");\n\n        delete debtTokenOf[debtToken_.syntheticToken()];\n\n        emit DebtTokenRemoved(debtToken_);\n    }\n\n    /**\n     * @notice Remove deposit token (i.e. collateral) from Synth\n     */\n    function removeDepositToken(IDepositToken depositToken_) external override onlyGovernor {\n        require(depositToken_.totalSupply() == 0, \"supply-gt-0\");\n\n        require(depositTokens.remove(address(depositToken_)), \"deposit-token-doesnt-exist\");\n        delete depositTokenOf[depositToken_.underlying()];\n\n        emit DepositTokenRemoved(depositToken_);\n    }\n\n    /**\n     * @notice Remove a RewardsDistributor contract\n     */\n    function removeRewardsDistributor(IRewardsDistributor distributor_) external override onlyGovernor {\n        require(address(distributor_) != address(0), \"address-is-null\");\n\n        uint256 _length = rewardsDistributors.length;\n        uint256 _index = _length;\n        for (uint256 i; i < _length; ++i) {\n            if (rewardsDistributors[i] == distributor_) {\n                _index = i;\n                break;\n            }\n        }\n        require(_index < _length, \"distribuitor-doesnt-exist\");\n        if (_index != _length - 1) {\n            rewardsDistributors[_index] = rewardsDistributors[_length - 1];\n        }\n        rewardsDistributors.pop();\n\n        emit RewardsDistributorRemoved(distributor_);\n    }\n\n    /**\n     * @notice Turn swap on/off\n     */\n    function toggleIsSwapActive() external override onlyGovernor {\n        bool _newIsSwapActive = !isSwapActive;\n        emit SwapActiveUpdated(_newIsSwapActive);\n        isSwapActive = _newIsSwapActive;\n    }\n\n    /**\n     * @notice Update debt floor\n     */\n    function updateDebtFloor(uint256 newDebtFloorInUsd_) external override onlyGovernor {\n        uint256 _currentDebtFloorInUsd = debtFloorInUsd;\n        require(newDebtFloorInUsd_ != _currentDebtFloorInUsd, \"new-same-as-current\");\n        emit DebtFloorUpdated(_currentDebtFloorInUsd, newDebtFloorInUsd_);\n        debtFloorInUsd = newDebtFloorInUsd_;\n    }\n\n    /**\n     * @notice Update deposit fee\n     */\n    function updateDepositFee(uint256 newDepositFee_) external override onlyGovernor {\n        require(newDepositFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentDepositFee = depositFee;\n        require(newDepositFee_ != _currentDepositFee, \"new-same-as-current\");\n        emit DepositFeeUpdated(_currentDepositFee, newDepositFee_);\n        depositFee = newDepositFee_;\n    }\n\n    /**\n     * @notice Update issue fee\n     */\n    function updateIssueFee(uint256 newIssueFee_) external override onlyGovernor {\n        require(newIssueFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentIssueFee = issueFee;\n        require(newIssueFee_ != _currentIssueFee, \"new-same-as-current\");\n        emit IssueFeeUpdated(_currentIssueFee, newIssueFee_);\n        issueFee = newIssueFee_;\n    }\n\n    /**\n     * @notice Update liquidator liquidation fee\n     */\n    function updateLiquidatorLiquidationFee(uint128 newLiquidatorLiquidationFee_) external override onlyGovernor {\n        require(newLiquidatorLiquidationFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentLiquidatorLiquidationFee = liquidationFees.liquidatorFee;\n        require(newLiquidatorLiquidationFee_ != _currentLiquidatorLiquidationFee, \"new-same-as-current\");\n        emit LiquidatorLiquidationFeeUpdated(_currentLiquidatorLiquidationFee, newLiquidatorLiquidationFee_);\n        liquidationFees.liquidatorFee = newLiquidatorLiquidationFee_;\n    }\n\n    /**\n     * @notice Update maxLiquidable (liquidation cap)\n     */\n    function updateMaxLiquidable(uint256 newMaxLiquidable_) external override onlyGovernor {\n        require(newMaxLiquidable_ <= 1e18, \"max-is-100%\");\n        uint256 _currentMaxLiquidable = maxLiquidable;\n        require(newMaxLiquidable_ != _currentMaxLiquidable, \"new-same-as-current\");\n        emit MaxLiquidableUpdated(_currentMaxLiquidable, newMaxLiquidable_);\n        maxLiquidable = newMaxLiquidable_;\n    }\n\n    /**\n     * @notice Update protocol liquidation fee\n     */\n    function updateProtocolLiquidationFee(uint128 newProtocolLiquidationFee_) external override onlyGovernor {\n        require(newProtocolLiquidationFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentProtocolLiquidationFee = liquidationFees.protocolFee;\n        require(newProtocolLiquidationFee_ != _currentProtocolLiquidationFee, \"new-same-as-current\");\n        emit ProtocolLiquidationFeeUpdated(_currentProtocolLiquidationFee, newProtocolLiquidationFee_);\n        liquidationFees.protocolFee = newProtocolLiquidationFee_;\n    }\n\n    /**\n     * @notice Update repay fee\n     */\n    function updateRepayFee(uint256 newRepayFee_) external override onlyGovernor {\n        require(newRepayFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentRepayFee = repayFee;\n        require(newRepayFee_ != _currentRepayFee, \"new-same-as-current\");\n        emit RepayFeeUpdated(_currentRepayFee, newRepayFee_);\n        repayFee = newRepayFee_;\n    }\n\n    /**\n     * @notice Update treasury contract - will migrate funds to the new contract\n     */\n    function updateTreasury(ITreasury newTreasury_) external override onlyGovernor {\n        require(address(newTreasury_) != address(0), \"address-is-null\");\n        ITreasury _currentTreasury = treasury;\n        require(newTreasury_ != _currentTreasury, \"new-same-as-current\");\n\n        if (address(_currentTreasury) != address(0)) {\n            _currentTreasury.migrateTo(address(newTreasury_));\n        }\n\n        emit TreasuryUpdated(_currentTreasury, newTreasury_);\n        treasury = newTreasury_;\n    }\n\n    /**\n     * @notice Update swap fee\n     */\n    function updateSwapFee(uint256 newSwapFee_) external override onlyGovernor {\n        require(newSwapFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentSwapFee = swapFee;\n        require(newSwapFee_ != _currentSwapFee, \"new-same-as-current\");\n        emit SwapFeeUpdated(_currentSwapFee, newSwapFee_);\n        swapFee = newSwapFee_;\n    }\n\n    /**\n     * @notice Update withdraw fee\n     */\n    function updateWithdrawFee(uint256 newWithdrawFee_) external override onlyGovernor {\n        require(newWithdrawFee_ <= 1e18, \"max-is-100%\");\n        uint256 _currentWithdrawFee = withdrawFee;\n        require(newWithdrawFee_ != _currentWithdrawFee, \"new-same-as-current\");\n        emit WithdrawFeeUpdated(_currentWithdrawFee, newWithdrawFee_);\n        withdrawFee = newWithdrawFee_;\n    }\n}\n"
    },
    "contracts/access/Governable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/proxy/utils/Initializable.sol\";\nimport \"../utils/TokenHolder.sol\";\nimport \"../interfaces/IGovernable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (governor) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the governor account will be the one that deploys the contract. This\n * can later be changed with {transferGovernorship}.\n *\n */\nabstract contract Governable is IGovernable, TokenHolder, Initializable {\n    address public governor;\n    address public proposedGovernor;\n\n    event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial governor.\n     */\n    constructor() {\n        governor = msg.sender;\n        emit UpdatedGovernor(address(0), msg.sender);\n    }\n\n    /**\n     * @dev If inheriting child is using proxy then child contract can use\n     * __Governable_init() function to initialization this contract\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function __Governable_init() internal initializer {\n        governor = msg.sender;\n        emit UpdatedGovernor(address(0), msg.sender);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the governor.\n     */\n    modifier onlyGovernor() {\n        require(governor == msg.sender, \"not-governor\");\n        _;\n    }\n\n    function _requireCanSweep() internal view override onlyGovernor {}\n\n    /**\n     * @dev Transfers governorship of the contract to a new account (`proposedGovernor`).\n     * Can only be called by the current owner.\n     */\n    function transferGovernorship(address proposedGovernor_) external onlyGovernor {\n        require(proposedGovernor_ != address(0), \"proposed-governor-is-zero\");\n        proposedGovernor = proposedGovernor_;\n    }\n\n    /**\n     * @dev Allows new governor to accept governorship of the contract.\n     */\n    function acceptGovernorship() external {\n        address _proposedGovernor = proposedGovernor;\n        require(_proposedGovernor == msg.sender, \"not-the-proposed-governor\");\n        emit UpdatedGovernor(governor, _proposedGovernor);\n        governor = _proposedGovernor;\n        proposedGovernor = address(0);\n    }\n}\n"
    },
    "contracts/dependencies/openzeppelin/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     */\n    bool private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Modifier to protect an initializer function from being invoked twice.\n     */\n    modifier initializer() {\n        require(_initializing || !_initialized, \"Initializable: contract is already initialized\");\n\n        bool isTopLevelCall = !_initializing;\n        if (isTopLevelCall) {\n            _initializing = true;\n            _initialized = true;\n        }\n\n        _;\n\n        if (isTopLevelCall) {\n            _initializing = false;\n        }\n    }\n}\n"
    },
    "contracts/dependencies/openzeppelin/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal initializer {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
    },
    "contracts/dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
    },
    "contracts/dependencies/openzeppelin/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
    },
    "contracts/dependencies/openzeppelin/utils/structs/EnumerableSet.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastvalue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastvalue;\n                // Update the index for the moved value\n                set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        return _values(set._inner);\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
    },
    "contracts/interfaces/IDebtToken.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"./ISyntheticToken.sol\";\n\ninterface IDebtToken is IERC20Metadata {\n    function isActive() external view returns (bool);\n\n    function syntheticToken() external view returns (ISyntheticToken);\n\n    function accrueInterest() external;\n\n    function debtIndex() external returns (uint256 debtIndex_);\n\n    function burn(address from_, uint256 amount_) external;\n\n    function issue(uint256 amount_, address to_) external;\n\n    function repay(address onBehalfOf_, uint256 amount_) external;\n\n    function updateMaxTotalSupply(uint256 newMaxTotalSupply_) external;\n\n    function updateInterestRate(uint256 newInterestRate_) external;\n\n    function maxTotalSupply() external view returns (uint256);\n\n    function interestRate() external view returns (uint256);\n\n    function interestRatePerSecond() external view returns (uint256);\n\n    function toggleIsActive() external;\n}\n"
    },
    "contracts/interfaces/IDepositToken.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol\";\n\ninterface IDepositToken is IERC20Metadata {\n    function underlying() external view returns (IERC20);\n\n    function collateralizationRatio() external view returns (uint256);\n\n    function unlockedBalanceOf(address account_) external view returns (uint256);\n\n    function lockedBalanceOf(address account_) external view returns (uint256);\n\n    function deposit(uint256 amount_, address onBehalfOf_) external;\n\n    function withdraw(uint256 amount_, address to_) external;\n\n    function seize(\n        address from_,\n        address to_,\n        uint256 amount_\n    ) external;\n\n    function updateCollateralizationRatio(uint128 newCollateralizationRatio_) external;\n\n    function isActive() external view returns (bool);\n\n    function toggleIsActive() external;\n\n    function maxTotalSupply() external view returns (uint256);\n\n    function updateMaxTotalSupply(uint256 newMaxTotalSupply_) external;\n}\n"
    },
    "contracts/interfaces/IGovernable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\n/**\n * @notice Governable interface\n */\ninterface IGovernable {\n    function governor() external view returns (address _governor);\n\n    function transferGovernorship(address _proposedGovernor) external;\n}\n"
    },
    "contracts/interfaces/IPauseable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\ninterface IPauseable {\n    function paused() external view returns (bool);\n\n    function everythingStopped() external view returns (bool);\n}\n"
    },
    "contracts/interfaces/IPool.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"./IDepositToken.sol\";\nimport \"./ITreasury.sol\";\nimport \"./IRewardsDistributor.sol\";\nimport \"./IPoolRegistry.sol\";\n\n/**\n * @notice Pool interface\n */\ninterface IPool is IPauseable, IGovernable {\n    function debtFloorInUsd() external view returns (uint256);\n\n    function depositFee() external view returns (uint256);\n\n    function issueFee() external view returns (uint256);\n\n    function withdrawFee() external view returns (uint256);\n\n    function repayFee() external view returns (uint256);\n\n    function swapFee() external view returns (uint256);\n\n    function feeCollector() external view returns (address);\n\n    function maxLiquidable() external view returns (uint256);\n\n    function isSyntheticTokenExists(ISyntheticToken syntheticToken_) external view returns (bool);\n\n    function isDebtTokenExists(IDebtToken debtToken_) external view returns (bool);\n\n    function isDepositTokenExists(IDepositToken depositToken_) external view returns (bool);\n\n    function depositTokenOf(IERC20 underlying_) external view returns (IDepositToken);\n\n    function debtTokenOf(ISyntheticToken syntheticToken_) external view returns (IDebtToken);\n\n    function getDepositTokens() external view returns (address[] memory);\n\n    function getDebtTokens() external view returns (address[] memory);\n\n    function getRewardsDistributors() external view returns (IRewardsDistributor[] memory);\n\n    function debtOf(address account_) external view returns (uint256 _debtInUsd);\n\n    function depositOf(address account_) external view returns (uint256 _depositInUsd, uint256 _issuableLimitInUsd);\n\n    function debtPositionOf(address account_)\n        external\n        view\n        returns (\n            bool _isHealthy,\n            uint256 _depositInUsd,\n            uint256 _debtInUsd,\n            uint256 _issuableLimitInUsd,\n            uint256 _issuableInUsd\n        );\n\n    function addDebtToken(IDebtToken debtToken_) external;\n\n    function removeDebtToken(IDebtToken debtToken_) external;\n\n    function addDepositToken(address depositToken_) external;\n\n    function removeDepositToken(IDepositToken depositToken_) external;\n\n    function liquidate(\n        ISyntheticToken syntheticToken_,\n        address account_,\n        uint256 amountToRepay_,\n        IDepositToken depositToken_\n    ) external;\n\n    function swap(\n        ISyntheticToken syntheticTokenIn_,\n        ISyntheticToken syntheticTokenOut_,\n        uint256 amountIn_\n    ) external returns (uint256 _amountOut);\n\n    function updateSwapFee(uint256 newSwapFee_) external;\n\n    function updateDebtFloor(uint256 newDebtFloorInUsd_) external;\n\n    function updateDepositFee(uint256 newDepositFee_) external;\n\n    function updateIssueFee(uint256 newIssueFee_) external;\n\n    function updateWithdrawFee(uint256 newWithdrawFee_) external;\n\n    function updateRepayFee(uint256 newRepayFee_) external;\n\n    function updateLiquidatorLiquidationFee(uint128 newLiquidatorLiquidationFee_) external;\n\n    function updateProtocolLiquidationFee(uint128 newProtocolLiquidationFee_) external;\n\n    function updateMaxLiquidable(uint256 newMaxLiquidable_) external;\n\n    function updateTreasury(ITreasury newTreasury_) external;\n\n    function treasury() external view returns (ITreasury);\n\n    function masterOracle() external view returns (IMasterOracle);\n\n    function poolRegistry() external view returns (IPoolRegistry);\n\n    function addToDepositTokensOfAccount(address account_) external;\n\n    function removeFromDepositTokensOfAccount(address account_) external;\n\n    function addToDebtTokensOfAccount(address account_) external;\n\n    function removeFromDebtTokensOfAccount(address account_) external;\n\n    function getDepositTokensOfAccount(address account_) external view returns (address[] memory);\n\n    function getDebtTokensOfAccount(address account_) external view returns (address[] memory);\n\n    function addRewardsDistributor(IRewardsDistributor distributor_) external;\n\n    function removeRewardsDistributor(IRewardsDistributor distributor_) external;\n\n    function toggleIsSwapActive() external;\n\n    function isSwapActive() external view returns (bool);\n}\n"
    },
    "contracts/interfaces/IPoolRegistry.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"./external/IMasterOracle.sol\";\nimport \"./IPauseable.sol\";\nimport \"./IGovernable.sol\";\nimport \"./ISyntheticToken.sol\";\n\ninterface IPoolRegistry is IPauseable, IGovernable {\n    function poolExists(address pool_) external view returns (bool);\n\n    function feeCollector() external view returns (address);\n\n    function getPools() external view returns (address[] memory);\n\n    function registerPool(address pool_) external;\n\n    function unregisterPool(address pool_) external;\n\n    function masterOracle() external view returns (IMasterOracle);\n\n    function updateMasterOracle(IMasterOracle newOracle_) external;\n}\n"
    },
    "contracts/interfaces/IRewardsDistributor.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/token/ERC20/IERC20.sol\";\n\n/**\n * @notice Reward Distributor interface\n */\ninterface IRewardsDistributor {\n    function rewardToken() external view returns (IERC20);\n\n    function tokenSpeeds(IERC20 token_) external view returns (uint256);\n\n    function tokensAccruedOf(address account_) external view returns (uint256);\n\n    function updateBeforeMintOrBurn(IERC20 token_, address account_) external;\n\n    function updateBeforeTransfer(\n        IERC20 token_,\n        address from_,\n        address to_\n    ) external;\n\n    function claimRewards(address account_) external;\n\n    function claimRewards(address account_, IERC20[] memory tokens_) external;\n\n    function claimRewards(address[] memory accounts_, IERC20[] memory tokens_) external;\n}\n"
    },
    "contracts/interfaces/ISyntheticToken.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"./IDebtToken.sol\";\n\ninterface ISyntheticToken is IERC20Metadata {\n    function isActive() external view returns (bool);\n\n    function mint(address to_, uint256 amount_) external;\n\n    function burn(address from_, uint256 amount) external;\n\n    function toggleIsActive() external;\n\n    function seize(\n        address from_,\n        address to_,\n        uint256 amount_\n    ) external;\n\n    function updateMaxTotalSupply(uint256 newMaxTotalSupply_) external;\n}\n"
    },
    "contracts/interfaces/ITreasury.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\ninterface ITreasury {\n    function pull(address to_, uint256 amount_) external;\n\n    function migrateTo(address newTreasury_) external;\n}\n"
    },
    "contracts/interfaces/external/IMasterOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\ninterface IMasterOracle {\n    function quoteTokenToUsd(address _asset, uint256 _amount) external view returns (uint256 _amountInUsd);\n\n    function quoteUsdToToken(address _asset, uint256 _amountInUsd) external view returns (uint256 _amount);\n\n    function quote(\n        address _assetIn,\n        address _assetOut,\n        uint256 _amountIn\n    ) external view returns (uint256 _amountOut);\n}\n"
    },
    "contracts/lib/MappedEnumerableSet.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev EnumerableSet fork to support `address => address[]` mapping\n * @dev Forked from OZ 4.3.2\n */\nlibrary MappedEnumerableSet {\n    struct Set {\n        // Storage of set values\n        address[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(address => uint256) _indexes;\n    }\n\n    struct AddressSet {\n        mapping(address => Set) _ofAddress;\n    }\n\n    function _add(\n        AddressSet storage set,\n        address _key,\n        address value\n    ) private returns (bool) {\n        if (!_contains(set, _key, value)) {\n            set._ofAddress[_key]._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._ofAddress[_key]._indexes[value] = set._ofAddress[_key]._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    function _remove(\n        AddressSet storage set,\n        address _key,\n        address value\n    ) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._ofAddress[_key]._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._ofAddress[_key]._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                address lastvalue = set._ofAddress[_key]._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._ofAddress[_key]._values[toDeleteIndex] = lastvalue;\n                // Update the index for the moved value\n                set._ofAddress[_key]._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._ofAddress[_key]._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._ofAddress[_key]._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    function _contains(\n        AddressSet storage set,\n        address _key,\n        address value\n    ) private view returns (bool) {\n        return set._ofAddress[_key]._indexes[value] != 0;\n    }\n\n    function _length(AddressSet storage set, address _key) private view returns (uint256) {\n        return set._ofAddress[_key]._values.length;\n    }\n\n    function _at(\n        AddressSet storage set,\n        address _key,\n        uint256 index\n    ) private view returns (address) {\n        return set._ofAddress[_key]._values[index];\n    }\n\n    function _values(AddressSet storage set, address _key) private view returns (address[] memory) {\n        return set._ofAddress[_key]._values;\n    }\n\n    function add(\n        AddressSet storage set,\n        address key,\n        address value\n    ) internal returns (bool) {\n        return _add(set, key, value);\n    }\n\n    function remove(\n        AddressSet storage set,\n        address key,\n        address value\n    ) internal returns (bool) {\n        return _remove(set, key, value);\n    }\n\n    function contains(\n        AddressSet storage set,\n        address key,\n        address value\n    ) internal view returns (bool) {\n        return _contains(set, key, value);\n    }\n\n    function length(AddressSet storage set, address key) internal view returns (uint256) {\n        return _length(set, key);\n    }\n\n    function at(\n        AddressSet storage set,\n        address key,\n        uint256 index\n    ) internal view returns (address) {\n        return _at(set, key, index);\n    }\n\n    function values(AddressSet storage set, address key) internal view returns (address[] memory) {\n        address[] memory store = _values(set, key);\n        address[] memory result;\n\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
    },
    "contracts/lib/WadRayMath.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\n/**\n * @title Math library\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)\n * @dev Based on https://github.com/dapphub/ds-math/blob/master/src/math.sol\n */\nlibrary WadRayMath {\n    uint256 internal constant WAD = 1e18;\n    uint256 internal constant HALF_WAD = WAD / 2;\n\n    uint256 internal constant RAY = 1e27;\n    uint256 internal constant HALF_RAY = RAY / 2;\n\n    uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n    /**\n     * @dev Multiplies two wad, rounding half up to the nearest wad\n     * @param a Wad\n     * @param b Wad\n     * @return The result of a*b, in wad\n     */\n    function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (a == 0 || b == 0) {\n            return 0;\n        }\n\n        return (a * b + HALF_WAD) / WAD;\n    }\n\n    /**\n     * @dev Divides two wad, rounding half up to the nearest wad\n     * @param a Wad\n     * @param b Wad\n     * @return The result of a/b, in wad\n     */\n    function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        return (a * WAD + b / 2) / b;\n    }\n}\n"
    },
    "contracts/storage/PoolStorage.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/utils/structs/EnumerableSet.sol\";\nimport \"../lib/MappedEnumerableSet.sol\";\nimport \"../interfaces/IPool.sol\";\n\nabstract contract PoolStorageV1 is IPool {\n    struct LiquidationFees {\n        uint128 liquidatorFee;\n        uint128 protocolFee;\n    }\n\n    /**\n     * @notice The debt floor (in USD) for each synthetic token\n     * This parameters is used to keep incentive for liquidators (i.e. cover gas and provide enough profit)\n     */\n    uint256 public debtFloorInUsd;\n\n    /**\n     * @notice The fee charged when depositing collateral\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public depositFee;\n\n    /**\n     * @notice The fee charged when minting a synthetic token\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public issueFee;\n\n    /**\n     * @notice The fee charged when withdrawing collateral\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public withdrawFee;\n\n    /**\n     * @notice The fee charged when repaying debt\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public repayFee;\n\n    /**\n     * @notice The fee charged when swapping synthetic tokens\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public swapFee;\n\n    /**\n     * @notice The fees charged when liquidating a position\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    LiquidationFees public liquidationFees;\n\n    /**\n     * @notice The max percent of the debt allowed to liquidate\n     * @dev Use 18 decimals (e.g. 1e16 = 1%)\n     */\n    uint256 public maxLiquidable;\n\n    /**\n     * @notice PoolRegistry\n     */\n    IPoolRegistry public poolRegistry;\n\n    /**\n     * @notice Swap feature on/off flag\n     */\n    bool public isSwapActive;\n\n    /**\n     * @notice Treasury contract\n     */\n    ITreasury public treasury;\n\n    /**\n     * @notice Represents collateral's deposits\n     */\n    EnumerableSet.AddressSet internal depositTokens;\n\n    /**\n     * @notice Get the deposit token's address from given underlying asset\n     */\n    mapping(IERC20 => IDepositToken) public depositTokenOf;\n\n    /**\n     * @notice Available debt tokens\n     */\n    EnumerableSet.AddressSet internal debtTokens;\n\n    /**\n     * @notice Per-account deposit tokens (i.e. tokens that user has balance > 0)\n     */\n    MappedEnumerableSet.AddressSet internal depositTokensOfAccount;\n\n    /**\n     * @notice Per-account debt tokens (i.e. tokens that user has balance > 0)\n     */\n    MappedEnumerableSet.AddressSet internal debtTokensOfAccount;\n\n    /**\n     * @notice RewardsDistributor contracts\n     */\n    IRewardsDistributor[] internal rewardsDistributors;\n\n    /**\n     * @notice Get the debt token's address from given synthetic asset\n     */\n    mapping(ISyntheticToken => IDebtToken) public debtTokenOf;\n}\n"
    },
    "contracts/utils/Pauseable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../interfaces/IPauseable.sol\";\nimport \"../access/Governable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n */\nabstract contract Pauseable is IPauseable, Governable {\n    /// @notice Emitted when contract is turned on\n    event Open(address caller);\n\n    /// @notice Emitted when contract is paused\n    event Paused(address caller);\n\n    /// @notice Emitted when contract is shuted down\n    event Shutdown(address caller);\n\n    /// @notice Emitted when contract is unpaused\n    event Unpaused(address caller);\n\n    bool private _paused;\n    bool private _everythingStopped;\n\n    /**\n     * @dev Throws if contract is paused\n     */\n    modifier whenNotPaused() {\n        require(!paused(), \"paused\");\n        _;\n    }\n\n    /**\n     * @dev Throws if contract is shutdown\n     */\n    modifier whenNotShutdown() {\n        require(!everythingStopped(), \"shutdown\");\n        _;\n    }\n\n    /**\n     * @dev Throws if contract is not paused\n     */\n    modifier whenPaused() {\n        require(paused(), \"not-paused\");\n        _;\n    }\n\n    /**\n     * @dev Throws if contract is not shutdown\n     */\n    modifier whenShutdown() {\n        require(everythingStopped(), \"not-shutdown\");\n        _;\n    }\n\n    /**\n     * @dev If inheriting child is using proxy then child contract can use\n     * __Pauseable_init() function to initialization this contract\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function __Pauseable_init() internal initializer {\n        __Governable_init();\n    }\n\n    /**\n     * @notice Return `true` if contract is shutdown\n     */\n    function everythingStopped() public view virtual returns (bool) {\n        return _everythingStopped;\n    }\n\n    /**\n     * @notice Return `true` if contract is paused\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Open contract operations, if contract is in shutdown state\n     */\n    function open() external virtual whenShutdown onlyGovernor {\n        _everythingStopped = false;\n        emit Open(msg.sender);\n    }\n\n    /**\n     * @dev Pause contract operations, if contract is not paused.\n     */\n    function pause() external virtual whenNotPaused onlyGovernor {\n        _paused = true;\n        emit Paused(msg.sender);\n    }\n\n    /**\n     * @dev Shutdown contract operations, if not already shutdown.\n     */\n    function shutdown() external virtual whenNotShutdown onlyGovernor {\n        _everythingStopped = true;\n        _paused = true;\n        emit Shutdown(msg.sender);\n    }\n\n    /**\n     * @dev Unpause contract operations, allow only if contract is paused and not shutdown.\n     */\n    function unpause() external virtual whenPaused whenNotShutdown onlyGovernor {\n        _paused = false;\n        emit Unpaused(msg.sender);\n    }\n}\n"
    },
    "contracts/utils/TokenHolder.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol\";\n\n/**\n * @title Utils contract that handles tokens sent to it\n */\nabstract contract TokenHolder {\n    using SafeERC20 for IERC20;\n\n    /**\n     * @dev Revert fallback calls\n     */\n    fallback() external payable {\n        revert(\"fallback-not-allowed\");\n    }\n\n    /**\n     * @dev Revert when receiving by default\n     */\n    receive() external payable virtual {\n        revert(\"receive-not-allowed\");\n    }\n\n    /**\n     * @notice ERC20 recovery in case of stuck tokens due direct transfers to the contract address.\n     * @param token_ The token to transfer\n     * @param to_ The recipient of the transfer\n     * @param amount_ The amount to send\n     */\n    function sweep(\n        IERC20 token_,\n        address to_,\n        uint256 amount_\n    ) external {\n        _requireCanSweep();\n\n        if (address(token_) == address(0)) {\n            Address.sendValue(payable(to_), amount_);\n        } else {\n            token_.safeTransfer(to_, amount_);\n        }\n    }\n\n    /**\n     * @notice Function that reverts if the caller isn't allowed to sweep tokens\n     */\n    function _requireCanSweep() internal view virtual;\n}\n"
    }
  }
}