creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "contracts/base/ScalingERC20.sol": {
        "content": "//██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗\n//██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║\n//██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║\n//██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║\n//██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║\n//╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝\n\n\npragma solidity 0.8.16;\n//SPDX-License-Identifier: BUSL-1.1\n\nimport \"../oz/interfaces/IERC20.sol\";\nimport \"../oz/utils/Context.sol\";\nimport {Errors} from  \"../utils/Errors.sol\";\nimport {WadRayMath} from  \"../utils/WadRayMath.sol\";\n\n/** @title ScalingERC20 contract\n *  @author Paladin, inspired by Aave & OpenZeppelin implementations\n *  @notice ERC20 implementation of scaled balance token\n*/\nabstract contract ScalingERC20 is Context, IERC20 {\n    using WadRayMath for uint256;\n\n    // Constants\n\n    /** @notice 1e18 scale */\n    uint256 public constant UNIT = 1e18;\n\n    /** @notice 1e27 - RAY - Initial Index for balance to scaled balance */\n    uint256 internal constant INITIAL_INDEX = 1e27;\n\n    // Structs\n\n    /** @notice UserState struct \n    *   scaledBalance: scaled balance of the user\n    *   index: last index for the user\n    */\n    struct UserState {\n        uint128 scaledBalance;\n        uint128 index;\n    }\n\n    // Storage\n\n    /** @notice Total scaled supply */\n    uint256 internal _totalSupply;\n\n    /** @notice Allowances for users */\n    mapping(address => mapping(address => uint256)) internal _allowances;\n\n    /** @notice Token name */\n    string private _name;\n    /** @notice Token symbol */\n    string private _symbol;\n    /** @notice Token decimals */\n    uint8 private _decimals;\n\n    /** @notice User states */\n    mapping(address => UserState) internal _userStates;\n\n\n    // Events\n\n    /** @notice Event emitted when minting */\n    event Mint(address indexed user, uint256 scaledAmount, uint256 index);\n    /** @notice Event emitted when burning */\n    event Burn(address indexed user, uint256 scaledAmount, uint256 index);\n\n\n    // Constructor\n\n    constructor(\n        string memory __name,\n        string memory __symbol\n    ) {\n        _name = __name;\n        _symbol = __symbol;\n        _decimals = 18;\n    }\n\n\n    // View methods\n\n    /**\n    * @notice Get the name of the ERC20\n    * @return string : Name\n    */\n    function name() public view returns (string memory) {\n        return _name;\n    }\n\n    /**\n    * @notice Get the symbol of the ERC20\n    * @return string : Symbol\n    */\n    function symbol() external view returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n    * @notice Get the decimals of the ERC20\n    * @return uint256 : Number of decimals\n    */\n    function decimals() external view returns (uint8) {\n        return _decimals;\n    }\n\n    /**\n    * @notice Get the current total supply\n    * @return uint256 : Current total supply\n    */\n    function totalSupply() public view override virtual returns (uint256) {\n        uint256 _scaledSupply = _totalSupply;\n        if(_scaledSupply == 0) return 0;\n        return _scaledSupply.rayMul(_getCurrentIndex());\n    }\n\n    /**\n    * @notice Get the current user balance\n    * @param account Address of user\n    * @return uint256 : User balance\n    */\n    function balanceOf(address account) public view override virtual returns (uint256) {\n        return uint256(_userStates[account].scaledBalance).rayMul(_getCurrentIndex());\n    }\n\n    /**\n    * @notice Get the current total scaled supply\n    * @return uint256 : Current total scaled supply\n    */\n    function totalScaledSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n    * @notice Get the current user scaled balance\n    * @param account Address of user\n    * @return uint256 : User scaled balance\n    */\n    function scaledBalanceOf(address account) public view virtual returns (uint256) {\n        return _userStates[account].scaledBalance;\n    }\n\n    /**\n    * @notice Get the allowance of a spender for a given owner\n    * @param owner Address of the owner\n    * @param spender Address of the spender\n    * @return uint256 : allowance amount\n    */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n\n\n\n    // Write methods\n\n    /**\n    * @notice Approve a spender to spend tokens\n    * @param spender Address of the spender\n    * @param amount Amount to approve\n    * @return bool : success\n    */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(msg.sender, spender, amount);\n        return true;\n    }\n\n    /**\n    * @notice Increase the allowance given to a spender\n    * @param spender Address of the spender\n    * @param addedValue Increase amount\n    * @return bool : success\n    */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = msg.sender;\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n    * @notice Decrease the allowance given to a spender\n    * @param spender Address of the spender\n    * @param subtractedValue Decrease amount\n    * @return bool : success\n    */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = msg.sender;\n        uint256 currentAllowance = allowance(owner, spender);\n        if(currentAllowance < subtractedValue) revert Errors.ERC20_AllowanceUnderflow();\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n    * @notice Transfer tokens to the given recipient\n    * @param recipient Address to receive the tokens\n    * @param amount Amount to transfer\n    * @return bool : success\n    */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(msg.sender, recipient, amount);\n        emit Transfer(msg.sender, recipient, amount);\n        return true;\n    }\n\n    /**\n    * @notice Transfer tokens from the spender to the given recipient\n    * @param sender Address sending the tokens\n    * @param recipient Address to receive the tokens\n    * @param amount Amount to transfer\n    * @return bool : success\n    */\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) public virtual override returns (bool) {\n        uint256 _allowance = _allowances[sender][msg.sender];\n        if(_allowance < amount) revert Errors.ERC20_AmountOverAllowance();\n        if(_allowance != type(uint256).max) {\n            _approve(\n                sender,\n                msg.sender,\n                _allowances[sender][msg.sender] - amount\n            );\n        }\n        _transfer(sender, recipient, amount);\n        emit Transfer(sender, recipient, amount);\n        return true;\n    }\n\n\n    // Internal methods\n\n    /**\n    * @dev Get the current index to convert between balance and scaled balances\n    * @return uint256 : Current index\n    */\n    // To implement in inheriting contract\n    function _getCurrentIndex() internal virtual view returns(uint256) {}\n\n    /**\n    * @dev Approve a spender to spend tokens\n    * @param owner Address of the woner\n    * @param spender Address of the spender\n    * @param amount Amount to approve\n    */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        if(owner == address(0) || spender == address(0)) revert Errors.ERC20_ApproveAddressZero();\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n    * @dev Transfer tokens from the spender to the given recipient\n    * @param sender Address sending the tokens\n    * @param recipient Address to receive the tokens\n    * @param amount Amount to transfer\n    */\n    function _transfer(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) internal virtual {\n        if(sender == address(0) || recipient == address(0)) revert Errors.ERC20_AddressZero();\n        if(sender == recipient) revert Errors.ERC20_SelfTransfer();\n        if(amount == 0) revert Errors.ERC20_NullAmount();\n\n        // Get the scaled amount to transfer for the given amount\n        uint128 _scaledAmount = safe128(amount.rayDiv(_getCurrentIndex()));\n        _transferScaled(sender, recipient, _scaledAmount);\n    }\n\n    /**\n    * @dev Transfer the scaled amount of tokens\n    * @param sender Address sending the tokens\n    * @param recipient Address to receive the tokens\n    * @param scaledAmount Scaled amount to transfer\n    */\n    function _transferScaled(\n        address sender,\n        address recipient,\n        uint128 scaledAmount\n    ) internal virtual {\n        if(scaledAmount > _userStates[sender].scaledBalance) revert Errors.ERC20_AmountExceedBalance();\n\n        _beforeTokenTransfer(sender, recipient, scaledAmount);\n\n        unchecked {\n            // Should never fail because of previous check\n            // & because the scaledBalance of an user should never exceed the _totalSupply\n            _userStates[sender].scaledBalance -= scaledAmount;\n            _userStates[recipient].scaledBalance += scaledAmount;\n        }\n\n        _afterTokenTransfer(sender, recipient, scaledAmount);\n    }\n\n    /**\n    * @dev Mint the given amount to the given address (by minting the correct scaled amount)\n    * @param account Address to mint to\n    * @param amount Amount to mint\n    * @param _currentIndex Index to use to calculate the scaled amount\n    * @return uint256 : Amount minted\n    */\n    function _mint(address account, uint256 amount, uint256 _currentIndex) internal virtual returns(uint256) {\n        uint256 _scaledAmount = amount.rayDiv(_currentIndex);\n        if(_scaledAmount == 0) revert Errors.ERC20_NullAmount();\n\n        _beforeTokenTransfer(address(0), account, _scaledAmount);\n\n        _userStates[account].index = safe128(_currentIndex);\n\n        _totalSupply += _scaledAmount;\n        _userStates[account].scaledBalance += safe128(_scaledAmount);\n\n        _afterTokenTransfer(address(0), account, _scaledAmount);\n\n        emit Mint(account, _scaledAmount, _currentIndex);\n        emit Transfer(address(0), account, amount);\n\n        return amount;\n    }\n\n    /**\n    * @dev Burn the given amount from the given address (by burning the correct scaled amount)\n    * @param account Address to burn from\n    * @param amount Amount to burn\n    * @param maxWithdraw True if burning the full balance\n    * @return uint256 : Amount burned\n    */\n    function _burn(address account, uint256 amount, bool maxWithdraw) internal virtual returns(uint256) {\n        uint256 _currentIndex = _getCurrentIndex();\n        uint256 _scaledBalance = _userStates[account].scaledBalance;\n\n        // if given maxWithdraw as true, we want to burn the whole balance for the user\n        uint256 _scaledAmount = maxWithdraw ?  _scaledBalance: amount.rayDiv(_currentIndex);\n        if(_scaledAmount == 0) revert Errors.ERC20_NullAmount();\n        if(_scaledAmount > _scaledBalance) revert Errors.ERC20_AmountExceedBalance();\n\n        _beforeTokenTransfer(account, address(0), _scaledAmount);\n        \n        _userStates[account].index = safe128(_currentIndex);\n\n        _totalSupply -= _scaledAmount;\n        _userStates[account].scaledBalance -= safe128(_scaledAmount);\n\n        _afterTokenTransfer(account, address(0), _scaledAmount);\n        \n        emit Burn(account, _scaledAmount, _currentIndex);\n        emit Transfer(account, address(0), amount);\n\n        return amount;\n    }\n\n\n    // Virtual hooks\n\n    /**\n    * @dev Hook executed before each transfer\n    * @param from Sender address\n    * @param to Receiver address\n    * @param amount Amount to transfer\n    */\n    // To implement in inheriting contract\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n    * @dev Hook executed after each transfer\n    * @param from Sender address\n    * @param to Receiver address\n    * @param amount Amount to transfer\n    */\n    // To implement in inheriting contract\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n\n    // Maths\n\n    function safe128(uint256 n) internal pure returns (uint128) {\n        if(n > type(uint128).max) revert Errors.NumberExceed128Bits();\n        return uint128(n);\n    }\n\n\n}"
      },
      "contracts/DullahanPod.sol": {
        "content": "//██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗\n//██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║\n//██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║\n//██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║\n//██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║\n//╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝\n\n\npragma solidity 0.8.16;\n//SPDX-License-Identifier: BUSL-1.1\n\nimport \"./oz/interfaces/IERC20.sol\";\nimport \"./oz/libraries/SafeERC20.sol\";\nimport \"./oz/utils/ReentrancyGuard.sol\";\nimport \"./interfaces/IDullahanPodManager.sol\";\nimport \"./DullahanVault.sol\";\nimport \"./modules/DullahanRegistry.sol\";\nimport \"./interfaces/IStakedAave.sol\";\nimport \"./interfaces/IAavePool.sol\";\nimport \"./interfaces/IGovernancePowerDelegationToken.sol\";\nimport \"./interfaces/IAaveRewardsController.sol\";\nimport {Errors} from \"./utils/Errors.sol\";\n\n/** @title Dullahan Pod contract\n *  @author Paladin\n *  @notice Dullahan Pod, unique to each user, allowing to depoist collateral,\n *          rent stkAAVE from the Dullahan Vault & borrow GHO\n */\ncontract DullahanPod is ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    // Constants\n\n    /** @notice Max value for BPS - 100% */\n    uint256 public constant MAX_BPS = 10000;\n    /** @notice Max value possible for an uint256 */\n    uint256 private constant MAX_UINT256 = 2**256 - 1;\n\n    /** @notice Minimum allowed amount of GHO to mint */\n    uint256 public constant MIN_MINT_AMOUNT = 1e9;\n\n    // Storage\n\n    /** @notice Is the Pod initialized */\n    bool public initialized;\n\n    /** @notice Address of the Pod manager */\n    address public manager;\n    /** @notice Address of the Vault */\n    address public vault;\n    /** @notice Address of the Registry */\n    address public registry;\n\n    /** @notice Address of the Pod owner */\n    address public podOwner;\n\n    /** @notice Address of the delegate receiving the Pod voting power */\n    address public votingPowerDelegate;\n    /** @notice Address of the delegate receiving the Pod proposal power */\n    address public proposalPowerDelegate;\n\n    /** @notice Address of the collateral in the Pod */\n    address public collateral;\n    /** @notice Address of the aToken for the collateral */\n    address public aToken;\n\n    /** @notice Address of the AAVE token */\n    address public aave;\n    /** @notice Address of the stkAAVE token */\n    address public stkAave;\n\n\n    // Events\n\n    /** @notice Event emitted when the Pod is initialized */\n    event PodInitialized(\n        address indexed podManager,\n        address indexed collateral,\n        address indexed podOwner,\n        address vault,\n        address registry\n    );\n\n    /** @notice Event emitted when collateral is deposited */\n    event CollateralDeposited(address indexed collateral, uint256 amount);\n    /** @notice Event emitted when collateral is withdrawn */\n    event CollateralWithdrawn(address indexed collateral, uint256 amount);\n    /** @notice Event emitted when collateral is liquidated */\n    event CollateralLiquidated(address indexed collateral, uint256 amount);\n\n    /** @notice Event emitted when GHO is minted */\n    event GhoMinted(uint256 mintedAmount);\n    /** @notice Event emitted when GHO is repayed */\n    event GhoRepayed(uint256 amountToRepay);\n\n    /** @notice Event emitted when stkAAVE is rented by the Pod */\n    event RentedStkAave();\n\n    /** @notice Event emitted when the Pod delegates are updated */\n    event UpdatedDelegate(address indexed newVotingDelegate, address indexed newProposalDelegate);\n    /** @notice Event emitted when the Pod registry is updated */\n    event UpdatedRegistry(address indexed oldRegistry, address indexed newRegistry);\n\n\n    // Modifers\n\n    /** @notice Check that the caller is the Pod owner */\n    modifier onlyPodOwner() {\n        if(msg.sender != podOwner) revert Errors.NotPodOwner();\n        _;\n    }\n\n    /** @notice Check that the caller is the manager */\n    modifier onlyManager() {\n        if(msg.sender != manager) revert Errors.NotPodManager();\n        _;\n    }\n\n    /** @notice Check that the Pod is initialized */\n    modifier isInitialized() {\n        if(!initialized) revert Errors.NotInitialized();\n        _;\n    }\n\n\n    // Constructor\n\n    constructor() {\n        manager = address(0xdEaD);\n        vault = address(0xdEaD);\n        registry = address(0xdEaD);\n        collateral = address(0xdEaD);\n        podOwner = address(0xdEaD);\n        votingPowerDelegate = address(0xdEaD);\n        proposalPowerDelegate = address(0xdEaD);\n    }\n\n    /**\n    * @notice Initialize the Pod with the given parameters\n    * @param _manager Address of the Manager\n    * @param _vault Address of the Vault\n    * @param _registry Address of the Registry\n    * @param _podOwner Address of the Pod owner\n    * @param _collateral Address of the collateral\n    * @param _aToken Address of the aToken for the collateral\n    * @param _votingPowerDelegate Address of the delegate for the voting power\n    * @param _proposalPowerDelegate Address of the delegate for the proposal power\n    */\n    function init(\n        address _manager,\n        address _vault,\n        address _registry,\n        address _podOwner,\n        address _collateral,\n        address _aToken,\n        address _votingPowerDelegate,\n        address _proposalPowerDelegate\n    ) external {\n        if(initialized) revert Errors.AlreadyInitialized();\n        if(manager == address(0xdEaD)) revert Errors.CannotInitialize();\n        if(\n            _manager == address(0)\n            || _vault == address(0)\n            || _registry == address(0)\n            || _podOwner == address(0)\n            || _collateral == address(0)\n            || _aToken == address(0)\n            || _votingPowerDelegate == address(0)\n            || _proposalPowerDelegate == address(0)\n        ) revert Errors.AddressZero();\n\n        initialized = true;\n        \n        manager = _manager;\n        vault = _vault;\n        registry = _registry;\n        podOwner = _podOwner;\n        collateral = _collateral;\n        votingPowerDelegate = _votingPowerDelegate;\n        proposalPowerDelegate = _proposalPowerDelegate;\n\n        aToken = _aToken;\n\n        // Fetch the stkAAVE address from the Registry\n        address _stkAave = DullahanRegistry(_registry).STK_AAVE();\n        stkAave = _stkAave;\n        aave = DullahanRegistry(registry).AAVE();\n\n        // Set full allowance for the Vault to be able to pull back the stkAAVE rented to this Pod\n        IERC20(_stkAave).safeIncreaseAllowance(_vault, type(uint256).max);\n\n        // Set the Delegates for this Pod's voting power\n        IGovernancePowerDelegationToken(_stkAave).delegateByType(\n            _votingPowerDelegate,\n            IGovernancePowerDelegationToken.DelegationType.VOTING_POWER\n        );\n        IGovernancePowerDelegationToken(_stkAave).delegateByType(\n            _proposalPowerDelegate,\n            IGovernancePowerDelegationToken.DelegationType.PROPOSITION_POWER\n        );\n\n        emit PodInitialized(_manager, _collateral, _podOwner, _vault, _registry);\n    }\n\n\n    // View functions\n\n    /**\n    * @notice Get the Pod's current collateral balance\n    * @return uint256 : Current collateral balance\n    */\n    function podCollateralBalance() external view returns(uint256) {\n        return IERC20(aToken).balanceOf(address(this));\n    }\n\n    /**\n    * @notice Get the Pod's current GHO debt balance\n    * @return uint256 : Current GHO debt balance\n    */\n    function podDebtBalance() public view returns(uint256) {\n        return IERC20(DullahanRegistry(registry).DEBT_GHO()).balanceOf(address(this));\n    }\n\n    /**\n    * @notice Get the stored amount of fees owed by this Pod\n    * @return uint256 : Stored amount of fees owed\n    */\n    function podOwedFees() external view returns(uint256) {\n        return IDullahanPodManager(manager).podOwedFees(address(this));\n    }\n\n\n    // State-changing functions\n\n    /**\n    * @notice Deposit collateral\n    * @dev Pull collateral in the Pod to deposit it in the Aave Pool\n    * @param amount Amount to deposit\n    */\n    function depositCollateral(uint256 amount) external nonReentrant isInitialized onlyPodOwner {\n        if(amount == 0) revert Errors.NullAmount();\n        if(!IDullahanPodManager(manager).updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n\n        IERC20 _collateral = IERC20(collateral);\n        // Pull the collateral from the Pod Owner\n        _collateral.safeTransferFrom(msg.sender, address(this), amount);\n\n        // And deposit it in the Aave Pool\n        address _aavePool = DullahanRegistry(registry).AAVE_POOL_V3();\n        _collateral.safeIncreaseAllowance(_aavePool, amount);\n        IAavePool(_aavePool).supply(address(_collateral), amount, address(this), 0);\n\n        emit CollateralDeposited(address(_collateral), amount);\n    }\n\n    /**\n    * @notice Withdraw collateral\n    * @param amount Amount to withdraw\n    * @param receiver Address to receive the collateral\n    */\n    // Can give MAX_UINT256 to withdraw full balance\n    function withdrawCollateral(uint256 amount, address receiver) external nonReentrant isInitialized onlyPodOwner {\n        if(amount == 0) revert Errors.NullAmount();\n        if(receiver == address(0)) revert Errors.AddressZero();\n        if(!IDullahanPodManager(manager).updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n        \n        _withdrawCollateral(amount, receiver);\n    }\n\n    /**\n    * @notice Claim any existing rewards from the Aave Rewards Controller for this Pod\n    * @param receiver Address to receive the rewards\n    */\n    function claimAaveExtraRewards(address receiver) external nonReentrant isInitialized onlyPodOwner {\n        if(receiver == address(0)) revert Errors.AddressZero();\n        address[] memory assets = new address[](2);\n        assets[0] = aToken;\n        assets[1] = DullahanRegistry(registry).DEBT_GHO();\n        // Claim any rewards accrued via the Aave Pool & send them directly to the given receiver\n        IAaveRewardsController(DullahanRegistry(registry).AAVE_REWARD_COONTROLLER()).claimAllRewards(assets, receiver);\n    }\n\n    /**\n    * @notice Claim Safety Module rewards & stake them in stkAAVE\n    */\n    function compoundStkAave() external nonReentrant isInitialized {\n        // Claim Aave Safety Module rewards for this Pod & stake them into stkAAVE directly\n        _getStkAaveRewards();\n    }\n\n    /**\n    * @notice Mint GHO & rent stkAAVE\n    * @dev Rent stkAAVE from the Vault & mint GHO with the best interest rate discount possible\n    * @param amountToMint Amount of GHO to be minted\n    * @param receiver Address to receive the minted GHO\n    * @return mintedAmount - uint256 : amount of GHO minted after fees\n    */\n    function mintGho(uint256 amountToMint, address receiver) external nonReentrant isInitialized onlyPodOwner returns(uint256 mintedAmount) {\n        if(amountToMint == 0) revert Errors.NullAmount();\n        if(receiver == address(0)) revert Errors.AddressZero();\n        if(amountToMint < MIN_MINT_AMOUNT) revert Errors.MintAmountUnderMinimum();\n        IDullahanPodManager _manager = IDullahanPodManager(manager);\n        if(!_manager.updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n\n        // Update this contract stkAAVE current balance is there is one\n        _getStkAaveRewards();\n\n        // Ask to rent stkAAVE based on amount wanted to be minted / already minted\n        // (will also take care of reverting if the Pod is not allowed to mint or can't receive stkAAVE)\n        if(!_manager.getStkAave(amountToMint)) revert Errors.MintingAllowanceFailed();\n\n        emit RentedStkAave();\n\n        // Mint GHO from the Aave Pool, with the Variable mode\n        address _ghoAddress = DullahanRegistry(registry).GHO();\n        IAavePool(DullahanRegistry(registry).AAVE_POOL_V3()).borrow(_ghoAddress, amountToMint, 2, 0, address(this)); // 2 => variable mode (might need to change that)\n\n        // Take the protocol minting fees & send them to the Pod Manager & notify it\n        // & Send the rest of the minted GHO to the given receiver\n        IERC20 _gho = IERC20(_ghoAddress);\n        uint256 mintFeeRatio = _manager.mintFeeRatio();\n        uint256 mintFeeAmount = (amountToMint * mintFeeRatio) / MAX_BPS;\n        _gho.safeTransfer(manager, mintFeeAmount);\n        _manager.notifyMintingFee(mintFeeAmount);\n\n        mintedAmount = amountToMint - mintFeeAmount;\n        _gho.safeTransfer(receiver, mintedAmount);\n\n        emit GhoMinted(mintedAmount);\n    }\n\n    /**\n    * @notice Repay GHO fees and debt\n    * @param amountToRepay Amount of GHO to de repaid\n    * @return bool : Success\n    */\n    // Can give MAX_UINT256 to repay everything (needs max allowance)\n    function repayGho(uint256 amountToRepay) external nonReentrant isInitialized onlyPodOwner returns(bool) {\n        if(amountToRepay == 0) revert Errors.NullAmount();\n        if(!IDullahanPodManager(manager).updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n        \n        return _repayGho(amountToRepay);\n    }\n\n    /**\n    * @notice Repay GHO fees and debt & withdraw collateral\n    * @dev Repay GHO fees & debt to be allowed to withdraw collateral\n    * @param repayAmount Amount of GHO to de repaid\n    * @param withdrawAmount Amount to withdraw\n    * @param receiver Address to receive the collateral\n    * @return bool : Success\n    */\n    function repayGhoAndWithdrawCollateral(\n        uint256 repayAmount,\n        uint256 withdrawAmount,\n        address receiver\n    ) external nonReentrant isInitialized onlyPodOwner returns(bool) {\n        if(repayAmount == 0 || withdrawAmount == 0) revert Errors.NullAmount();\n        if(receiver == address(0)) revert Errors.AddressZero();\n        if(!IDullahanPodManager(manager).updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n\n        bool repaySuccess = _repayGho(repayAmount);\n        if(!repaySuccess) revert Errors.RepayFailed();\n        \n        _withdrawCollateral(withdrawAmount, receiver);\n\n        return repaySuccess;\n    }\n\n    /**\n    * @notice Rent stkAAVE from the Vault to get the best interest rate reduction\n    * @return bool : Success\n    */\n    function rentStkAave() external nonReentrant isInitialized onlyPodOwner returns(bool) {\n        IDullahanPodManager _manager = IDullahanPodManager(manager);\n        if(!_manager.updatePodState(address(this))) revert Errors.FailPodStateUpdate();\n\n        // Update this contract stkAAVE current balance is there is one\n        _getStkAaveRewards();\n\n        // Ask to rent stkAAVE based on amount wanted to be minted / already minted\n        // (will also take care of reverting if the Pod is not allowed to mint or can't receive stkAAVE)\n        if(!IDullahanPodManager(manager).getStkAave(0)) revert Errors.MintingAllowanceFailed();\n\n        emit RentedStkAave();\n\n        return true;\n    }\n\n\n    // Manager only functions\n\n    /**\n    * @notice Liquidate Pod collateral to repay owed fees\n    * @dev Liquidate Pod collateral to repay owed fees, in the case the this Pod got liquidated on Aave market, and fees are still owed to Dullahan\n    * @param amount Amount of collateral to liquidate\n    * @param receiver Address to receive the collateral\n    */\n    function liquidateCollateral(uint256 amount, address receiver) external nonReentrant isInitialized onlyManager {\n        if(amount == 0) return;\n\n        // Withdraw the amount to be liquidated from the aave Pool\n        // (Using MAX_UINT256 here will withdraw everything)\n        IAavePool(DullahanRegistry(registry).AAVE_POOL_V3()).withdraw(collateral, amount, address(this));\n\n        // Send the tokens to the liquidator (here the given receiver)\n        IERC20(collateral).safeTransfer(receiver, amount);\n\n        emit CollateralLiquidated(collateral, amount);\n    }\n\n    /**\n    * @notice Update the Pod's delegate address & delegate the voting power to it\n    * @param newVotingDelegate Address of the new voting power delegate\n    * @param newProposalDelegate Address of the new proposal power delegate\n    */\n    function updateDelegation(address newVotingDelegate, address newProposalDelegate) external isInitialized onlyManager {\n        if(newVotingDelegate == address(0) || newProposalDelegate == address(0)) revert Errors.AddressZero();\n\n        votingPowerDelegate = newVotingDelegate;\n        proposalPowerDelegate = newProposalDelegate;\n\n        // Update the delegation to the new Delegate\n        IGovernancePowerDelegationToken(stkAave).delegateByType(\n            newVotingDelegate,\n            IGovernancePowerDelegationToken.DelegationType.VOTING_POWER\n        );\n        IGovernancePowerDelegationToken(stkAave).delegateByType(\n            newProposalDelegate,\n            IGovernancePowerDelegationToken.DelegationType.PROPOSITION_POWER\n        );\n\n        emit UpdatedDelegate(newVotingDelegate, newProposalDelegate);\n    }\n\n    /**\n    * @notice Update the Pod's Registry address\n    * @param newRegistry Address of the new Registry\n    */\n    function updateRegistry(address newRegistry) external isInitialized onlyManager {\n        if(newRegistry == address(0)) revert Errors.AddressZero();\n        if(newRegistry == registry) revert Errors.SameAddress();\n\n        address oldRegistry = registry;\n        registry = newRegistry;\n\n        emit UpdatedRegistry(oldRegistry, newRegistry);\n    }\n\n\n    // Internal functions\n\n    /**\n    * @dev Withdraw collateral from the Aave Pool directly to the given receiver (only if Pod fees are fully repaid)\n    * @param amount Amount to withdraw\n    * @param receiver Address to receive the collateral\n    */\n    function _withdrawCollateral(uint256 amount, address receiver) internal {\n        // Not allowed to withdraw collateral before paying the owed fees,\n        // in case we need to liquidate part if this collateral to pay\n        // the fees owed by this Pod.\n        if(\n            IDullahanPodManager(manager).podOwedFees(address(this)) > 0\n        ) revert Errors.CollateralBlocked();\n\n        // Withdraw from the Aave Pool & send directly to the given receiver\n        // If given MAX_UINT256, we want to withdraw all the collateral\n        uint256 withdrawnAmount = IAavePool(DullahanRegistry(registry).AAVE_POOL_V3()).withdraw(collateral, amount, receiver);\n\n        emit CollateralWithdrawn(collateral, withdrawnAmount);\n    }\n    \n    /**\n    * @dev Repay GHO owed fees & debt (fees in priority)\n    * @param amountToRepay Amount of GHO to be repayed\n    * @return bool : Success\n    */\n    function _repayGho(uint256 amountToRepay) internal returns(bool) {\n        IDullahanPodManager _manager = IDullahanPodManager(manager);\n\n        // Update this contract stkAAVE current balance is there is one\n        _getStkAaveRewards();\n\n        // Fetch the current owed fees for this Pod from the Pod Manager\n        uint256 owedFees = _manager.podOwedFees(address(this));\n        uint256 variableDebt = podDebtBalance();\n\n        // If given the MAX_UINT256, we want to repay the fees and all the debt\n        if(amountToRepay == MAX_UINT256) {\n            amountToRepay = owedFees + variableDebt;\n        }\n\n        // Pull the GHO from the Pod Owner\n        IERC20 _gho = IERC20(DullahanRegistry(registry).GHO());\n        _gho.safeTransferFrom(msg.sender, address(this), amountToRepay);\n\n        uint256 realRepayAmount;\n        uint256 feesToPay;\n\n        // Repay in priority the owed fees, and then the debt to the Aave Pool\n        if(owedFees >= amountToRepay) {\n            feesToPay = amountToRepay;\n        } else {\n            realRepayAmount = amountToRepay == MAX_UINT256 ? MAX_UINT256 : amountToRepay - owedFees;\n            feesToPay = owedFees;\n        }\n\n        // If there is owed fees to pay, transfer the needed amount to the Pod Manager & notify it\n        if(feesToPay > 0) {\n            _gho.safeTransfer(manager, feesToPay);\n            _manager.notifyPayFee(feesToPay);\n        }\n\n        // If there is GHO debt to be repayed, increase allowance to the Aave Pool and repay the debt\n        if(realRepayAmount > 0) {\n            address _aavePool = DullahanRegistry(registry).AAVE_POOL_V3();\n            if(_gho.allowance(address(this), _aavePool) != 0) _gho.safeApprove(_aavePool, 0);\n            _gho.safeIncreaseAllowance(_aavePool, realRepayAmount);\n            IAavePool(_aavePool).repay(address(_gho), realRepayAmount, 2, address(this)); // 2 => variable mode (might need to change that)\n        }\n\n        // Notify the Pod Manager, so not needed stkAave in this Pod\n        // can be freed & pull back by the Vaut\n        if(!_manager.freeStkAave(address(this))) revert Errors.FreeingStkAaveFailed();\n\n        // Send back any remaining GHO from in the Pod to the caller\n        uint256 remainingGho = _gho.balanceOf(address(this));\n        if(remainingGho > 0) {\n            _gho.safeTransfer(msg.sender, remainingGho);\n        }\n\n        emit GhoRepayed(amountToRepay);\n\n        return true;\n    }\n\n    /**\n    * @dev Claim AAVE rewards from the Safety Module & stake them to receive stkAAVE & notify the Manager\n    */\n    function _getStkAaveRewards() internal {\n        IStakedAave _stkAave = IStakedAave(stkAave);\n\n        // Get pending rewards amount\n        uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));\n\n        if(pendingRewards == 0) return;\n\n        // Claim the AAVE tokens\n        _stkAave.claimRewards(address(this), pendingRewards);\n\n        IERC20 _aave = IERC20(aave);\n        uint256 currentBalance = _aave.balanceOf(address(this));\n        \n        if(currentBalance > 0) {\n            // Increase allowance for the Safety Module & stake AAVE into stkAAVE\n            _aave.safeIncreaseAllowance(address(_stkAave), currentBalance);\n            _stkAave.stake(address(this), currentBalance);\n\n            // Notify the Pod Manager fro the new amount staked, so the tracking of\n            // the Pod rented amount & fees on that claim can be updated in the Vault\n            IDullahanPodManager(manager).notifyStkAaveClaim(currentBalance);\n        }\n    }\n\n\n\n}"
      },
      "contracts/DullahanVault.sol": {
        "content": "//██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗\n//██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║\n//██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║\n//██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║\n//██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║\n//╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝\n\n\npragma solidity 0.8.16;\n//SPDX-License-Identifier: BUSL-1.1\n\nimport \"./base/ScalingERC20.sol\";\nimport \"./interfaces/IERC4626.sol\";\nimport \"./oz/interfaces/IERC20.sol\";\nimport \"./oz/libraries/SafeERC20.sol\";\nimport \"./oz/utils/ReentrancyGuard.sol\";\nimport \"./oz/utils/Pausable.sol\";\nimport \"./interfaces/IStakedAave.sol\";\nimport \"./interfaces/IGovernancePowerDelegationToken.sol\";\nimport {Errors} from \"./utils/Errors.sol\";\nimport {WadRayMath} from  \"./utils/WadRayMath.sol\";\n\n/** @title DullahanVault contract\n *  @author Paladin\n *  @notice Main Dullahan Vault. IERC4626 compatible & ScalingERC20 token\n */\ncontract DullahanVault is IERC4626, ScalingERC20, ReentrancyGuard, Pausable {\n    using SafeERC20 for IERC20;\n    using WadRayMath for uint256;\n\n    // Constants\n\n    /** @notice Max value for BPS - 100% */\n    uint256 public constant MAX_BPS = 10000;\n    /** @notice Max value possible for an uint256 */\n    uint256 public constant MAX_UINT256 = 2**256 - 1;\n\n    /** @notice Amount to deposit to seed the Vault during initialization */\n    uint256 private constant SEED_DEPOSIT = 0.001 ether;\n\n    /** @notice Address of the stkAAVE token */\n    address public immutable STK_AAVE;\n    /** @notice Address of the AAVE token */\n    address public immutable AAVE;\n\n\n    // Struct\n\n    /** @notice PodsManager struct \n    *   rentingAllowed: Is the Manager allowed to rent from the Vault\n    *   totalRented: Total amount rented to the Manager (based on the AAVE max total supply, should be safe)\n    */\n    struct PodsManager {\n        bool rentingAllowed;\n        uint248 totalRented;\n    }\n\n\n    // Storage\n\n    /** @notice Is the Vault initialized */\n    bool public initialized;\n\n    /** @notice Address of the Vault admin */\n    address public admin;\n    /** @notice Address of the Vault pending admin */\n    address public pendingAdmin;\n\n    /** @notice Total amount of stkAAVE rented to Pod Managers */\n    uint256 public totalRentedAmount;\n\n    /** @notice Pod Manager states */\n    mapping(address => PodsManager) public podManagers;\n\n    /** @notice Address receiving the delegated voting power from the Vault */\n    address public votingPowerManager;\n    /** @notice Address receiving the delegated proposal power from the Vault */\n    address public proposalPowerManager;\n\n    /** @notice Percentage of funds to stay in the contract for withdraws */\n    uint256 public bufferRatio = 500;\n\n    /** @notice Amount accrued as Reserve */\n    uint256 public reserveAmount;\n    /** @notice Ratio of claimed rewards to be set as Reserve */\n    uint256 public reserveRatio;\n    /** @notice Address of the Reserve Manager */\n    address public reserveManager;\n\n\n    // Events\n\n    /** @notice Event emitted when the Vault is initialized */\n    event Initialized();\n\n    /** @notice Event emitted when stkAAVE is rented to a Pod */\n    event RentToPod(address indexed manager, address indexed pod, uint256 amount);\n    /** @notice Event emitted when stkAAVE claim is notified by a Pod */\n    event NotifyRentedAmount(address indexed manager, address indexed pod, uint256 addedAmount);\n    /** @notice Event emitted when stkAAVE is pulled back from a Pod */\n    event PullFromPod(address indexed manager, address indexed pod, uint256 amount);\n\n    /** @notice Event emitted when the adminship is transfered */\n    event AdminTransferred(\n        address indexed previousAdmin,\n        address indexed newAdmin\n    );\n    /** @notice Event emitted when a new pending admin is set */\n    event NewPendingAdmin(\n        address indexed previousPendingAdmin,\n        address indexed newPendingAdmin\n    );\n\n    /** @notice Event emitted when a new Pod Manager is added */\n    event NewPodManager(address indexed newManager);\n    /** @notice Event emitted when a Pod Manager is blocked */\n    event BlockedPodManager(address indexed manager);\n\n    /** @notice Event emitted when depositing in the Reserve */\n    event ReserveDeposit(address indexed from, uint256 amount);\n    /** @notice Event emitted when withdrawing from the Reserve */\n    event ReserveWithdraw(address indexed to, uint256 amount);\n\n    /** @notice Event emitted when the Voting maanger is updated */\n    event UpdatedVotingPowerManager(address indexed oldManager, address indexed newManager);\n    /** @notice Event emitted when the Proposal maanger is updated */\n    event UpdatedProposalPowerManager(address indexed oldManager, address indexed newManager);\n    /** @notice Event emitted when the Reserve manager is updated */\n    event UpdatedReserveManager(address indexed oldManager, address indexed newManager);\n    /** @notice Event emitted when the Buffer ratio is updated */\n    event UpdatedBufferRatio(uint256 oldRatio, uint256 newRatio);\n    /** @notice Event emitted when the Reserve ratio is updated */\n    event UpdatedReserveRatio(uint256 oldRatio, uint256 newRatio);\n\n    /** @notice Event emitted when an ERC20 token is recovered */\n    event TokenRecovered(address indexed token, uint256 amount);\n\n\n    // Modifers\n\n    /** @notice Check that the caller is the admin */\n    modifier onlyAdmin() {\n        if (msg.sender != admin) revert Errors.CallerNotAdmin();\n        _;\n    }\n\n    /** @notice Check that the caller is the admin or the Reserve maanger */\n    modifier onlyAllowed() {\n        if (msg.sender != admin && msg.sender != reserveManager) revert Errors.CallerNotAdmin();\n        _;\n    }\n\n    /** @notice Check that the contract is initialized */\n    modifier isInitialized() {\n        if (!initialized) revert Errors.NotInitialized();\n        _;\n    }\n\n\n    // Constructor\n\n    constructor(\n        address _admin,\n        uint256 _reserveRatio,\n        address _reserveManager,\n        address _aave,\n        address _stkAave,\n        string memory _name,\n        string memory _symbol\n    ) ScalingERC20(_name, _symbol) {\n        if(_admin == address(0) || _reserveManager == address(0) || _aave == address(0) || _stkAave == address(0)) revert Errors.AddressZero();\n        if(_reserveRatio == 0) revert Errors.NullAmount();\n\n        admin = _admin;\n\n        reserveRatio = _reserveRatio;\n        reserveManager = _reserveManager;\n\n        AAVE = _aave;\n        STK_AAVE = _stkAave;\n    }\n\n    /**\n    * @notice Initialize the Vault\n    * @dev Initialize the Vault by performing a seed deposit & delegating voting power\n    * @param _votingPowerManager Address to receive the voting power delegation\n    * @param _proposalPowerManager Address to receive the proposal power delegation\n    */\n    function init(address _votingPowerManager, address _proposalPowerManager) external onlyAdmin {\n        if(initialized) revert Errors.AlreadyInitialized();\n\n        initialized = true;\n\n        votingPowerManager = _votingPowerManager;\n        proposalPowerManager = _proposalPowerManager;\n\n        // Seed deposit to prevent 1 wei LP token exploit\n        _deposit(\n            SEED_DEPOSIT,\n            msg.sender,\n            msg.sender\n        );\n\n        // Set the delegates, so any received token updates the delegates power\n        IGovernancePowerDelegationToken(STK_AAVE).delegateByType(\n            _votingPowerManager,\n            IGovernancePowerDelegationToken.DelegationType.VOTING_POWER\n        );\n        IGovernancePowerDelegationToken(STK_AAVE).delegateByType(\n            _proposalPowerManager,\n            IGovernancePowerDelegationToken.DelegationType.PROPOSITION_POWER\n        );\n\n        emit Initialized();\n    }\n\n\n    // View functions\n\n    /**\n    * @notice Get the vault's asset\n    * @return address : Address of the asset\n    */\n    function asset() external view returns (address) {\n        return STK_AAVE;\n    }\n\n    /**\n    * @notice Get the total amount of assets in the Vault\n    * @return uint256 : total amount of assets\n    */\n    function totalAssets() public view returns (uint256) {\n        return\n            IERC20(STK_AAVE).balanceOf(address(this)) +\n            totalRentedAmount -\n            reserveAmount;\n    }\n\n    /**\n    * @notice Get the total supply of shares\n    * @return uint256 : Total supply of shares\n    */\n    function totalSupply()\n        public\n        view\n        override(ScalingERC20, IERC20)\n        returns (uint256)\n    {\n        return totalAssets();\n    }\n\n    /**\n    * @notice Get the current total amount of asset available in the Vault\n    * @return uint256 : Current total amount available\n    */\n    function totalAvailable() public view returns (uint256) {\n        uint256 availableBalance = IERC20(STK_AAVE).balanceOf(address(this));\n        availableBalance = reserveAmount >= availableBalance ? 0 : availableBalance - reserveAmount;\n        uint256 bufferAmount = (totalAssets() * bufferRatio) / MAX_BPS;\n        return availableBalance > bufferAmount ? availableBalance - bufferAmount : 0;\n    }\n\n    /**\n    * @notice Convert a given amount of assets to shares\n    * @param assets amount of assets\n    * @return uint256 : amount of shares\n    */\n    function convertToShares(uint256 assets) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return assets;\n    }\n\n    /**\n    * @notice Convert a given amount of shares to assets\n    * @param shares amount of shares\n    * @return uint256 : amount of assets\n    */\n    function convertToAssets(uint256 shares) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return shares;\n    }\n\n    /**\n    * @notice Return the amount of shares expected for depositing the given assets\n    * @param assets Amount of assets to be deposited\n    * @return uint256 : amount of shares\n    */\n    function previewDeposit(uint256 assets) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return assets;\n    }\n\n    /**\n    * @notice Return the amount of assets expected for minting the given shares\n    * @param shares Amount of shares to be minted\n    * @return uint256 : amount of assets\n    */\n    function previewMint(uint256 shares) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return shares;\n    }\n\n    /**\n    * @notice Return the amount of shares expected for withdrawing the given assets\n    * @param assets Amount of assets to be withdrawn\n    * @return uint256 : amount of shares\n    */\n    function previewWithdraw(uint256 assets) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return assets;\n    }\n\n    /**\n    * @notice Return the amount of assets expected for burning the given shares\n    * @param shares Amount of shares to be burned\n    * @return uint256 : amount of assets\n    */\n    function previewRedeem(uint256 shares) public pure returns (uint256) {\n        // Because we use a ScalingERC20, shares of the user will grow over time to match the owed assets\n        // (assets & shares are always 1:1)\n        return shares;\n    }\n\n    /**\n    * @notice Get the maximum amount that can be deposited by the user\n    * @param user User address\n    * @return uint256 : Max amount to deposit\n    */\n    function maxDeposit(address user) public view returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n    * @notice Get the maximum amount that can be minted by the user\n    * @param user User address\n    * @return uint256 : Max amount to mint\n    */\n    function maxMint(address user) public view returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n    * @notice Get the maximum amount that can be withdrawn by the user\n    * @param owner Owner address\n    * @return uint256 : Max amount to withdraw\n    */\n    function maxWithdraw(address owner) public view returns (uint256) {\n        return balanceOf(owner);\n    }\n\n    /**\n    * @notice Get the maximum amount that can be burned by the user\n    * @param owner Owner address\n    * @return uint256 : Max amount to burn\n    */\n    function maxRedeem(address owner) public view returns (uint256) {\n        return balanceOf(owner);\n    }\n\n    /**\n    * @notice Get the current index to convert between balance and scaled balances\n    * @return uint256 : Current index\n    */\n    function getCurrentIndex() public view returns(uint256) {\n        return _getCurrentIndex();\n    }\n\n    /**\n    * @notice Get the current delegates for the Vault voting power & proposal power\n    */\n    function getDelegates() external view returns(address votingPower, address proposalPower) {\n        return (votingPowerManager, proposalPowerManager);\n    }\n\n\n    // State-changing functions\n\n    /**\n    * @notice Deposit assets in the Vault & mint shares\n    * @param assets Amount to deposit\n    * @param receiver Address to receive the shares\n    * @return shares - uint256 : Amount of shares minted\n    */\n    function deposit(\n        uint256 assets,\n        address receiver\n    ) public isInitialized nonReentrant whenNotPaused returns (uint256 shares) {\n        (assets, shares) = _deposit(assets, receiver, msg.sender);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n    }\n\n    /**\n    * @notice Mint vault shares by depositing assets\n    * @param shares Amount of shares to mint\n    * @param receiver Address to receive the shares\n    * @return assets - uint256 : Amount of assets deposited\n    */\n    function mint(\n        uint256 shares,\n        address receiver\n        ) public isInitialized nonReentrant whenNotPaused returns (uint256 assets) {\n        (assets, shares) = _deposit(shares, receiver, msg.sender);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n    }\n\n    /**\n    * @notice Withdraw from the Vault & burn shares\n    * @param assets Amount of assets to withdraw\n    * @param receiver Address to receive the assets\n    * @param owner Address of the owner of the shares\n    * @return shares - uint256 : Amount of shares burned\n    */\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner\n    ) public isInitialized nonReentrant returns (uint256 shares) {\n        (uint256 _withdrawn, uint256 _burntShares) = _withdraw(\n            assets,\n            owner,\n            receiver,\n            msg.sender\n        );\n\n        emit Withdraw(msg.sender, receiver, owner, _withdrawn, _burntShares);\n        return _burntShares;\n    }\n\n    /**\n    * @notice Burn shares to withdraw from the Vault\n    * @param shares Amount of shares to burn\n    * @param receiver Address to receive the assets\n    * @param owner Address of the owner of the shares\n    * @return assets - uint256 : Amount of assets withdrawn\n    */\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner\n    ) public isInitialized nonReentrant returns (uint256 assets) {\n        (uint256 _withdrawn, uint256 _burntShares) = _withdraw(\n            shares,\n            owner,\n            receiver,\n            msg.sender\n        );\n\n        emit Withdraw(msg.sender, receiver, owner, _withdrawn, _burntShares);\n        return _withdrawn;\n    }\n\n    /**\n    * @notice Claim Safety Module rewards & stake them in stkAAVE\n    */\n    function updateStkAaveRewards() external nonReentrant {\n        _getStkAaveRewards();\n    }\n\n\n    // Pods Manager functions\n\n    /**\n    * @notice Rent stkAAVE for a Pod\n    * @dev Rent stkAAVE to a Pod, sending the amount & tracking the manager that requested \n    * @param pod Address of the Pod\n    * @param amount Amount to rent\n    */\n    function rentStkAave(address pod, uint256 amount) external nonReentrant {\n        address manager = msg.sender;\n        if(!podManagers[manager].rentingAllowed) revert Errors.CallerNotAllowedManager();\n        if(pod == address(0)) revert Errors.AddressZero();\n        if(amount == 0) revert Errors.NullAmount();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        IERC20 _stkAave = IERC20(STK_AAVE);\n\n        // Check that the asked amount is available :\n        // - Vault has enough asset for the asked amount\n        // - Asked amount does not include the buffer allocated to withdraws\n        uint256 availableBalance = _stkAave.balanceOf(address(this));\n        availableBalance = reserveAmount >= availableBalance ? 0 : availableBalance - reserveAmount;\n        uint256 bufferAmount = (totalAssets() * bufferRatio) / MAX_BPS;\n        if(availableBalance < bufferAmount) revert Errors.WithdrawBuffer();\n        if(amount > (availableBalance - bufferAmount)) revert Errors.NotEnoughAvailableFunds();\n\n        // Track the amount rented for the manager that requested it\n        // & send the token to the Pod\n        podManagers[manager].totalRented += safe248(amount);\n        totalRentedAmount += amount;\n        _stkAave.safeTransfer(pod, amount);\n    \n        emit RentToPod(manager, pod, amount);\n    }\n\n    /**\n    * @notice Notify a claim on rented stkAAVE\n    * @dev Notify the newly claimed rewards from rented stkAAVE to a Pod & add it as rented to the Pod\n    * @param pod Address of the Pod\n    * @param addedAmount Amount added\n    */\n    // To track pods stkAave claims & re-stake into the main balance for ScalingeRC20 logic\n    function notifyRentedAmount(address pod, uint256 addedAmount) external nonReentrant {\n        address manager = msg.sender;\n        if(podManagers[manager].totalRented == 0) revert Errors.NotUndebtedManager();\n        if(pod == address(0)) revert Errors.AddressZero();\n        if(addedAmount == 0) revert Errors.NullAmount();\n\n        // Update the total amount rented & the amount rented for the specific\n        // maanger with the amount claimed from Aave's Safety Module via the Pod\n        podManagers[manager].totalRented += safe248(addedAmount);\n        totalRentedAmount += addedAmount;\n\n        // Add the part taken as fees to the Reserve\n        reserveAmount += (addedAmount * reserveRatio) / MAX_BPS;\n\n        emit NotifyRentedAmount(manager, pod, addedAmount);\n    }\n\n    /**\n    * @notice Pull rented stkAAVE from a Pod\n    * @dev Pull stkAAVE from a Pod & update the tracked rented amount\n    * @param pod Address of the Pod\n    * @param amount Amount to pull\n    */\n    function pullRentedStkAave(address pod, uint256 amount) external nonReentrant {\n        address manager = msg.sender;\n        if(podManagers[manager].totalRented == 0) revert Errors.NotUndebtedManager();\n        if(pod == address(0)) revert Errors.AddressZero();\n        if(amount == 0) revert Errors.NullAmount();\n        if(amount > podManagers[manager].totalRented) revert Errors.AmountExceedsDebt();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        // Pull the tokens from the Pod, and update the tracked rented amount for the\n        // corresponding Manager\n        podManagers[manager].totalRented -= safe248(amount);\n        totalRentedAmount -= amount;\n        // We consider that pod give MAX_UINT256 allowance to this contract when created\n        IERC20(STK_AAVE).safeTransferFrom(pod, address(this), amount);\n\n        emit PullFromPod(manager, pod, amount);\n    }\n\n\n    // Internal functions\n\n    /**\n    * @dev Get the current index to convert between balance and scaled balances\n    * @return uint256 : Current index\n    */\n    function _getCurrentIndex() internal view override returns (uint256) {\n        if(_totalSupply == 0) return INITIAL_INDEX;\n        return totalAssets().rayDiv(_totalSupply);\n    }\n\n    /**\n    * @dev Pull assets to deposit in the Vault & mint shares\n    * @param amount Amount to deposit\n    * @param receiver Address to receive the shares\n    * @param depositor Address depositing the assets\n    * @return uint256 : Amount of assets deposited\n    * @return uint256 : Amount of shares minted\n    */\n    function _deposit(\n        uint256 amount,\n        address receiver,\n        address depositor\n    ) internal returns (uint256, uint256) {\n        if (receiver == address(0)) revert Errors.AddressZero();\n        if (amount == 0) revert Errors.NullAmount();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        // We need to get the index before pulling the assets\n        // so we can have the correct one based on previous stkAave claim\n        uint256 _currentIndex = _getCurrentIndex();\n\n        // Pull tokens from the depositor\n        IERC20(STK_AAVE).safeTransferFrom(depositor, address(this), amount);\n\n        // Mint the scaled balance of the user to match the deposited amount\n        uint256 minted = _mint(receiver, amount, _currentIndex);\n\n        afterDeposit(amount);\n\n        return (amount, minted);\n    }\n\n    /**\n    * @dev Withdraw assets from the Vault & send to the receiver & burn shares\n    * @param amount Amount to withdraw\n    * @param owner Address owning the shares\n    * @param receiver Address to receive the assets\n    * @param sender Address of the caller\n    * @return uint256 : Amount of assets withdrawn\n    * @return uint256 : Amount of shares burned\n    */\n    function _withdraw(\n        uint256 amount, // if `MAX_UINT256`, just withdraw everything\n        address owner,\n        address receiver,\n        address sender\n    ) internal returns (uint256, uint256) {\n        if (receiver == address(0) || owner == address(0)) revert Errors.AddressZero();\n        if (amount == 0) revert Errors.NullAmount();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        // If the user wants to withdraw their full balance\n        bool _maxWithdraw;\n        if(amount == MAX_UINT256) {\n            amount = balanceOf(owner);\n            _maxWithdraw = true;\n        }\n\n        // Check that the caller has the allowance to withdraw for the given owner\n        if (owner != sender) {\n            uint256 allowed = _allowances[owner][sender];\n            if (allowed < amount) revert Errors.ERC20_AmountOverAllowance();\n            if (allowed != type(uint256).max)\n                _allowances[owner][sender] = allowed - amount;\n        }\n\n        IERC20 _stkAave = IERC20(STK_AAVE);\n\n        // Check that the Vault has enough stkAave to send\n        uint256 availableBalance = _stkAave.balanceOf(address(this));\n        availableBalance = reserveAmount >= availableBalance ? 0 : availableBalance - reserveAmount;\n        if(amount > availableBalance) revert Errors.NotEnoughAvailableFunds();\n\n        // Burn the scaled balance matching the amount to withdraw\n        uint256 burned = _burn(owner, amount, _maxWithdraw);\n\n        beforeWithdraw(amount);\n\n        // Send the tokens to the given receiver\n        _stkAave.safeTransfer(receiver, amount);\n\n        return (amount, burned);\n    }\n\n    /**\n    * @dev Hook exectued before withdrawing\n    * @param amount Amount to withdraw\n    */\n    function beforeWithdraw(uint256 amount) internal {}\n\n    /**\n    * @dev Hook exectued after depositing\n    * @param amount Amount deposited\n    */\n    function afterDeposit(uint256 amount) internal {}\n\n    /**\n    * @dev Hook executed before each transfer\n    * @param from Sender address\n    * @param to Receiver address\n    * @param amount Amount to transfer\n    */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal isInitialized whenNotPaused override virtual {\n        super._beforeTokenTransfer(from, to, amount);\n    }\n\n    /**\n    * @dev Hook executed after each transfer\n    * @param from Sender address\n    * @param to Receiver address\n    * @param amount Amount to transfer\n    */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal override virtual {\n        super._afterTokenTransfer(from, to, amount);\n    }\n\n    /**\n    * @dev Claim AAVE rewards from the Safety Module & stake them to receive stkAAVE\n    */\n    function _getStkAaveRewards() internal {\n        IStakedAave _stkAave = IStakedAave(STK_AAVE);\n\n        // Get pending rewards amount\n        uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));\n\n        if (pendingRewards > 0) {\n            // Claim the AAVE tokens\n            _stkAave.claimRewards(address(this), pendingRewards);\n\n            // Set a part of the claimed amount as the Reserve (protocol fees)\n            reserveAmount += (pendingRewards * reserveRatio) / MAX_BPS;\n        }\n\n        IERC20 _aave = IERC20(AAVE);\n        uint256 currentBalance = _aave.balanceOf(address(this));\n        \n        if(currentBalance > 0) {\n            // Increase allowance for the Safety Module & stake AAVE into stkAAVE\n            _aave.safeIncreaseAllowance(STK_AAVE, currentBalance);\n            _stkAave.stake(address(this), currentBalance);\n        }\n    }\n\n\n    // Admin \n    \n    /**\n     * @notice Pause the contract\n     */\n    function pause() external onlyAdmin {\n        _pause();\n    }\n\n    /**\n     * @notice Unpause the contract\n     */\n    function unpause() external onlyAdmin {\n        _unpause();\n    }\n\n    /**\n    * @notice Set a given address as the new pending admin\n    * @param newAdmin Address to be the new admin\n    */\n    function transferAdmin(address newAdmin) external onlyAdmin {\n        if (newAdmin == address(0)) revert Errors.AddressZero();\n        if (newAdmin == admin) revert Errors.CannotBeAdmin();\n        address oldPendingAdmin = pendingAdmin;\n\n        pendingAdmin = newAdmin;\n\n        emit NewPendingAdmin(oldPendingAdmin, newAdmin);\n    }\n\n    /**\n    * @notice Accpet adminship of the contract (must be the pending admin)\n    */\n    function acceptAdmin() external {\n        if (msg.sender != pendingAdmin) revert Errors.CallerNotPendingAdmin();\n        address newAdmin = pendingAdmin;\n        address oldAdmin = admin;\n        admin = newAdmin;\n        pendingAdmin = address(0);\n\n        emit AdminTransferred(oldAdmin, newAdmin);\n        emit NewPendingAdmin(newAdmin, address(0));\n    }\n\n    /**\n    * @notice Add a new Pod Manager\n    * @param newManager Address of the new manager\n    */\n    function addPodManager(address newManager) external onlyAdmin {\n        if(newManager == address(0)) revert Errors.AddressZero();\n        if(podManagers[newManager].rentingAllowed) revert Errors.ManagerAlreadyListed();\n\n        podManagers[newManager].rentingAllowed = true;\n\n        emit NewPodManager(newManager);\n    }\n\n    /**\n    * @notice Block a Pod Manager\n    * @param manager Address of the manager\n    */\n    function blockPodManager(address manager) external onlyAdmin {\n        if(manager == address(0)) revert Errors.AddressZero();\n        if(!podManagers[manager].rentingAllowed) revert Errors.ManagerNotListed();\n\n        podManagers[manager].rentingAllowed = false;\n\n        emit BlockedPodManager(manager);\n    }\n\n    /**\n    * @notice Update the Vault's voting power manager & delegate the voting power to it\n    * @param newManager Address of the new manager\n    */\n    function updateVotingPowerManager(address newManager) external onlyAdmin {\n        if(newManager == address(0)) revert Errors.AddressZero();\n        if(newManager == votingPowerManager) revert Errors.SameAddress();\n\n        address oldManager = votingPowerManager;\n        votingPowerManager = newManager;\n\n        IGovernancePowerDelegationToken(STK_AAVE).delegateByType(\n            newManager,\n            IGovernancePowerDelegationToken.DelegationType.VOTING_POWER\n        );\n\n        emit UpdatedVotingPowerManager(oldManager, newManager);\n    }\n\n    /**\n    * @notice Update the Vault's proposal power manager & delegate the proposal power to it\n    * @param newManager Address of the new manager\n    */\n    function updateProposalPowerManager(address newManager) external onlyAdmin {\n        if(newManager == address(0)) revert Errors.AddressZero();\n        if(newManager == proposalPowerManager) revert Errors.SameAddress();\n\n        address oldManager = proposalPowerManager;\n        proposalPowerManager = newManager;\n\n        IGovernancePowerDelegationToken(STK_AAVE).delegateByType(\n            newManager,\n            IGovernancePowerDelegationToken.DelegationType.PROPOSITION_POWER\n        );\n\n        emit UpdatedProposalPowerManager(oldManager, newManager);\n    }\n\n    /**\n    * @notice Update the Vault's Reserve manager\n    * @param newManager Address of the new manager\n    */\n    function updateReserveManager(address newManager) external onlyAdmin {\n        if(newManager == address(0)) revert Errors.AddressZero();\n        if(newManager == reserveManager) revert Errors.SameAddress();\n\n        address oldManager = reserveManager;\n        reserveManager = newManager;\n\n        emit UpdatedReserveManager(oldManager, newManager);\n    }\n\n    /**\n    * @notice Uodate the reserve ratio parameter\n    * @param newRatio New ratio value\n    */\n    function updateReserveRatio(uint256 newRatio) external onlyAdmin {\n        if(newRatio > 1500) revert Errors.InvalidParameter();\n\n        uint256 oldRatio = reserveRatio;\n        reserveRatio = newRatio;\n\n        emit UpdatedReserveRatio(oldRatio, newRatio);\n    }\n\n    /**\n    * @notice Uodate the buffer ratio parameter\n    * @param newRatio New ratio value\n    */\n    function updateBufferRatio(uint256 newRatio) external onlyAdmin {\n        if(newRatio > 1500) revert Errors.InvalidParameter();\n\n        uint256 oldRatio = bufferRatio;\n        bufferRatio = newRatio;\n\n        emit UpdatedBufferRatio(oldRatio, newRatio);\n    }\n\n    /**\n     * @notice Deposit token in the reserve\n     * @param amount Amount of token to deposit\n     */\n    function depositToReserve(uint256 amount) external nonReentrant onlyAllowed returns(bool) {\n        if(amount == 0) revert Errors.NullAmount();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        IERC20(STK_AAVE).safeTransferFrom(msg.sender, address(this), amount);\n        reserveAmount += amount;\n\n        emit ReserveDeposit(msg.sender, amount);\n\n        return true;\n    }\n\n    /**\n     * @notice Withdraw tokens from the reserve to send to the given receiver\n     * @param amount Amount of token to withdraw\n     * @param receiver Address to receive the tokens\n     */\n    function withdrawFromReserve(uint256 amount, address receiver) external nonReentrant onlyAllowed returns(bool) {\n        if(amount == 0) revert Errors.NullAmount();\n        if(receiver == address(0)) revert Errors.AddressZero();\n        if(amount > reserveAmount) revert Errors.ReserveTooLow();\n\n        // Fetch Aave Safety Module rewards & stake them into stkAAVE\n        _getStkAaveRewards();\n\n        IERC20(STK_AAVE).safeTransfer(receiver, amount);\n        reserveAmount -= amount;\n\n        emit ReserveWithdraw(receiver, amount);\n\n        return true;\n    }\n\n    /**\n    * @notice Recover ERC2O tokens sent by mistake to the contract\n    * @dev Recover ERC2O tokens sent by mistake to the contract\n    * @param token Address of the ERC2O token\n    * @return bool: success\n    */\n    function recoverERC20(address token) external onlyAdmin returns(bool) {\n        if(token == AAVE || token == STK_AAVE) revert Errors.CannotRecoverToken();\n\n        uint256 amount = IERC20(token).balanceOf(address(this));\n        if(amount == 0) revert Errors.NullAmount();\n        IERC20(token).safeTransfer(admin, amount);\n\n        emit TokenRecovered(token, amount);\n\n        return true;\n    }\n\n    // Maths\n\n    function safe248(uint256 n) internal pure returns (uint248) {\n        if(n > type(uint248).max) revert Errors.NumberExceed248Bits();\n        return uint248(n);\n    }\n\n}"
      },
      "contracts/interfaces/IAavePool.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.16;\n\ninterface IAavePool {\n\n    function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n    function withdraw(address asset, uint256 amount, address to) external returns (uint256);\n\n    function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external;\n    function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256);\n    function repayWithATokens(address asset,uint256 amount,uint256 interestRateMode) external returns (uint256);\n\n    function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n    function getUserAccountData(address user) external view returns(\n        uint256 totalCollateralBase,\n        uint256 totalDebtBase,\n        uint256 availableBorrowsBase,\n        uint256 currentLiquidationThreshold,\n        uint256 ltv,\n        uint256 healthFactor\n    );\n\n}"
      },
      "contracts/interfaces/IAaveRewardsController.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.16;\n\ninterface IAaveRewardsController {\n\n    function getUserAccruedRewards(address user, address reward) external view returns (uint256);\n\n    function getUserRewards(\n        address[] calldata assets,\n        address user,\n        address reward\n    ) external view returns (uint256);\n\n    function getAllUserRewards(\n        address[] calldata assets,\n        address user\n    ) external view returns (\n        address[] memory rewardsList,\n        uint256[] memory unclaimedAmounts\n    );\n\n    function claimAllRewards(\n        address[] calldata assets,\n        address to\n    ) external returns (\n        address[] memory rewardsList,\n        uint256[] memory claimedAmounts\n    );\n\n}\n"
      },
      "contracts/interfaces/IDullahanPodManager.sol": {
        "content": "//██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗\n//██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║\n//██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║\n//██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║\n//██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║\n//╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝\n\n\npragma solidity 0.8.16;\n//SPDX-License-Identifier: MIT\n\ninterface IDullahanPodManager {\n\n    function mintFeeRatio() external view returns(uint256);\n\n    function podOwedFees(address pod) external view returns(uint256);\n\n    function updatePodState(address pod) external returns(bool);\n\n    function getStkAave(uint256 amountToMint) external returns(bool);\n    function freeStkAave(address pod) external returns(bool);\n\n    function notifyStkAaveClaim(uint256 claimedAmount) external;\n    function notifyPayFee(uint256 feeAmount) external;\n    function notifyMintingFee(uint256 feeAmount) external;\n\n}"
      },
      "contracts/interfaces/IERC4626.sol": {
        "content": "pragma solidity 0.8.16;\n//SPDX-License-Identifier: MIT\n\nimport \"../oz/interfaces/IERC20.sol\";\n\ninterface IERC4626 is IERC20 {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Deposit(\n        address indexed caller,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    event Withdraw(\n        address indexed caller,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /*//////////////////////////////////////////////////////////////\n                               IMMUTABLES\n    //////////////////////////////////////////////////////////////*/\n\n    function asset() external view returns (address);\n\n    /*//////////////////////////////////////////////////////////////\n                        DEPOSIT/WITHDRAWAL LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function deposit(uint256 assets, address receiver)\n        external\n        returns (uint256 shares);\n\n    function mint(uint256 shares, address receiver)\n        external\n        returns (uint256 assets);\n\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner\n    ) external returns (uint256 shares);\n\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner\n    ) external returns (uint256 assets);\n\n    /*//////////////////////////////////////////////////////////////\n                            ACCOUNTING LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function totalAssets() external view returns (uint256);\n\n    function convertToShares(uint256 assets) external view returns (uint256);\n\n    function convertToAssets(uint256 shares) external view returns (uint256);\n\n    function previewDeposit(uint256 assets) external view returns (uint256);\n\n    function previewMint(uint256 shares) external view returns (uint256);\n\n    function previewWithdraw(uint256 assets) external view returns (uint256);\n\n    function previewRedeem(uint256 shares) external view returns (uint256);\n\n    /*//////////////////////////////////////////////////////////////\n                     DEPOSIT/WITHDRAWAL LIMIT LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function maxDeposit(address) external view returns (uint256);\n\n    function maxMint(address) external view returns (uint256);\n\n    function maxWithdraw(address owner) external view returns (uint256);\n\n    function maxRedeem(address owner) external view returns (uint256);\n\n    /*//////////////////////////////////////////////////////////////\n                          INTERNAL HOOKS LOGIC\n    //////////////////////////////////////////////////////////////*/\n    /*\n    function beforeWithdraw(uint256 assets, uint256 shares) internal {}\n    function afterDeposit(uint256 assets, uint256 shares) internal {}\n    */\n}\n"
      },
      "contracts/interfaces/IGovernancePowerDelegationToken.sol": {
        "content": "//Aave Governance Token Interface\n\n// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.16;\n\ninterface IGovernancePowerDelegationToken {\n    enum DelegationType {\n        VOTING_POWER,\n        PROPOSITION_POWER\n    }\n\n    /**\n     * @dev emitted when a user delegates to another\n     * @param delegator the delegator\n     * @param delegatee the delegatee\n     * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER)\n     **/\n    event DelegateChanged(\n        address indexed delegator,\n        address indexed delegatee,\n        DelegationType delegationType\n    );\n\n    /**\n     * @dev emitted when an action changes the delegated power of a user\n     * @param user the user which delegated power has changed\n     * @param amount the amount of delegated power for the user\n     * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER)\n     **/\n    event DelegatedPowerChanged(\n        address indexed user,\n        uint256 amount,\n        DelegationType delegationType\n    );\n\n    /**\n     * @dev delegates the specific power to a delegatee\n     * @param delegatee the user which delegated power has changed\n     * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER)\n     **/\n    function delegateByType(address delegatee, DelegationType delegationType)\n        external;\n\n    /**\n     * @dev delegates all the powers to a specific user\n     * @param delegatee the user to which the power will be delegated\n     **/\n    function delegate(address delegatee) external;\n\n    /**\n     * @dev returns the delegatee of an user\n     * @param delegator the address of the delegator\n     **/\n    function getDelegateeByType(\n        address delegator,\n        DelegationType delegationType\n    ) external view returns (address);\n\n    /**\n     * @dev returns the current delegated power of a user. The current power is the\n     * power delegated at the time of the last snapshot\n     * @param user the user\n     **/\n    function getPowerCurrent(address user, DelegationType delegationType)\n        external\n        view\n        returns (uint256);\n\n    /**\n     * @dev returns the delegated power of a user at a certain block\n     * @param user the user\n     **/\n    function getPowerAtBlock(\n        address user,\n        uint256 blockNumber,\n        DelegationType delegationType\n    ) external view returns (uint256);\n\n    /**\n     * @dev returns the total supply at a certain block number\n     **/\n    function totalSupplyAt(uint256 blockNumber) external view returns (uint256);\n}\n"
      },
      "contracts/interfaces/IStakedAave.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.16;\n\ninterface IStakedAave {\n\n  event Staked(\n    address indexed from,\n    address indexed to,\n    uint256 assets,\n    uint256 shares\n  );\n  event Redeem(\n    address indexed from,\n    address indexed to,\n    uint256 assets,\n    uint256 shares\n  );\n\n  event RewardsAccrued(address user, uint256 amount);\n  event RewardsClaimed(address indexed from, address indexed to, uint256 amount);\n\n  event Cooldown(address indexed user);\n\n  function stake(address to, uint256 amount) external;\n\n  function redeem(address to, uint256 amount) external;\n\n  function cooldown() external;\n\n  function claimRewards(address to, uint256 amount) external;\n\n  function getTotalRewardsBalance(address staker) external view returns (uint256);\n}"
      },
      "contracts/modules/DullahanRegistry.sol": {
        "content": "//██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗\n//██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║\n//██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║\n//██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║\n//██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║\n//╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝\n\n\npragma solidity 0.8.16;\n//SPDX-License-Identifier: BUSL-1.1\n\nimport \"../utils/Owner.sol\";\nimport {Errors} from \"../utils/Errors.sol\";\n\n/** @title Dullahan Registry contract\n *  @author Paladin\n *  @notice Registry, for all Aave related addresses & some Dullahan addresses\n */\ncontract DullahanRegistry is Owner {\n\n    // Storage\n\n    /** @notice Address of the stkAAVE token */\n    address public immutable STK_AAVE;\n    /** @notice Address of the AAVE token */\n    address public immutable AAVE;\n\n    /** @notice Address of the GHO token */\n    address public immutable GHO;\n    /** @notice Address of the GHO debt token */\n    address public immutable DEBT_GHO;\n\n    /** @notice Address of the Aave v3 Pool */\n    address public immutable AAVE_POOL_V3;\n\n    /** @notice Address of the Aave rewards controller */\n    address public immutable AAVE_REWARD_COONTROLLER;\n\n    /** @notice Address of the Dullahan Vault */\n    address public dullahanVault;\n\n    /** @notice Address of Dullahan Pod Managers */\n    address[] public dullahanPodManagers;\n\n    // Events\n\n    /** @notice Event emitted when the Vault is set */\n    event SetVault(address indexed vault);\n    /** @notice Event emitted when a Manager is added */\n    event AddPodManager(address indexed newManager);\n\n\n    // Constructor\n    constructor(\n        address _aave,\n        address _stkAave,\n        address _gho,\n        address _ghoDebt,\n        address _aavePool,\n        address _aaveRewardController\n    ) {\n        if(\n            _aave == address(0)\n            || _stkAave == address(0)\n            || _gho == address(0)\n            || _ghoDebt == address(0)\n            || _aavePool == address(0)\n            || _aaveRewardController == address(0)\n        ) revert Errors.AddressZero();\n\n        STK_AAVE = _stkAave;\n        AAVE = _aave;\n\n        GHO = _gho;\n        DEBT_GHO = _ghoDebt;\n\n        AAVE_POOL_V3 = _aavePool;\n\n        AAVE_REWARD_COONTROLLER = _aaveRewardController;\n    }\n\n    /**\n    * @notice Set the Dullahan Vault\n    * @param vault address of the vault\n    */\n    function setVault(address vault) external onlyOwner {\n        if(vault == address(0)) revert Errors.AddressZero();\n        if(dullahanVault != address(0)) revert Errors.VaultAlreadySet();\n\n        dullahanVault = vault;\n\n        emit SetVault(vault);\n    }\n\n    /**\n    * @notice Add a Pod Manager\n    * @param manager Address of the new manager\n    */\n    function addPodManager(address manager) external onlyOwner {\n        if(manager == address(0)) revert Errors.AddressZero();\n\n        // Check in the Manager list that it's not already present\n        address[] memory _managers = dullahanPodManagers;\n        uint256 length = _managers.length;\n        for(uint256 i; i < length;){\n            if(_managers[i] == manager) revert Errors.AlreadyListedManager();\n            unchecked { ++i; }\n        }\n\n        dullahanPodManagers.push(manager);\n\n        emit AddPodManager(manager);\n    }\n\n    /**\n    * @notice Get the list of Pod Managers\n    * @return address[] : List of Pod Managers\n    */\n    function getPodManagers() external view returns(address[] memory) {\n        return dullahanPodManagers;\n    }\n\n}"
      },
      "contracts/oz/interfaces/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\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 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    /**\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 `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, 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 `from` to `to` 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 from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}"
      },
      "contracts/oz/libraries/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../interfaces/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}"
      },
      "contracts/oz/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\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     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 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 functionCallWithValue(target, data, 0, \"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                /// @solidity memory-safe-assembly\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}"
      },
      "contracts/oz/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}"
      },
      "contracts/oz/utils/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}"
      },
      "contracts/oz/utils/Pausable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Context.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 *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    bool private _paused;\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    constructor() {\n        _paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        require(!paused(), \"Pausable: paused\");\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        require(paused(), \"Pausable: not paused\");\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n}"
      },
      "contracts/oz/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\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 {\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    constructor() {\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 making 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}"
      },
      "contracts/utils/Errors.sol": {
        "content": "pragma solidity 0.8.16;\n//SPDX-License-Identifier: MIT\n\nlibrary Errors {\n\n    // Common Errors\n    error AddressZero();\n    error NullAmount();\n    error IncorrectRewardToken();\n    error SameAddress();\n    error InequalArraySizes();\n    error EmptyArray();\n    error EmptyParameters();\n    error NotInitialized();\n    error AlreadyInitialized();\n    error CannotInitialize();\n    error InvalidParameter();\n    error CannotRecoverToken();\n    error NullWithdraw();\n    error AlreadyListedManager();\n    error NotListedManager();\n\n    // Access Control Erros\n    error CallerNotAdmin();\n    error CannotBeAdmin();\n    error CallerNotPendingAdmin();\n    error CallerNotAllowed();\n\n    // ERC20 Errors\n    error ERC20_ApproveAddressZero();\n    error ERC20_AllowanceUnderflow();\n    error ERC20_AmountOverAllowance();\n    error ERC20_AddressZero();\n    error ERC20_SelfTransfer();\n    error ERC20_NullAmount();\n    error ERC20_AmountExceedBalance();\n\n    // Maths Errors\n    error NumberExceed96Bits();\n    error NumberExceed128Bits();\n    error NumberExceed248Bits();\n\n    // Vault Errors\n    error ManagerAlreadyListed();\n    error ManagerNotListed();\n    error NotEnoughAvailableFunds();\n    error WithdrawBuffer();\n    error ReserveTooLow();\n    error CallerNotAllowedManager();\n    error NotUndebtedManager();\n    error AmountExceedsDebt();\n\n    // Vaults Rewards Errors\n    error NullScaledAmount();\n    error AlreadyListedDepositor();\n    error NotListedDepositor();\n    error ClaimNotAllowed();\n\n    // Pods Errors\n    error NotPodOwner();\n    error NotPodManager();\n    error FailPodStateUpdate();\n    error MintAmountUnderMinimum();\n    error RepayFailed();\n\n    // Pods Manager Errors\n    error CallerNotValidPod();\n    error CollateralBlocked();\n    error MintingAllowanceFailed();\n    error FreeingStkAaveFailed();\n    error CollateralAlreadyListed();\n    error CollateralNotListed();\n    error CollateralNotAllowed();\n    error PodInvalid();\n    error FailStateUpdate();\n    error PodNotLiquidable();\n\n    // Registry Errors\n    error VaultAlreadySet();\n\n    // Zap Errors\n    error InvalidSourceToken();\n    error DepositFailed();\n\n    // Wrapper Errors\n    error NullConvertedAmount();\n\n}"
      },
      "contracts/utils/Owner.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.16;\n\nimport \"../oz/utils/Ownable.sol\";\n\n/** @title Extend OZ Ownable contract  */\n/// @author Paladin\n\ncontract Owner is Ownable {\n\n    address public pendingOwner;\n\n    event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);\n\n    error CannotBeOwner();\n    error CallerNotPendingOwner();\n    error OwnerAddressZero();\n\n    function transferOwnership(address newOwner) public override virtual onlyOwner {\n        if(newOwner == address(0)) revert OwnerAddressZero();\n        if(newOwner == owner()) revert CannotBeOwner();\n        address oldPendingOwner = pendingOwner;\n\n        pendingOwner = newOwner;\n\n        emit NewPendingOwner(oldPendingOwner, newOwner);\n    }\n\n    function acceptOwnership() public virtual {\n        if(msg.sender != pendingOwner) revert CallerNotPendingOwner();\n        address newOwner = pendingOwner;\n        _transferOwnership(pendingOwner);\n        pendingOwner = address(0);\n\n        emit NewPendingOwner(newOwner, address(0));\n    }\n\n}"
      },
      "contracts/utils/WadRayMath.sol": {
        "content": "// SPDX-License-Identifier: GNU AGPLv3\npragma solidity ^0.8.0;\n\n/// @title WadRayMath.\n/// @author Morpho Labs.\n/// @custom:contact security@morpho.xyz\n/// @notice Optimized version of Aave V3 math library WadRayMath to conduct wad and ray manipulations: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/WadRayMath.sol\nlibrary WadRayMath {\n    /// CONSTANTS ///\n\n    uint256 internal constant WAD = 1e18;\n    uint256 internal constant HALF_WAD = 0.5e18;\n    uint256 internal constant RAY = 1e27;\n    uint256 internal constant HALF_RAY = 0.5e27;\n    uint256 internal constant WAD_RAY_RATIO = 1e9;\n    uint256 internal constant HALF_WAD_RAY_RATIO = 0.5e9;\n    uint256 internal constant MAX_UINT256 = 2**256 - 1; // Not possible to use type(uint256).max in yul.\n    uint256 internal constant MAX_UINT256_MINUS_HALF_WAD = 2**256 - 1 - 0.5e18;\n    uint256 internal constant MAX_UINT256_MINUS_HALF_RAY = 2**256 - 1 - 0.5e27;\n\n    /// INTERNAL ///\n\n    /// @dev Multiplies two wad, rounding half up to the nearest wad.\n    /// @param x Wad.\n    /// @param y Wad.\n    /// @return z The result of x * y, in wad.\n    function wadMul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        // Let y > 0\n        // Overflow if (x * y + HALF_WAD) > type(uint256).max\n        // <=> x * y > type(uint256).max - HALF_WAD\n        // <=> x > (type(uint256).max - HALF_WAD) / y\n        assembly {\n            if mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_WAD, y))) {\n                revert(0, 0)\n            }\n\n            z := div(add(mul(x, y), HALF_WAD), WAD)\n        }\n    }\n\n    /// @dev Divides two wad, rounding half up to the nearest wad.\n    /// @param x Wad.\n    /// @param y Wad.\n    /// @return z The result of x / y, in wad.\n    function wadDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        // Overflow if y == 0\n        // Overflow if (x * WAD + y / 2) > type(uint256).max\n        // <=> x * WAD > type(uint256).max - y / 2\n        // <=> x > (type(uint256).max - y / 2) / WAD\n        assembly {\n            z := div(y, 2)\n            if iszero(mul(y, iszero(gt(x, div(sub(MAX_UINT256, z), WAD))))) {\n                revert(0, 0)\n            }\n\n            z := div(add(mul(WAD, x), z), y)\n        }\n    }\n\n    /// @dev Multiplies two ray, rounding half up to the nearest ray.\n    /// @param x Ray.\n    /// @param y Ray.\n    /// @return z The result of x * y, in ray.\n    function rayMul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        // Let y > 0\n        // Overflow if (x * y + HALF_RAY) > type(uint256).max\n        // <=> x * y > type(uint256).max - HALF_RAY\n        // <=> x > (type(uint256).max - HALF_RAY) / y\n        assembly {\n            if mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_RAY, y))) {\n                revert(0, 0)\n            }\n\n            z := div(add(mul(x, y), HALF_RAY), RAY)\n        }\n    }\n\n    /// @dev Divides two ray, rounding half up to the nearest ray.\n    /// @param x Ray.\n    /// @param y Ray.\n    /// @return z The result of x / y, in ray.\n    function rayDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        // Overflow if y == 0\n        // Overflow if (x * RAY + y / 2) > type(uint256).max\n        // <=> x * RAY > type(uint256).max - y / 2\n        // <=> x > (type(uint256).max - y / 2) / RAY\n        assembly {\n            z := div(y, 2)\n            if iszero(mul(y, iszero(gt(x, div(sub(MAX_UINT256, z), RAY))))) {\n                revert(0, 0)\n            }\n\n            z := div(add(mul(RAY, x), z), y)\n        }\n    }\n\n    /// @dev Casts ray down to wad.\n    /// @param x Ray.\n    /// @return y = x converted to wad, rounded half up to the nearest wad.\n    function rayToWad(uint256 x) internal pure returns (uint256 y) {\n        assembly {\n            // If x % WAD_RAY_RATIO >= HALF_WAD_RAY_RATIO, round up.\n            y := add(div(x, WAD_RAY_RATIO), iszero(lt(mod(x, WAD_RAY_RATIO), HALF_WAD_RAY_RATIO)))\n        }\n    }\n\n    /// @dev Converts wad up to ray.\n    /// @param x Wad.\n    /// @return y = x converted in ray.\n    function wadToRay(uint256 x) internal pure returns (uint256 y) {\n        assembly {\n            y := mul(WAD_RAY_RATIO, x)\n            // Revert if y / WAD_RAY_RATIO != x\n            if iszero(eq(div(y, WAD_RAY_RATIO), x)) {\n                revert(0, 0)\n            }\n        }\n    }\n}"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}