ETH Price: $2,194.88 (-3.85%)

Transaction Decoder

Block:
19633675 at Apr-11-2024 04:49:47 PM +UTC
Transaction Fee:
0.003785868553764675 ETH $8.31
Gas Used:
148,901 Gas / 25.425407175 Gwei

Emitted Events:

390 Stone.Transfer( from=[Receiver] StoneVault, to=0x0000000000000000000000000000000000000000, value=149947625000000000000 )
391 StoneVault.Withdrawn( account=[Sender] 0xc4de91d0683a0765790335d10828c3accae54909, amount=151963223544313045397, round=92 )

Account State Difference:

  Address   Before After State Difference Code
(Titan Builder)
11.292508285860366139 Eth11.292510352136761286 Eth0.000002066276395147
0x71229856...2b145bD3C
0x9485711f...BDc7E9ad9 10,067.14052692570554049 Eth9,915.177303381392495093 Eth151.963223544313045397
0xA62F9C5a...d81B90572
(StakeStone: Stone Vault)
0xc4DE91d0...ccAE54909
0.077007182969732851 Eth
Nonce: 5
152.036444858729013573 Eth
Nonce: 6
151.959437675759280722

Execution Trace

StoneVault.instantWithdraw( _amount=151963223544313045397, _shares=0 ) => ( actualWithdrawn=151963223544313045397 )
  • AssetsVault.STATICCALL( )
  • AssetsVault.STATICCALL( )
  • StrategyController.CALL( )
    • 0xe942cdd0af66ab9ab06515701fa3707ec7deb93e.CALL( )
      • AppProxyUpgradeable.70a08231( )
        • KernelProxy.be00bbd8( )
          • Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=3CA7C3E38968823CCB4C78EA688DF41356F182AE1D159E4EE608D30D68CEF320 ) => ( 0x17144556fd3424EDC8Fc8A4C940B2D04936d17eb )
          • Lido.balanceOf( _account=0xE942cDd0AF66aB9AB06515701fa3707Ec7deB93e ) => ( 188384098450271885651604 )
          • 0xfaac8b3fba2fcc01e4ddb5d5fc761578d0d05545.CALL( )
          • Minter.burn( _from=0xA62F9C5af106FeEE069F38dE51098D9d81B90572, _amount=149947625000000000000 )
            • Stone.burn( _from=0xA62F9C5af106FeEE069F38dE51098D9d81B90572, _amount=149947625000000000000 )
            • AssetsVault.STATICCALL( )
            • AssetsVault.withdraw( _to=0xc4DE91d0683a0765790335D10828C3AccAE54909, _amount=151963223544313045397 )
              • ETH 151.963223544313045397 0xc4de91d0683a0765790335d10828c3accae54909.CALL( )
                File 1 of 9: StoneVault
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
                import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                import {Minter} from "./token/Minter.sol";
                import {Stone} from "./token/Stone.sol";
                import {AssetsVault} from "./AssetsVault.sol";
                import {StrategyController} from "./strategies/StrategyController.sol";
                import {VaultMath} from "./libraries/VaultMath.sol";
                contract StoneVault is ReentrancyGuard, Ownable {
                    uint256 internal constant MULTIPLIER = 1e18;
                    uint256 internal constant ONE_HUNDRED_PERCENT = 1e6;
                    uint256 internal constant MAXMIUM_FEE_RATE = ONE_HUNDRED_PERCENT / 100; // 1%
                    uint256 internal constant MINIMUM_REBASE_INTERVAL = 7 * 24 * 60 * 60;
                    uint256 public constant VERSION = 1;
                    uint256 public rebaseTimeInterval = 24 * 60 * 60;
                    address public immutable minter;
                    address public immutable stone;
                    address payable public immutable strategyController;
                    address payable public immutable assetsVault;
                    address public proposal;
                    address public feeRecipient;
                    uint256 public latestRoundID;
                    uint256 public withdrawableAmountInPast;
                    uint256 public withdrawingSharesInPast;
                    uint256 public withdrawingSharesInRound;
                    uint256 public withdrawFeeRate;
                    uint256 public rebaseTime;
                    mapping(uint256 => uint256) public roundPricePerShare;
                    mapping(uint256 => uint256) public settlementTime;
                    mapping(address => UserReceipt) public userReceipts;
                    struct UserReceipt {
                        uint256 withdrawRound;
                        uint256 withdrawShares;
                        uint256 withdrawableAmount;
                    }
                    event Deposit(
                        address indexed account,
                        uint256 amount,
                        uint256 mint,
                        uint256 round
                    );
                    event InitiateWithdraw(
                        address indexed account,
                        uint256 shares,
                        uint256 round
                    );
                    event CancelWithdraw(
                        address indexed account,
                        uint256 amount,
                        uint256 round
                    );
                    event Withdrawn(address indexed account, uint256 amount, uint256 round);
                    event WithdrawnFromStrategy(
                        address indexed account,
                        uint256 amount,
                        uint256 actualAmount,
                        uint256 round
                    );
                    event RollToNextRound(
                        uint256 round,
                        uint256 vaultIn,
                        uint256 vaultOut,
                        uint256 sharePrice
                    );
                    event StragetyAdded(address strategy);
                    event StragetyDestroyed(address strategy);
                    event StragetyCleared(address strategy);
                    event PortfolioConfigUpdated(address[] strategies, uint256[] ratios);
                    event FeeCharged(address indexed account, uint256 amount);
                    event SetWithdrawFeeRate(uint256 oldRate, uint256 newRate);
                    event SetFeeRecipient(address oldAddr, address newAddr);
                    event SetRebaseInterval(uint256 interval);
                    modifier onlyProposal() {
                        require(proposal == msg.sender, "not proposal");
                        _;
                    }
                    constructor(
                        address _minter,
                        address _proposal,
                        address payable _assetsVault,
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) {
                        require(
                            _minter != address(0) &&
                                _proposal != address(0) &&
                                _assetsVault != address(0),
                            "ZERO ADDRESS"
                        );
                        uint256 length = _strategies.length;
                        for (uint256 i; i < length; i++) {
                            require(_strategies[i] != address(0), "ZERO ADDRESS");
                        }
                        minter = _minter;
                        proposal = _proposal;
                        assetsVault = _assetsVault;
                        feeRecipient = msg.sender;
                        StrategyController controller = new StrategyController(
                            _assetsVault,
                            _strategies,
                            _ratios
                        );
                        strategyController = payable(address(controller));
                        stone = Minter(_minter).stone();
                        roundPricePerShare[0] = MULTIPLIER;
                        latestRoundID = 0;
                    }
                    function deposit()
                        external
                        payable
                        nonReentrant
                        returns (uint256 mintAmount)
                    {
                        mintAmount = _depositFor(msg.value, msg.sender);
                    }
                    function depositFor(
                        address _user
                    ) external payable nonReentrant returns (uint256 mintAmount) {
                        mintAmount = _depositFor(msg.value, _user);
                    }
                    function _depositFor(
                        uint256 _amount,
                        address _user
                    ) internal returns (uint256 mintAmount) {
                        require(_amount != 0, "too small");
                        uint256 sharePrice;
                        uint256 currSharePrice = currentSharePrice();
                        if (latestRoundID == 0) {
                            sharePrice = MULTIPLIER;
                        } else {
                            uint256 latestSharePrice = roundPricePerShare[latestRoundID - 1];
                            sharePrice = latestSharePrice > currSharePrice
                                ? latestSharePrice
                                : currSharePrice;
                        }
                        mintAmount = (_amount * MULTIPLIER) / sharePrice;
                        AssetsVault(assetsVault).deposit{value: address(this).balance}();
                        Minter(minter).mint(_user, mintAmount);
                        emit Deposit(_user, _amount, mintAmount, latestRoundID);
                    }
                    function requestWithdraw(uint256 _shares) external nonReentrant {
                        require(_shares != 0, "too small");
                        require(latestRoundID != 0, "should withdraw instantly");
                        Stone stoneToken = Stone(stone);
                        Minter stoneMinter = Minter(minter);
                        require(stoneToken.balanceOf(msg.sender) >= _shares, "exceed balance");
                        TransferHelper.safeTransferFrom(
                            stone,
                            msg.sender,
                            address(this),
                            _shares
                        );
                        withdrawingSharesInRound = withdrawingSharesInRound + _shares;
                        UserReceipt storage receipt = userReceipts[msg.sender];
                        if (receipt.withdrawRound == latestRoundID) {
                            receipt.withdrawShares = receipt.withdrawShares + _shares;
                        } else if (receipt.withdrawRound == 0) {
                            receipt.withdrawShares = _shares;
                            receipt.withdrawRound = latestRoundID;
                        } else {
                            // Withdraw previous round share first
                            uint256 withdrawAmount = VaultMath.sharesToAsset(
                                receipt.withdrawShares,
                                roundPricePerShare[receipt.withdrawRound]
                            );
                            stoneMinter.burn(address(this), receipt.withdrawShares);
                            withdrawingSharesInPast =
                                withdrawingSharesInPast -
                                receipt.withdrawShares;
                            receipt.withdrawShares = _shares;
                            receipt.withdrawableAmount =
                                receipt.withdrawableAmount +
                                withdrawAmount;
                            receipt.withdrawRound = latestRoundID;
                        }
                        emit InitiateWithdraw(msg.sender, _shares, latestRoundID);
                    }
                    function cancelWithdraw(uint256 _shares) external nonReentrant {
                        require(_shares != 0, "too small");
                        UserReceipt storage receipt = userReceipts[msg.sender];
                        require(receipt.withdrawRound == latestRoundID, "no pending withdraw");
                        require(receipt.withdrawShares >= _shares, "exceed pending withdraw");
                        receipt.withdrawShares = receipt.withdrawShares - _shares;
                        TransferHelper.safeTransfer(stone, msg.sender, _shares);
                        if (receipt.withdrawShares == 0) {
                            receipt.withdrawRound = 0;
                        }
                        withdrawingSharesInRound = withdrawingSharesInRound - _shares;
                        emit CancelWithdraw(msg.sender, _shares, latestRoundID);
                    }
                    function instantWithdraw(
                        uint256 _amount,
                        uint256 _shares
                    ) external nonReentrant returns (uint256 actualWithdrawn) {
                        require(_amount != 0 || _shares != 0, "too small");
                        AssetsVault aVault = AssetsVault(assetsVault);
                        Minter stoneMinter = Minter(minter);
                        (uint256 idleAmount, ) = getVaultAvailableAmount();
                        if (_amount != 0) {
                            UserReceipt storage receipt = userReceipts[msg.sender];
                            if (
                                receipt.withdrawRound != latestRoundID &&
                                receipt.withdrawRound != 0
                            ) {
                                // Withdraw previous round share first
                                uint256 withdrawAmount = VaultMath.sharesToAsset(
                                    receipt.withdrawShares,
                                    roundPricePerShare[receipt.withdrawRound]
                                );
                                stoneMinter.burn(address(this), receipt.withdrawShares);
                                withdrawingSharesInPast =
                                    withdrawingSharesInPast -
                                    receipt.withdrawShares;
                                receipt.withdrawShares = 0;
                                receipt.withdrawableAmount =
                                    receipt.withdrawableAmount +
                                    withdrawAmount;
                                receipt.withdrawRound = 0;
                            }
                            require(
                                receipt.withdrawableAmount >= _amount,
                                "exceed withdrawable"
                            );
                            receipt.withdrawableAmount = receipt.withdrawableAmount - _amount;
                            withdrawableAmountInPast = withdrawableAmountInPast - _amount;
                            actualWithdrawn = _amount;
                            emit Withdrawn(msg.sender, _amount, latestRoundID);
                        }
                        if (_shares != 0) {
                            uint256 sharePrice;
                            if (latestRoundID == 0) {
                                sharePrice = MULTIPLIER;
                            } else {
                                uint256 currSharePrice = currentSharePrice();
                                uint256 latestSharePrice = roundPricePerShare[
                                    latestRoundID - 1
                                ];
                                sharePrice = latestSharePrice < currSharePrice
                                    ? latestSharePrice
                                    : currSharePrice;
                            }
                            uint256 ethAmount = VaultMath.sharesToAsset(_shares, sharePrice);
                            stoneMinter.burn(msg.sender, _shares);
                            if (ethAmount <= idleAmount) {
                                actualWithdrawn = actualWithdrawn + ethAmount;
                                emit Withdrawn(msg.sender, ethAmount, latestRoundID);
                            } else {
                                actualWithdrawn = actualWithdrawn + idleAmount;
                                ethAmount = ethAmount - idleAmount;
                                StrategyController controller = StrategyController(
                                    strategyController
                                );
                                uint256 actualAmount = controller.forceWithdraw(ethAmount);
                                actualWithdrawn = actualWithdrawn + actualAmount;
                                emit WithdrawnFromStrategy(
                                    msg.sender,
                                    ethAmount,
                                    actualAmount,
                                    latestRoundID
                                );
                            }
                        }
                        require(aVault.getBalance() >= actualWithdrawn, "still need wait");
                        uint256 withFee;
                        if (withdrawFeeRate != 0) {
                            withFee = (actualWithdrawn * withdrawFeeRate) / ONE_HUNDRED_PERCENT;
                            aVault.withdraw(feeRecipient, withFee);
                            emit FeeCharged(msg.sender, withFee);
                        }
                        aVault.withdraw(msg.sender, actualWithdrawn - withFee);
                    }
                    function rollToNextRound() external {
                        require(
                            block.timestamp > rebaseTime + rebaseTimeInterval,
                            "already rebased"
                        );
                        StrategyController controller = StrategyController(strategyController);
                        AssetsVault aVault = AssetsVault(assetsVault);
                        uint256 previewSharePrice = currentSharePrice();
                        uint256 vaultBalance = aVault.getBalance();
                        uint256 amountToWithdraw = VaultMath.sharesToAsset(
                            withdrawingSharesInRound,
                            previewSharePrice
                        );
                        uint256 amountVaultNeed = withdrawableAmountInPast + amountToWithdraw;
                        uint256 allPendingValue = controller.getAllStrategyPendingValue();
                        uint256 vaultIn;
                        uint256 vaultOut;
                        if (vaultBalance > amountVaultNeed) {
                            vaultIn = vaultBalance - amountVaultNeed;
                        } else if (vaultBalance + allPendingValue < amountVaultNeed) {
                            vaultOut = amountVaultNeed - vaultBalance - allPendingValue;
                        }
                        controller.rebaseStrategies(vaultIn, vaultOut);
                        uint256 newSharePrice = currentSharePrice();
                        roundPricePerShare[latestRoundID] = previewSharePrice < newSharePrice
                            ? previewSharePrice
                            : newSharePrice;
                        settlementTime[latestRoundID] = block.timestamp;
                        latestRoundID = latestRoundID + 1;
                        withdrawingSharesInPast =
                            withdrawingSharesInPast +
                            withdrawingSharesInRound;
                        withdrawableAmountInPast =
                            withdrawableAmountInPast +
                            VaultMath.sharesToAsset(withdrawingSharesInRound, newSharePrice);
                        withdrawingSharesInRound = 0;
                        rebaseTime = block.timestamp;
                        emit RollToNextRound(latestRoundID, vaultIn, vaultOut, newSharePrice);
                    }
                    function addStrategy(address _strategy) external onlyProposal {
                        StrategyController controller = StrategyController(strategyController);
                        controller.addStrategy(_strategy);
                        emit StragetyAdded(_strategy);
                    }
                    function destroyStrategy(address _strategy) external onlyOwner {
                        StrategyController controller = StrategyController(strategyController);
                        controller.destroyStrategy(_strategy);
                        emit StragetyDestroyed(_strategy);
                    }
                    function clearStrategy(address _strategy) external onlyOwner {
                        StrategyController controller = StrategyController(strategyController);
                        controller.clearStrategy(_strategy);
                        emit StragetyCleared(_strategy);
                    }
                    function updatePortfolioConfig(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) external onlyProposal {
                        StrategyController controller = StrategyController(strategyController);
                        controller.setStrategies(_strategies, _ratios);
                        emit PortfolioConfigUpdated(_strategies, _ratios);
                    }
                    function updateProposal(address _proposal) external onlyProposal {
                        proposal = _proposal;
                    }
                    function migrateVault(address _vault) external onlyProposal {
                        Minter(minter).setNewVault(_vault);
                        AssetsVault(assetsVault).setNewVault(_vault);
                        StrategyController(strategyController).setNewVault(_vault);
                    }
                    function currentSharePrice() public returns (uint256 price) {
                        Stone stoneToken = Stone(stone);
                        uint256 totalStone = stoneToken.totalSupply();
                        if (
                            latestRoundID == 0 ||
                            totalStone == 0 ||
                            totalStone == withdrawingSharesInPast
                        ) {
                            return MULTIPLIER;
                        }
                        uint256 etherAmount = AssetsVault(assetsVault).getBalance() +
                            StrategyController(strategyController).getAllStrategiesValue() -
                            withdrawableAmountInPast;
                        uint256 activeShare = totalStone - withdrawingSharesInPast;
                        return (etherAmount * MULTIPLIER) / activeShare;
                    }
                    function getVaultAvailableAmount()
                        public
                        returns (uint256 idleAmount, uint256 investedAmount)
                    {
                        AssetsVault vault = AssetsVault(assetsVault);
                        if (vault.getBalance() > withdrawableAmountInPast) {
                            idleAmount = vault.getBalance() - withdrawableAmountInPast;
                        }
                        investedAmount = StrategyController(strategyController)
                            .getAllStrategyValidValue();
                    }
                    function setWithdrawFeeRate(uint256 _withdrawFeeRate) external onlyOwner {
                        require(_withdrawFeeRate <= MAXMIUM_FEE_RATE, "exceed maximum");
                        emit SetWithdrawFeeRate(withdrawFeeRate, _withdrawFeeRate);
                        withdrawFeeRate = _withdrawFeeRate;
                    }
                    function setFeeRecipient(address _feeRecipient) external onlyOwner {
                        require(_feeRecipient != address(0), "zero address");
                        emit SetFeeRecipient(feeRecipient, _feeRecipient);
                        feeRecipient = _feeRecipient;
                    }
                    function setRebaseInterval(uint256 _interval) external onlyOwner {
                        require(_interval <= MINIMUM_REBASE_INTERVAL, "invalid");
                        rebaseTimeInterval = _interval;
                        emit SetRebaseInterval(rebaseTimeInterval);
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import "@layerzerolabs/solidity-examples/contracts/token/oft/extension/BasedOFT.sol";
                import {Minter} from "./Minter.sol";
                contract Stone is BasedOFT {
                    uint256 public constant DAY_INTERVAL = 24 * 60 * 60;
                    address public minter;
                    uint16 public constant PT_FEED = 1;
                    uint16 public constant PT_SET_ENABLE = 2;
                    uint16 public constant PT_SET_CAP = 3;
                    uint256 public cap;
                    bool public enable = true;
                    mapping(uint256 => uint256) public quota;
                    event FeedToChain(
                        uint16 indexed dstChainId,
                        address indexed from,
                        bytes toAddress,
                        uint price
                    );
                    event SetCapFor(uint16 indexed dstChainId, bytes toAddress, uint cap);
                    event SetEnableFor(uint16 indexed dstChainId, bytes toAddress, bool flag);
                    constructor(
                        address _minter,
                        address _layerZeroEndpoint,
                        uint256 _cap
                    ) BasedOFT("StakeStone Ether", "STONE", _layerZeroEndpoint) {
                        minter = _minter;
                        cap = _cap;
                    }
                    modifier onlyMinter() {
                        require(msg.sender == minter, "NM");
                        _;
                    }
                    function mint(address _to, uint256 _amount) external onlyMinter {
                        _mint(_to, _amount);
                    }
                    function burn(address _from, uint256 _amount) external onlyMinter {
                        _burn(_from, _amount);
                    }
                    function sendFrom(
                        address _from,
                        uint16 _dstChainId,
                        bytes calldata _toAddress,
                        uint _amount,
                        address payable _refundAddress,
                        address _zroPaymentAddress,
                        bytes calldata _adapterParams
                    ) public payable override(IOFTCore, OFTCore) {
                        require(enable, "invalid");
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        require(id != _dstChainId, "same chain");
                        uint256 day = block.timestamp / DAY_INTERVAL;
                        require(_amount + quota[day] <= cap, "Exceed cap");
                        quota[day] = quota[day] + _amount;
                        super.sendFrom(
                            _from,
                            _dstChainId,
                            _toAddress,
                            _amount,
                            _refundAddress,
                            _zroPaymentAddress,
                            _adapterParams
                        );
                    }
                    function updatePrice(
                        uint16 _dstChainId,
                        bytes memory _toAddress
                    ) external payable returns (uint256 price) {
                        require(enable, "invalid");
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        require(id != _dstChainId, "same chain");
                        price = tokenPrice();
                        bytes memory lzPayload = abi.encode(
                            PT_FEED,
                            _toAddress,
                            price,
                            block.timestamp
                        );
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit FeedToChain(_dstChainId, msg.sender, _toAddress, price);
                    }
                    function setEnableFor(
                        uint16 _dstChainId,
                        bool _flag,
                        bytes memory _toAddress
                    ) external payable onlyOwner {
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        if (_dstChainId == id) {
                            enable = _flag;
                            emit SetEnableFor(
                                _dstChainId,
                                abi.encodePacked(address(this)),
                                enable
                            );
                            return;
                        }
                        bytes memory lzPayload = abi.encode(PT_SET_ENABLE, _toAddress, _flag);
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit SetEnableFor(_dstChainId, _toAddress, _flag);
                    }
                    function setCapFor(
                        uint16 _dstChainId,
                        uint256 _cap,
                        bytes memory _toAddress
                    ) external payable onlyOwner {
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        if (_dstChainId == id) {
                            cap = _cap;
                            emit SetCapFor(_dstChainId, abi.encodePacked(address(this)), cap);
                            return;
                        }
                        bytes memory lzPayload = abi.encode(PT_SET_CAP, _toAddress, _cap);
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit SetCapFor(_dstChainId, _toAddress, _cap);
                    }
                    function tokenPrice() public returns (uint256 price) {
                        price = Minter(minter).getTokenPrice();
                    }
                    function getQuota() external view returns (uint256) {
                        uint256 amount = quota[block.timestamp / DAY_INTERVAL];
                        if (cap > amount && enable) {
                            return cap - amount;
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {Stone} from "./Stone.sol";
                import {StoneVault} from "../StoneVault.sol";
                contract Minter {
                    // TODO: governable upgrade
                    address public stone;
                    address payable public vault;
                    modifier onlyVault() {
                        require(msg.sender == vault, "not vault");
                        _;
                    }
                    constructor(address _stone, address payable _vault) {
                        stone = _stone;
                        vault = _vault;
                    }
                    function mint(address _to, uint256 _amount) external onlyVault {
                        Stone(stone).mint(_to, _amount);
                    }
                    function burn(address _from, uint256 _amount) external onlyVault {
                        Stone(stone).burn(_from, _amount);
                    }
                    function setNewVault(address _vault) external onlyVault {
                        vault = payable(_vault);
                    }
                    function getTokenPrice() public returns (uint256 price) {
                        price = StoneVault(vault).currentSharePrice();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                import {Strategy} from "./Strategy.sol";
                import {AssetsVault} from "../AssetsVault.sol";
                contract StrategyController {
                    using EnumerableSet for EnumerableSet.AddressSet;
                    uint256 internal constant ONE_HUNDRED_PERCENT = 1e6;
                    address public stoneVault;
                    address payable public immutable assetsVault;
                    EnumerableSet.AddressSet private strategies;
                    mapping(address => uint256) public ratios;
                    struct StrategyDiff {
                        address strategy;
                        bool isDeposit;
                        uint256 amount;
                    }
                    modifier onlyVault() {
                        require(stoneVault == msg.sender, "not vault");
                        _;
                    }
                    constructor(
                        address payable _assetsVault,
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) {
                        require(_assetsVault != address(0), "ZERO ADDRESS");
                        uint256 length = _strategies.length;
                        for (uint256 i; i < length; i++) {
                            require(_strategies[i] != address(0), "ZERO ADDRESS");
                        }
                        stoneVault = msg.sender;
                        assetsVault = _assetsVault;
                        _initStrategies(_strategies, _ratios);
                    }
                    function onlyRebaseStrategies() external {
                        _rebase(0, 0);
                    }
                    function forceWithdraw(
                        uint256 _amount
                    ) external onlyVault returns (uint256 actualAmount) {
                        uint256 balanceBeforeRepay = address(this).balance;
                        if (balanceBeforeRepay >= _amount) {
                            _repayToVault();
                            actualAmount = balanceBeforeRepay;
                        } else {
                            actualAmount =
                                _forceWithdraw(_amount - balanceBeforeRepay) +
                                balanceBeforeRepay;
                        }
                    }
                    function setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) external onlyVault {
                        _setStrategies(_strategies, _ratios);
                    }
                    function addStrategy(address _strategy) external onlyVault {
                        require(!strategies.contains(_strategy), "already exist");
                        strategies.add(_strategy);
                    }
                    function rebaseStrategies(
                        uint256 _in,
                        uint256 _out
                    ) external payable onlyVault {
                        _rebase(_in, _out);
                    }
                    function destroyStrategy(address _strategy) external onlyVault {
                        _destoryStrategy(_strategy);
                    }
                    function _rebase(uint256 _in, uint256 _out) internal {
                        require(_in == 0 || _out == 0, "only deposit or withdraw");
                        if (_in != 0) {
                            AssetsVault(assetsVault).withdraw(address(this), _in);
                        }
                        uint256 total = getAllStrategyValidValue();
                        if (total < _out) {
                            total = 0;
                        } else {
                            total = total + _in - _out;
                        }
                        uint256 length = strategies.length();
                        StrategyDiff[] memory diffs = new StrategyDiff[](length);
                        uint256 head;
                        uint256 tail = length - 1;
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            if (ratios[strategy] == 0) {
                                _clearStrategy(strategy, true);
                                continue;
                            }
                            uint256 newPosition = (total * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            uint256 position = getStrategyValidValue(strategy);
                            if (newPosition < position) {
                                diffs[head] = StrategyDiff(
                                    strategy,
                                    false,
                                    position - newPosition
                                );
                                head++;
                            } else if (newPosition > position) {
                                diffs[tail] = StrategyDiff(
                                    strategy,
                                    true,
                                    newPosition - position
                                );
                                if (tail != 0) {
                                    tail--;
                                }
                            }
                        }
                        length = diffs.length;
                        for (uint256 i; i < length; i++) {
                            StrategyDiff memory diff = diffs[i];
                            if (diff.amount == 0) {
                                continue;
                            }
                            if (diff.isDeposit) {
                                if (address(this).balance < diff.amount) {
                                    diff.amount = address(this).balance;
                                }
                                _depositToStrategy(diff.strategy, diff.amount);
                            } else {
                                _withdrawFromStrategy(diff.strategy, diff.amount);
                            }
                        }
                        _repayToVault();
                    }
                    function _repayToVault() internal {
                        if (address(this).balance != 0) {
                            TransferHelper.safeTransferETH(assetsVault, address(this).balance);
                        }
                    }
                    function _depositToStrategy(address _strategy, uint256 _amount) internal {
                        Strategy(_strategy).deposit{value: _amount}();
                    }
                    function _withdrawFromStrategy(
                        address _strategy,
                        uint256 _amount
                    ) internal {
                        Strategy(_strategy).withdraw(_amount);
                    }
                    function _forceWithdraw(
                        uint256 _amount
                    ) internal returns (uint256 actualAmount) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            uint256 withAmount = (_amount * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            if (withAmount != 0) {
                                actualAmount =
                                    Strategy(strategy).instantWithdraw(withAmount) +
                                    actualAmount;
                            }
                        }
                        _repayToVault();
                    }
                    function getStrategyValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getAllValue();
                    }
                    function getStrategyValidValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getInvestedValue();
                    }
                    function getStrategyPendingValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getPendingValue();
                    }
                    function getAllStrategiesValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyValidValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValidValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyPendingValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyPendingValue(strategies.at(i));
                        }
                    }
                    function getStrategies()
                        public
                        view
                        returns (address[] memory addrs, uint256[] memory portions)
                    {
                        uint256 length = strategies.length();
                        addrs = new address[](length);
                        portions = new uint256[](length);
                        for (uint256 i; i < length; i++) {
                            address addr = strategies.at(i);
                            addrs[i] = addr;
                            portions[i] = ratios[addr];
                        }
                    }
                    function _initStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        require(_strategies.length == _ratios.length, "invalid length");
                        uint256 totalRatio;
                        uint256 length = _strategies.length;
                        for (uint i; i < length; i++) {
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function _setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        uint256 length = _strategies.length;
                        require(length == _ratios.length, "invalid length");
                        uint256 oldLength = strategies.length();
                        for (uint i; i < oldLength; i++) {
                            ratios[strategies.at(i)] = 0;
                        }
                        uint256 totalRatio;
                        for (uint i; i < length; i++) {
                            require(
                                Strategy(_strategies[i]).controller() == address(this),
                                "controller mismatch"
                            );
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function clearStrategy(address _strategy) public onlyVault {
                        _clearStrategy(_strategy, false);
                    }
                    function _clearStrategy(address _strategy, bool _isRebase) internal {
                        Strategy(_strategy).clear();
                        if (!_isRebase) {
                            _repayToVault();
                        }
                    }
                    function _destoryStrategy(address _strategy) internal {
                        require(_couldDestroyStrategy(_strategy), "still active");
                        strategies.remove(_strategy);
                        _repayToVault();
                    }
                    function _couldDestroyStrategy(
                        address _strategy
                    ) internal returns (bool status) {
                        return
                            ratios[_strategy] == 0 && Strategy(_strategy).getAllValue() < 1e4;
                    }
                    function setNewVault(address _vault) external onlyVault {
                        stoneVault = _vault;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {StrategyController} from "../strategies/StrategyController.sol";
                abstract contract Strategy {
                    address payable public immutable controller;
                    address public governance;
                    string public name;
                    modifier onlyGovernance() {
                        require(governance == msg.sender, "not governace");
                        _;
                    }
                    event TransferGovernance(address oldOwner, address newOwner);
                    constructor(address payable _controller, string memory _name) {
                        require(_controller != address(0), "ZERO ADDRESS");
                        governance = msg.sender;
                        controller = _controller;
                        name = _name;
                    }
                    modifier onlyController() {
                        require(controller == msg.sender, "not controller");
                        _;
                    }
                    function deposit() public payable virtual onlyController {}
                    function withdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function instantWithdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function clear() public virtual onlyController returns (uint256 amount) {}
                    function execPendingRequest(
                        uint256 _amount
                    ) public virtual returns (uint256 amount) {}
                    function getAllValue() public virtual returns (uint256 value) {}
                    function getPendingValue() public virtual returns (uint256 value) {}
                    function getInvestedValue() public virtual returns (uint256 value) {}
                    function checkPendingStatus()
                        public
                        virtual
                        returns (uint256 pending, uint256 executable)
                    {}
                    function setGovernance(address governance_) external onlyGovernance {
                        emit TransferGovernance(governance, governance_);
                        governance = governance_;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                library VaultMath {
                    uint256 internal constant DECIMALS = 18;
                    function assetToShares(
                        uint256 _assetAmount,
                        uint256 _assetPerShare
                    ) internal pure returns (uint256) {
                        require(_assetPerShare > 1, "Vault Lib: invalid assetPerShare");
                        return (_assetAmount * (10 ** DECIMALS)) / _assetPerShare;
                    }
                    function sharesToAsset(
                        uint256 _shares,
                        uint256 _assetPerShare
                    ) internal pure returns (uint256) {
                        require(_assetPerShare > 1, "Vault Lib: invalid assetPerShare");
                        return (_shares * _assetPerShare) / (10 ** DECIMALS);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                contract AssetsVault {
                    address public stoneVault;
                    address public strategyController;
                    modifier onlyPermit() {
                        require(
                            stoneVault == msg.sender || strategyController == msg.sender,
                            "not permit"
                        );
                        _;
                    }
                    constructor(address _stoneVault, address _strategyController) {
                        require(
                            _stoneVault != address(0) && _strategyController != address(0),
                            "ZERO ADDRESS"
                        );
                        stoneVault = _stoneVault;
                        strategyController = _strategyController;
                    }
                    function deposit() external payable {
                        require(msg.value != 0, "too small");
                    }
                    function withdraw(address _to, uint256 _amount) external onlyPermit {
                        TransferHelper.safeTransferETH(_to, _amount);
                    }
                    function setNewVault(address _vault) external onlyPermit {
                        stoneVault = _vault;
                    }
                    function getBalance() external view returns (uint256 amount) {
                        amount = address(this).balance;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: GPL-2.0-or-later
                pragma solidity >=0.6.0;
                import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                library TransferHelper {
                    /// @notice Transfers tokens from the targeted address to the given destination
                    /// @notice Errors with 'STF' if transfer fails
                    /// @param token The contract address of the token to be transferred
                    /// @param from The originating address from which the tokens will be transferred
                    /// @param to The destination address of the transfer
                    /// @param value The amount to be transferred
                    function safeTransferFrom(
                        address token,
                        address from,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) =
                            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
                    }
                    /// @notice Transfers tokens from msg.sender to a recipient
                    /// @dev Errors with ST if transfer fails
                    /// @param token The contract address of the token which will be transferred
                    /// @param to The recipient of the transfer
                    /// @param value The value of the transfer
                    function safeTransfer(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
                    }
                    /// @notice Approves the stipulated contract to spend the given allowance in the given token
                    /// @dev Errors with 'SA' if transfer fails
                    /// @param token The contract address of the token to be approved
                    /// @param to The target of the approval
                    /// @param value The amount of the given token the target will be allowed to spend
                    function safeApprove(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
                    }
                    /// @notice Transfers ETH to the recipient address
                    /// @dev Fails with `STE`
                    /// @param to The destination of the transfer
                    /// @param value The value to be transferred
                    function safeTransferETH(address to, uint256 value) internal {
                        (bool success, ) = to.call{value: value}(new bytes(0));
                        require(success, 'STE');
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
                // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for managing
                 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                 * types.
                 *
                 * Sets have the following properties:
                 *
                 * - Elements are added, removed, and checked for existence in constant time
                 * (O(1)).
                 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                 *
                 * ```solidity
                 * contract Example {
                 *     // Add the library methods
                 *     using EnumerableSet for EnumerableSet.AddressSet;
                 *
                 *     // Declare a set state variable
                 *     EnumerableSet.AddressSet private mySet;
                 * }
                 * ```
                 *
                 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                 * and `uint256` (`UintSet`) are supported.
                 *
                 * [WARNING]
                 * ====
                 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
                 * unusable.
                 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
                 *
                 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
                 * array of EnumerableSet.
                 * ====
                 */
                library EnumerableSet {
                    // To implement this library for multiple types with as little code
                    // repetition as possible, we write it in terms of a generic Set type with
                    // bytes32 values.
                    // The Set implementation uses private functions, and user-facing
                    // implementations (such as AddressSet) are just wrappers around the
                    // underlying Set.
                    // This means that we can only create new EnumerableSets for types that fit
                    // in bytes32.
                    struct Set {
                        // Storage of set values
                        bytes32[] _values;
                        // Position of the value in the `values` array, plus 1 because index 0
                        // means a value is not in the set.
                        mapping(bytes32 => uint256) _indexes;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function _add(Set storage set, bytes32 value) private returns (bool) {
                        if (!_contains(set, value)) {
                            set._values.push(value);
                            // The value is stored at length-1, but we add 1 to all indexes
                            // and use 0 as a sentinel value
                            set._indexes[value] = set._values.length;
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function _remove(Set storage set, bytes32 value) private returns (bool) {
                        // We read and store the value's index to prevent multiple reads from the same storage slot
                        uint256 valueIndex = set._indexes[value];
                        if (valueIndex != 0) {
                            // Equivalent to contains(set, value)
                            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                            // the array, and then remove the last element (sometimes called as 'swap and pop').
                            // This modifies the order of the array, as noted in {at}.
                            uint256 toDeleteIndex = valueIndex - 1;
                            uint256 lastIndex = set._values.length - 1;
                            if (lastIndex != toDeleteIndex) {
                                bytes32 lastValue = set._values[lastIndex];
                                // Move the last value to the index where the value to delete is
                                set._values[toDeleteIndex] = lastValue;
                                // Update the index for the moved value
                                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                            }
                            // Delete the slot where the moved value was stored
                            set._values.pop();
                            // Delete the index for the deleted slot
                            delete set._indexes[value];
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function _contains(Set storage set, bytes32 value) private view returns (bool) {
                        return set._indexes[value] != 0;
                    }
                    /**
                     * @dev Returns the number of values on the set. O(1).
                     */
                    function _length(Set storage set) private view returns (uint256) {
                        return set._values.length;
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function _at(Set storage set, uint256 index) private view returns (bytes32) {
                        return set._values[index];
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function _values(Set storage set) private view returns (bytes32[] memory) {
                        return set._values;
                    }
                    // Bytes32Set
                    struct Bytes32Set {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _add(set._inner, value);
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _remove(set._inner, value);
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                        return _contains(set._inner, value);
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(Bytes32Set storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                        return _at(set._inner, index);
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        bytes32[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // AddressSet
                    struct AddressSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(AddressSet storage set, address value) internal returns (bool) {
                        return _add(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(AddressSet storage set, address value) internal returns (bool) {
                        return _remove(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(AddressSet storage set, address value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(AddressSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(AddressSet storage set, uint256 index) internal view returns (address) {
                        return address(uint160(uint256(_at(set._inner, index))));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(AddressSet storage set) internal view returns (address[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        address[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // UintSet
                    struct UintSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(UintSet storage set, uint256 value) internal returns (bool) {
                        return _add(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(UintSet storage set, uint256 value) internal returns (bool) {
                        return _remove(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(UintSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                        return uint256(_at(set._inner, index));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(UintSet storage set) internal view returns (uint256[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        uint256[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC165 standard, as defined in the
                 * https://eips.ethereum.org/EIPS/eip-165[EIP].
                 *
                 * Implementers can declare support of contract interfaces, which can then be
                 * queried by others ({ERC165Checker}).
                 *
                 * For an implementation, see {ERC165}.
                 */
                interface IERC165 {
                    /**
                     * @dev Returns true if this contract implements the interface defined by
                     * `interfaceId`. See the corresponding
                     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                     * to learn more about how these ids are created.
                     *
                     * This function call must use less than 30 000 gas.
                     */
                    function supportsInterface(bytes4 interfaceId) external view returns (bool);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
                pragma solidity ^0.8.0;
                import "./IERC165.sol";
                /**
                 * @dev Implementation of the {IERC165} interface.
                 *
                 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
                 * for the additional interface id that will be supported. For example:
                 *
                 * ```solidity
                 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
                 * }
                 * ```
                 *
                 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
                 */
                abstract contract ERC165 is IERC165 {
                    /**
                     * @dev See {IERC165-supportsInterface}.
                     */
                    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                        return interfaceId == type(IERC165).interfaceId;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Provides information about the current execution context, including the
                 * sender of the transaction and its data. While these are generally available
                 * via msg.sender and msg.data, they should not be accessed in such a direct
                 * manner, since when dealing with meta-transactions the account sending and
                 * paying for execution may not be the actual sender (as far as an application
                 * is concerned).
                 *
                 * This contract is only required for intermediate, library-like contracts.
                 */
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                pragma solidity ^0.8.0;
                import "../IERC20.sol";
                /**
                 * @dev Interface for the optional metadata functions from the ERC20 standard.
                 *
                 * _Available since v4.1._
                 */
                interface IERC20Metadata is IERC20 {
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() external view returns (string memory);
                    /**
                     * @dev Returns the symbol of the token.
                     */
                    function symbol() external view returns (string memory);
                    /**
                     * @dev Returns the decimals places of the token.
                     */
                    function decimals() external view returns (uint8);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                    /**
                     * @dev Returns the amount of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                    /**
                     * @dev Returns the amount of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * @dev Moves `amount` tokens from the caller's account to `to`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address to, uint256 amount) external returns (bool);
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 amount) external returns (bool);
                    /**
                     * @dev Moves `amount` tokens from `from` to `to` using the
                     * allowance mechanism. `amount` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address from, address to, uint256 amount) external returns (bool);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
                pragma solidity ^0.8.0;
                import "./IERC20.sol";
                import "./extensions/IERC20Metadata.sol";
                import "../../utils/Context.sol";
                /**
                 * @dev Implementation of the {IERC20} interface.
                 *
                 * This implementation is agnostic to the way tokens are created. This means
                 * that a supply mechanism has to be added in a derived contract using {_mint}.
                 * For a generic mechanism see {ERC20PresetMinterPauser}.
                 *
                 * TIP: For a detailed writeup see our guide
                 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                 * to implement supply mechanisms].
                 *
                 * The default value of {decimals} is 18. To change this, you should override
                 * this function so it returns a different value.
                 *
                 * We have followed general OpenZeppelin Contracts guidelines: functions revert
                 * instead returning `false` on failure. This behavior is nonetheless
                 * conventional and does not conflict with the expectations of ERC20
                 * applications.
                 *
                 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                 * This allows applications to reconstruct the allowance for all accounts just
                 * by listening to said events. Other implementations of the EIP may not emit
                 * these events, as it isn't required by the specification.
                 *
                 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                 * functions have been added to mitigate the well-known issues around setting
                 * allowances. See {IERC20-approve}.
                 */
                contract ERC20 is Context, IERC20, IERC20Metadata {
                    mapping(address => uint256) private _balances;
                    mapping(address => mapping(address => uint256)) private _allowances;
                    uint256 private _totalSupply;
                    string private _name;
                    string private _symbol;
                    /**
                     * @dev Sets the values for {name} and {symbol}.
                     *
                     * All two of these values are immutable: they can only be set once during
                     * construction.
                     */
                    constructor(string memory name_, string memory symbol_) {
                        _name = name_;
                        _symbol = symbol_;
                    }
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() public view virtual override returns (string memory) {
                        return _name;
                    }
                    /**
                     * @dev Returns the symbol of the token, usually a shorter version of the
                     * name.
                     */
                    function symbol() public view virtual override returns (string memory) {
                        return _symbol;
                    }
                    /**
                     * @dev Returns the number of decimals used to get its user representation.
                     * For example, if `decimals` equals `2`, a balance of `505` tokens should
                     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                     *
                     * Tokens usually opt for a value of 18, imitating the relationship between
                     * Ether and Wei. This is the default value returned by this function, unless
                     * it's overridden.
                     *
                     * NOTE: This information is only used for _display_ purposes: it in
                     * no way affects any of the arithmetic of the contract, including
                     * {IERC20-balanceOf} and {IERC20-transfer}.
                     */
                    function decimals() public view virtual override returns (uint8) {
                        return 18;
                    }
                    /**
                     * @dev See {IERC20-totalSupply}.
                     */
                    function totalSupply() public view virtual override returns (uint256) {
                        return _totalSupply;
                    }
                    /**
                     * @dev See {IERC20-balanceOf}.
                     */
                    function balanceOf(address account) public view virtual override returns (uint256) {
                        return _balances[account];
                    }
                    /**
                     * @dev See {IERC20-transfer}.
                     *
                     * Requirements:
                     *
                     * - `to` cannot be the zero address.
                     * - the caller must have a balance of at least `amount`.
                     */
                    function transfer(address to, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _transfer(owner, to, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-allowance}.
                     */
                    function allowance(address owner, address spender) public view virtual override returns (uint256) {
                        return _allowances[owner][spender];
                    }
                    /**
                     * @dev See {IERC20-approve}.
                     *
                     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                     * `transferFrom`. This is semantically equivalent to an infinite approval.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function approve(address spender, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-transferFrom}.
                     *
                     * Emits an {Approval} event indicating the updated allowance. This is not
                     * required by the EIP. See the note at the beginning of {ERC20}.
                     *
                     * NOTE: Does not update the allowance if the current allowance
                     * is the maximum `uint256`.
                     *
                     * Requirements:
                     *
                     * - `from` and `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     * - the caller must have allowance for ``from``'s tokens of at least
                     * `amount`.
                     */
                    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
                        address spender = _msgSender();
                        _spendAllowance(from, spender, amount);
                        _transfer(from, to, amount);
                        return true;
                    }
                    /**
                     * @dev Atomically increases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, allowance(owner, spender) + addedValue);
                        return true;
                    }
                    /**
                     * @dev Atomically decreases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `spender` must have allowance for the caller of at least
                     * `subtractedValue`.
                     */
                    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        uint256 currentAllowance = allowance(owner, spender);
                        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                        unchecked {
                            _approve(owner, spender, currentAllowance - subtractedValue);
                        }
                        return true;
                    }
                    /**
                     * @dev Moves `amount` of tokens from `from` to `to`.
                     *
                     * This internal function is equivalent to {transfer}, and can be used to
                     * e.g. implement automatic token fees, slashing mechanisms, etc.
                     *
                     * Emits a {Transfer} event.
                     *
                     * Requirements:
                     *
                     * - `from` cannot be the zero address.
                     * - `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     */
                    function _transfer(address from, address to, uint256 amount) internal virtual {
                        require(from != address(0), "ERC20: transfer from the zero address");
                        require(to != address(0), "ERC20: transfer to the zero address");
                        _beforeTokenTransfer(from, to, amount);
                        uint256 fromBalance = _balances[from];
                        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                        unchecked {
                            _balances[from] = fromBalance - amount;
                            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                            // decrementing then incrementing.
                            _balances[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        _afterTokenTransfer(from, to, amount);
                    }
                    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                     * the total supply.
                     *
                     * Emits a {Transfer} event with `from` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     */
                    function _mint(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: mint to the zero address");
                        _beforeTokenTransfer(address(0), account, amount);
                        _totalSupply += amount;
                        unchecked {
                            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                            _balances[account] += amount;
                        }
                        emit Transfer(address(0), account, amount);
                        _afterTokenTransfer(address(0), account, amount);
                    }
                    /**
                     * @dev Destroys `amount` tokens from `account`, reducing the
                     * total supply.
                     *
                     * Emits a {Transfer} event with `to` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     * - `account` must have at least `amount` tokens.
                     */
                    function _burn(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: burn from the zero address");
                        _beforeTokenTransfer(account, address(0), amount);
                        uint256 accountBalance = _balances[account];
                        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                        unchecked {
                            _balances[account] = accountBalance - amount;
                            // Overflow not possible: amount <= accountBalance <= totalSupply.
                            _totalSupply -= amount;
                        }
                        emit Transfer(account, address(0), amount);
                        _afterTokenTransfer(account, address(0), amount);
                    }
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                     *
                     * This internal function is equivalent to `approve`, and can be used to
                     * e.g. set automatic allowances for certain subsystems, etc.
                     *
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `owner` cannot be the zero address.
                     * - `spender` cannot be the zero address.
                     */
                    function _approve(address owner, address spender, uint256 amount) internal virtual {
                        require(owner != address(0), "ERC20: approve from the zero address");
                        require(spender != address(0), "ERC20: approve to the zero address");
                        _allowances[owner][spender] = amount;
                        emit Approval(owner, spender, amount);
                    }
                    /**
                     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                     *
                     * Does not update the allowance amount in case of infinite allowance.
                     * Revert if not enough allowance is available.
                     *
                     * Might emit an {Approval} event.
                     */
                    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                        uint256 currentAllowance = allowance(owner, spender);
                        if (currentAllowance != type(uint256).max) {
                            require(currentAllowance >= amount, "ERC20: insufficient allowance");
                            unchecked {
                                _approve(owner, spender, currentAllowance - amount);
                            }
                        }
                    }
                    /**
                     * @dev Hook that is called before any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * will be transferred to `to`.
                     * - when `from` is zero, `amount` tokens will be minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                    /**
                     * @dev Hook that is called after any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * has been transferred to `to`.
                     * - when `from` is zero, `amount` tokens have been minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    constructor() {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        _nonReentrantBefore();
                        _;
                        _nonReentrantAfter();
                    }
                    function _nonReentrantBefore() private {
                        // On the first call to nonReentrant, _status will be _NOT_ENTERED
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                    }
                    function _nonReentrantAfter() private {
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
                     * `nonReentrant` function in the call stack.
                     */
                    function _reentrancyGuardEntered() internal view returns (bool) {
                        return _status == _ENTERED;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
                pragma solidity ^0.8.0;
                import "../utils/Context.sol";
                /**
                 * @dev Contract module which provides a basic access control mechanism, where
                 * there is an account (an owner) that can be granted exclusive access to
                 * specific functions.
                 *
                 * By default, the owner account will be the one that deploys the contract. This
                 * can later be changed with {transferOwnership}.
                 *
                 * This module is used through inheritance. It will make available the modifier
                 * `onlyOwner`, which can be applied to your functions to restrict their use to
                 * the owner.
                 */
                abstract contract Ownable is Context {
                    address private _owner;
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    /**
                     * @dev Initializes the contract setting the deployer as the initial owner.
                     */
                    constructor() {
                        _transferOwnership(_msgSender());
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        _checkOwner();
                        _;
                    }
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if the sender is not the owner.
                     */
                    function _checkOwner() internal view virtual {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby disabling any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        _transferOwnership(address(0));
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Can only be called by the current owner.
                     */
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        require(newOwner != address(0), "Ownable: new owner is the zero address");
                        _transferOwnership(newOwner);
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Internal function without access restriction.
                     */
                    function _transferOwnership(address newOwner) internal virtual {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                // SPDX-License-Identifier: MIT OR Apache-2.0
                pragma solidity >=0.7.6;
                library ExcessivelySafeCall {
                    uint256 constant LOW_28_MASK =
                    0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                    /// @notice Use when you _really_ really _really_ don't trust the called
                    /// contract. This prevents the called contract from causing reversion of
                    /// the caller in as many ways as we can.
                    /// @dev The main difference between this and a solidity low-level call is
                    /// that we limit the number of bytes that the callee can cause to be
                    /// copied to caller memory. This prevents stupid things like malicious
                    /// contracts returning 10,000,000 bytes causing a local OOG when copying
                    /// to memory.
                    /// @param _target The address to call
                    /// @param _gas The amount of gas to forward to the remote contract
                    /// @param _maxCopy The maximum number of bytes of returndata to copy
                    /// to memory.
                    /// @param _calldata The data to send to the remote contract
                    /// @return success and returndata, as `.call()`. Returndata is capped to
                    /// `_maxCopy` bytes.
                    function excessivelySafeCall(
                        address _target,
                        uint256 _gas,
                        uint16 _maxCopy,
                        bytes memory _calldata
                    ) internal returns (bool, bytes memory) {
                        // set up for assembly call
                        uint256 _toCopy;
                        bool _success;
                        bytes memory _returnData = new bytes(_maxCopy);
                        // dispatch message to recipient
                        // by assembly calling "handle" function
                        // we call via assembly to avoid memcopying a very large returndata
                        // returned by a malicious contract
                        assembly {
                            _success := call(
                            _gas, // gas
                            _target, // recipient
                            0, // ether value
                            add(_calldata, 0x20), // inloc
                            mload(_calldata), // inlen
                            0, // outloc
                            0 // outlen
                            )
                        // limit our copy to 256 bytes
                            _toCopy := returndatasize()
                            if gt(_toCopy, _maxCopy) {
                                _toCopy := _maxCopy
                            }
                        // Store the length of the copied bytes
                            mstore(_returnData, _toCopy)
                        // copy the bytes from returndata[0:_toCopy]
                            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                        }
                        return (_success, _returnData);
                    }
                    /// @notice Use when you _really_ really _really_ don't trust the called
                    /// contract. This prevents the called contract from causing reversion of
                    /// the caller in as many ways as we can.
                    /// @dev The main difference between this and a solidity low-level call is
                    /// that we limit the number of bytes that the callee can cause to be
                    /// copied to caller memory. This prevents stupid things like malicious
                    /// contracts returning 10,000,000 bytes causing a local OOG when copying
                    /// to memory.
                    /// @param _target The address to call
                    /// @param _gas The amount of gas to forward to the remote contract
                    /// @param _maxCopy The maximum number of bytes of returndata to copy
                    /// to memory.
                    /// @param _calldata The data to send to the remote contract
                    /// @return success and returndata, as `.call()`. Returndata is capped to
                    /// `_maxCopy` bytes.
                    function excessivelySafeStaticCall(
                        address _target,
                        uint256 _gas,
                        uint16 _maxCopy,
                        bytes memory _calldata
                    ) internal view returns (bool, bytes memory) {
                        // set up for assembly call
                        uint256 _toCopy;
                        bool _success;
                        bytes memory _returnData = new bytes(_maxCopy);
                        // dispatch message to recipient
                        // by assembly calling "handle" function
                        // we call via assembly to avoid memcopying a very large returndata
                        // returned by a malicious contract
                        assembly {
                            _success := staticcall(
                            _gas, // gas
                            _target, // recipient
                            add(_calldata, 0x20), // inloc
                            mload(_calldata), // inlen
                            0, // outloc
                            0 // outlen
                            )
                        // limit our copy to 256 bytes
                            _toCopy := returndatasize()
                            if gt(_toCopy, _maxCopy) {
                                _toCopy := _maxCopy
                            }
                        // Store the length of the copied bytes
                            mstore(_returnData, _toCopy)
                        // copy the bytes from returndata[0:_toCopy]
                            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                        }
                        return (_success, _returnData);
                    }
                    /**
                     * @notice Swaps function selectors in encoded contract calls
                     * @dev Allows reuse of encoded calldata for functions with identical
                     * argument types but different names. It simply swaps out the first 4 bytes
                     * for the new selector. This function modifies memory in place, and should
                     * only be used with caution.
                     * @param _newSelector The new 4-byte selector
                     * @param _buf The encoded contract args
                     */
                    function swapSelector(bytes4 _newSelector, bytes memory _buf)
                    internal
                    pure
                    {
                        require(_buf.length >= 4);
                        uint256 _mask = LOW_28_MASK;
                        assembly {
                        // load the first word of
                            let _word := mload(add(_buf, 0x20))
                        // mask out the top 4 bytes
                        // /x
                            _word := and(_word, _mask)
                            _word := or(_newSelector, _word)
                            mstore(add(_buf, 0x20), _word)
                        }
                    }
                }
                // SPDX-License-Identifier: Unlicense
                /*
                 * @title Solidity Bytes Arrays Utils
                 * @author Gonçalo Sá <[email protected]>
                 *
                 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
                 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
                 */
                pragma solidity >=0.8.0 <0.9.0;
                library BytesLib {
                    function concat(
                        bytes memory _preBytes,
                        bytes memory _postBytes
                    )
                    internal
                    pure
                    returns (bytes memory)
                    {
                        bytes memory tempBytes;
                        assembly {
                        // Get a location of some free memory and store it in tempBytes as
                        // Solidity does for memory variables.
                            tempBytes := mload(0x40)
                        // Store the length of the first bytes array at the beginning of
                        // the memory for tempBytes.
                            let length := mload(_preBytes)
                            mstore(tempBytes, length)
                        // Maintain a memory counter for the current write location in the
                        // temp bytes array by adding the 32 bytes for the array length to
                        // the starting location.
                            let mc := add(tempBytes, 0x20)
                        // Stop copying when the memory counter reaches the length of the
                        // first bytes array.
                            let end := add(mc, length)
                            for {
                            // Initialize a copy counter to the start of the _preBytes data,
                            // 32 bytes into its memory.
                                let cc := add(_preBytes, 0x20)
                            } lt(mc, end) {
                            // Increase both counters by 32 bytes each iteration.
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                            // Write the _preBytes data into the tempBytes memory 32 bytes
                            // at a time.
                                mstore(mc, mload(cc))
                            }
                        // Add the length of _postBytes to the current length of tempBytes
                        // and store it as the new length in the first 32 bytes of the
                        // tempBytes memory.
                            length := mload(_postBytes)
                            mstore(tempBytes, add(length, mload(tempBytes)))
                        // Move the memory counter back from a multiple of 0x20 to the
                        // actual end of the _preBytes data.
                            mc := end
                        // Stop copying when the memory counter reaches the new combined
                        // length of the arrays.
                            end := add(mc, length)
                            for {
                                let cc := add(_postBytes, 0x20)
                            } lt(mc, end) {
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                mstore(mc, mload(cc))
                            }
                        // Update the free-memory pointer by padding our last write location
                        // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                        // next 32 byte block, then round down to the nearest multiple of
                        // 32. If the sum of the length of the two arrays is zero then add
                        // one before rounding down to leave a blank 32 bytes (the length block with 0).
                            mstore(0x40, and(
                            add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                            not(31) // Round down to the nearest 32 bytes.
                            ))
                        }
                        return tempBytes;
                    }
                    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                        assembly {
                        // Read the first 32 bytes of _preBytes storage, which is the length
                        // of the array. (We don't need to use the offset into the slot
                        // because arrays use the entire slot.)
                            let fslot := sload(_preBytes.slot)
                        // Arrays of 31 bytes or less have an even value in their slot,
                        // while longer arrays have an odd value. The actual length is
                        // the slot divided by two for odd values, and the lowest order
                        // byte divided by two for even values.
                        // If the slot is even, bitwise and the slot with 255 and divide by
                        // two to get the length. If the slot is odd, bitwise and the slot
                        // with -1 and divide by two.
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            let newlength := add(slength, mlength)
                        // slength can contain both the length and contents of the array
                        // if length < 32 bytes so let's prepare for that
                        // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                            switch add(lt(slength, 32), lt(newlength, 32))
                            case 2 {
                            // Since the new array still fits in the slot, we just need to
                            // update the contents of the slot.
                            // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                                sstore(
                                _preBytes.slot,
                                // all the modifications to the slot are inside this
                                // next block
                                add(
                                // we can just add to the slot contents because the
                                // bytes we want to change are the LSBs
                                fslot,
                                add(
                                mul(
                                div(
                                // load the bytes from memory
                                mload(add(_postBytes, 0x20)),
                                // zero all bytes to the right
                                exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                                ),
                                // increase length by the double of the memory
                                // bytes length
                                mul(mlength, 2)
                                )
                                )
                                )
                            }
                            case 1 {
                            // The stored value fits in the slot, but the combined value
                            // will exceed it.
                            // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                            // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                            // The contents of the _postBytes array start 32 bytes into
                            // the structure. Our first read should obtain the `submod`
                            // bytes that can fit into the unused space in the last word
                            // of the stored array. To get this, we read 32 bytes starting
                            // from `submod`, so the data we read overlaps with the array
                            // contents by `submod` bytes. Masking the lowest-order
                            // `submod` bytes allows us to add that value directly to the
                            // stored value.
                                let submod := sub(32, slength)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(
                                sc,
                                add(
                                and(
                                fslot,
                                0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                                ),
                                and(mload(mc), mask)
                                )
                                )
                                for {
                                    mc := add(mc, 0x20)
                                    sc := add(sc, 1)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                            default {
                            // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                            // Start copying to the last used word of the stored array.
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                            // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                            // Copy over the first `submod` bytes of the new data as in
                            // case 1 above.
                                let slengthmod := mod(slength, 32)
                                let mlengthmod := mod(mlength, 32)
                                let submod := sub(32, slengthmod)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(sc, add(sload(sc), and(mload(mc), mask)))
                                for {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                        }
                    }
                    function slice(
                        bytes memory _bytes,
                        uint256 _start,
                        uint256 _length
                    )
                    internal
                    pure
                    returns (bytes memory)
                    {
                        require(_length + 31 >= _length, "slice_overflow");
                        require(_bytes.length >= _start + _length, "slice_outOfBounds");
                        bytes memory tempBytes;
                        assembly {
                            switch iszero(_length)
                            case 0 {
                            // Get a location of some free memory and store it in tempBytes as
                            // Solidity does for memory variables.
                                tempBytes := mload(0x40)
                            // The first word of the slice result is potentially a partial
                            // word read from the original array. To read it, we calculate
                            // the length of that partial word and start copying that many
                            // bytes into the array. The first word we copy will start with
                            // data we don't care about, but the last `lengthmod` bytes will
                            // land at the beginning of the contents of the new array. When
                            // we're done copying, we overwrite the full first word with
                            // the actual length of the slice.
                                let lengthmod := and(_length, 31)
                            // The multiplication in the next line is necessary
                            // because when slicing multiples of 32 bytes (lengthmod == 0)
                            // the following copy loop was copying the origin's length
                            // and then ending prematurely not copying everything it should.
                                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                                let end := add(mc, _length)
                                for {
                                // The multiplication in the next line has the same exact purpose
                                // as the one above.
                                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                                } lt(mc, end) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                    mstore(mc, mload(cc))
                                }
                                mstore(tempBytes, _length)
                            //update free-memory pointer
                            //allocating the array padded to 32 bytes like the compiler does now
                                mstore(0x40, and(add(mc, 31), not(31)))
                            }
                            //if we want a zero-length slice let's just return a zero-length array
                            default {
                                tempBytes := mload(0x40)
                            //zero out the 32 bytes slice we are about to return
                            //we need to do it because Solidity does not garbage collect
                                mstore(tempBytes, 0)
                                mstore(0x40, add(tempBytes, 0x20))
                            }
                        }
                        return tempBytes;
                    }
                    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
                        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
                        address tempAddress;
                        assembly {
                            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                        }
                        return tempAddress;
                    }
                    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
                        uint8 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x1), _start))
                        }
                        return tempUint;
                    }
                    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
                        uint16 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x2), _start))
                        }
                        return tempUint;
                    }
                    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
                        uint32 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x4), _start))
                        }
                        return tempUint;
                    }
                    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
                        uint64 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x8), _start))
                        }
                        return tempUint;
                    }
                    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
                        uint96 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0xc), _start))
                        }
                        return tempUint;
                    }
                    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
                        uint128 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x10), _start))
                        }
                        return tempUint;
                    }
                    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
                        uint256 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempUint;
                    }
                    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
                        bytes32 tempBytes32;
                        assembly {
                            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempBytes32;
                    }
                    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                        bool success = true;
                        assembly {
                            let length := mload(_preBytes)
                        // if lengths don't match the arrays are not equal
                            switch eq(length, mload(_postBytes))
                            case 1 {
                            // cb is a circuit breaker in the for loop since there's
                            //  no said feature for inline assembly loops
                            // cb = 1 - don't breaker
                            // cb = 0 - break
                                let cb := 1
                                let mc := add(_preBytes, 0x20)
                                let end := add(mc, length)
                                for {
                                    let cc := add(_postBytes, 0x20)
                                // the next line is the loop condition:
                                // while(uint256(mc < end) + cb == 2)
                                } eq(add(lt(mc, end), cb), 2) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                // if any of these checks fails then arrays are not equal
                                    if iszero(eq(mload(mc), mload(cc))) {
                                    // unsuccess:
                                        success := 0
                                        cb := 0
                                    }
                                }
                            }
                            default {
                            // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                    function equalStorage(
                        bytes storage _preBytes,
                        bytes memory _postBytes
                    )
                    internal
                    view
                    returns (bool)
                    {
                        bool success = true;
                        assembly {
                        // we know _preBytes_offset is 0
                            let fslot := sload(_preBytes.slot)
                        // Decode the length of the stored array like in concatStorage().
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                        // if lengths don't match the arrays are not equal
                            switch eq(slength, mlength)
                            case 1 {
                            // slength can contain both the length and contents of the array
                            // if length < 32 bytes so let's prepare for that
                            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                if iszero(iszero(slength)) {
                                    switch lt(slength, 32)
                                    case 1 {
                                    // blank the last byte which is the length
                                        fslot := mul(div(fslot, 0x100), 0x100)
                                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                        // unsuccess:
                                            success := 0
                                        }
                                    }
                                    default {
                                    // cb is a circuit breaker in the for loop since there's
                                    //  no said feature for inline assembly loops
                                    // cb = 1 - don't breaker
                                    // cb = 0 - break
                                        let cb := 1
                                    // get the keccak hash to get the contents of the array
                                        mstore(0x0, _preBytes.slot)
                                        let sc := keccak256(0x0, 0x20)
                                        let mc := add(_postBytes, 0x20)
                                        let end := add(mc, mlength)
                                    // the next line is the loop condition:
                                    // while(uint256(mc < end) + cb == 2)
                                        for {} eq(add(lt(mc, end), cb), 2) {
                                            sc := add(sc, 1)
                                            mc := add(mc, 0x20)
                                        } {
                                            if iszero(eq(sload(sc), mload(mc))) {
                                            // unsuccess:
                                                success := 0
                                                cb := 0
                                            }
                                        }
                                    }
                                }
                            }
                            default {
                            // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../OFT.sol";
                contract BasedOFT is OFT {
                    constructor(string memory _name, string memory _symbol, address _lzEndpoint) OFT(_name, _symbol, _lzEndpoint) {}
                    function circulatingSupply() public view virtual override returns (uint) {
                        unchecked {
                            return totalSupply() - balanceOf(address(this));
                        }
                    }
                    function _debitFrom(address _from, uint16, bytes memory, uint _amount) internal virtual override returns(uint) {
                        address spender = _msgSender();
                        if (_from != spender) _spendAllowance(_from, spender, _amount);
                        _transfer(_from, address(this), _amount);
                        return _amount;
                    }
                    function _creditTo(uint16, address _toAddress, uint _amount) internal virtual override returns(uint) {
                        _transfer(address(this), _toAddress, _amount);
                        return _amount;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../../lzApp/NonblockingLzApp.sol";
                import "./IOFTCore.sol";
                import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
                abstract contract OFTCore is NonblockingLzApp, ERC165, IOFTCore {
                    using BytesLib for bytes;
                    uint public constant NO_EXTRA_GAS = 0;
                    // packet type
                    uint16 public constant PT_SEND = 0;
                    bool public useCustomAdapterParams;
                    constructor(address _lzEndpoint) NonblockingLzApp(_lzEndpoint) {}
                    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
                        return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId);
                    }
                    function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) public view virtual override returns (uint nativeFee, uint zroFee) {
                        // mock the payload for sendFrom()
                        bytes memory payload = abi.encode(PT_SEND, _toAddress, _amount);
                        return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams);
                    }
                    function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {
                        _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);
                    }
                    function setUseCustomAdapterParams(bool _useCustomAdapterParams) public virtual onlyOwner {
                        useCustomAdapterParams = _useCustomAdapterParams;
                        emit SetUseCustomAdapterParams(_useCustomAdapterParams);
                    }
                    function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                        uint16 packetType;
                        assembly {
                            packetType := mload(add(_payload, 32))
                        }
                        if (packetType == PT_SEND) {
                            _sendAck(_srcChainId, _srcAddress, _nonce, _payload);
                        } else {
                            revert("OFTCore: unknown packet type");
                        }
                    }
                    function _send(address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams) internal virtual {
                        _checkAdapterParams(_dstChainId, PT_SEND, _adapterParams, NO_EXTRA_GAS);
                        uint amount = _debitFrom(_from, _dstChainId, _toAddress, _amount);
                        bytes memory lzPayload = abi.encode(PT_SEND, _toAddress, amount);
                        _lzSend(_dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value);
                        emit SendToChain(_dstChainId, _from, _toAddress, amount);
                    }
                    function _sendAck(uint16 _srcChainId, bytes memory, uint64, bytes memory _payload) internal virtual {
                        (, bytes memory toAddressBytes, uint amount) = abi.decode(_payload, (uint16, bytes, uint));
                        address to = toAddressBytes.toAddress(0);
                        amount = _creditTo(_srcChainId, to, amount);
                        emit ReceiveFromChain(_srcChainId, to, amount);
                    }
                    function _checkAdapterParams(uint16 _dstChainId, uint16 _pkType, bytes memory _adapterParams, uint _extraGas) internal virtual {
                        if (useCustomAdapterParams) {
                            _checkGasLimit(_dstChainId, _pkType, _adapterParams, _extraGas);
                        } else {
                            require(_adapterParams.length == 0, "OFTCore: _adapterParams must be empty.");
                        }
                    }
                    function _debitFrom(address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount) internal virtual returns(uint);
                    function _creditTo(uint16 _srcChainId, address _toAddress, uint _amount) internal virtual returns(uint);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
                import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
                import "./IOFT.sol";
                import "./OFTCore.sol";
                // override decimal() function is needed
                contract OFT is OFTCore, ERC20, IOFT {
                    constructor(string memory _name, string memory _symbol, address _lzEndpoint) ERC20(_name, _symbol) OFTCore(_lzEndpoint) {}
                    function supportsInterface(bytes4 interfaceId) public view virtual override(OFTCore, IERC165) returns (bool) {
                        return interfaceId == type(IOFT).interfaceId || interfaceId == type(IERC20).interfaceId || super.supportsInterface(interfaceId);
                    }
                    function token() public view virtual override returns (address) {
                        return address(this);
                    }
                    function circulatingSupply() public view virtual override returns (uint) {
                        return totalSupply();
                    }
                    function _debitFrom(address _from, uint16, bytes memory, uint _amount) internal virtual override returns(uint) {
                        address spender = _msgSender();
                        if (_from != spender) _spendAllowance(_from, spender, _amount);
                        _burn(_from, _amount);
                        return _amount;
                    }
                    function _creditTo(uint16, address _toAddress, uint _amount) internal virtual override returns(uint) {
                        _mint(_toAddress, _amount);
                        return _amount;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
                /**
                 * @dev Interface of the IOFT core standard
                 */
                interface IOFTCore is IERC165 {
                    /**
                     * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
                     * _dstChainId - L0 defined chain id to send tokens too
                     * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
                     * _amount - amount of the tokens to transfer
                     * _useZro - indicates to use zro to pay L0 fees
                     * _adapterParam - flexible bytes array to indicate messaging adapter services in L0
                     */
                    function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
                    /**
                     * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
                     * `_from` the owner of token
                     * `_dstChainId` the destination chain identifier
                     * `_toAddress` can be any size depending on the `dstChainId`.
                     * `_amount` the quantity of tokens in wei
                     * `_refundAddress` the address LayerZero refunds if too much message fee is sent
                     * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
                     * `_adapterParams` is a flexible bytes array to indicate messaging adapter services
                     */
                    function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                    /**
                     * @dev returns the circulating amount of tokens on current chain
                     */
                    function circulatingSupply() external view returns (uint);
                    /**
                     * @dev returns the address of the ERC20 token
                     */
                    function token() external view returns (address);
                    /**
                     * @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`)
                     * `_nonce` is the outbound nonce
                     */
                    event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint _amount);
                    /**
                     * @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain.
                     * `_nonce` is the inbound nonce.
                     */
                    event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint _amount);
                    event SetUseCustomAdapterParams(bool _useCustomAdapterParams);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "./IOFTCore.sol";
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                /**
                 * @dev Interface of the OFT standard
                 */
                interface IOFT is IOFTCore, IERC20 {
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./LzApp.sol";
                import "../util/ExcessivelySafeCall.sol";
                /*
                 * the default LayerZero messaging behaviour is blocking, i.e. any failed message will block the channel
                 * this abstract class try-catch all fail messages and store locally for future retry. hence, non-blocking
                 * NOTE: if the srcAddress is not configured properly, it will still block the message pathway from (srcChainId, srcAddress)
                 */
                abstract contract NonblockingLzApp is LzApp {
                    using ExcessivelySafeCall for address;
                    constructor(address _endpoint) LzApp(_endpoint) {}
                    mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages;
                    event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);
                    event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);
                    // overriding the virtual function in LzReceiver
                    function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                        (bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft(), 150, abi.encodeWithSelector(this.nonblockingLzReceive.selector, _srcChainId, _srcAddress, _nonce, _payload));
                        // try-catch all errors/exceptions
                        if (!success) {
                            _storeFailedMessage(_srcChainId, _srcAddress, _nonce, _payload, reason);
                        }
                    }
                    function _storeFailedMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload, bytes memory _reason) internal virtual {
                        failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
                        emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload, _reason);
                    }
                    function nonblockingLzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual {
                        // only internal transaction
                        require(_msgSender() == address(this), "NonblockingLzApp: caller must be LzApp");
                        _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                    }
                    //@notice override this function
                    function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
                    function retryMessage(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public payable virtual {
                        // assert there is message to retry
                        bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce];
                        require(payloadHash != bytes32(0), "NonblockingLzApp: no stored message");
                        require(keccak256(_payload) == payloadHash, "NonblockingLzApp: invalid payload");
                        // clear the stored message
                        failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0);
                        // execute the message. revert if it fails again
                        _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                        emit RetryMessageSuccess(_srcChainId, _srcAddress, _nonce, payloadHash);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "../interfaces/ILayerZeroReceiver.sol";
                import "../interfaces/ILayerZeroUserApplicationConfig.sol";
                import "../interfaces/ILayerZeroEndpoint.sol";
                import "../util/BytesLib.sol";
                /*
                 * a generic LzReceiver implementation
                 */
                abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                    using BytesLib for bytes;
                    // ua can not send payload larger than this by default, but it can be changed by the ua owner
                    uint constant public DEFAULT_PAYLOAD_SIZE_LIMIT = 10000;
                    ILayerZeroEndpoint public immutable lzEndpoint;
                    mapping(uint16 => bytes) public trustedRemoteLookup;
                    mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
                    mapping(uint16 => uint) public payloadSizeLimitLookup;
                    address public precrime;
                    event SetPrecrime(address precrime);
                    event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
                    event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
                    event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
                    constructor(address _endpoint) {
                        lzEndpoint = ILayerZeroEndpoint(_endpoint);
                    }
                    function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual override {
                        // lzReceive must be called by the endpoint for security
                        require(_msgSender() == address(lzEndpoint), "LzApp: invalid endpoint caller");
                        bytes memory trustedRemote = trustedRemoteLookup[_srcChainId];
                        // if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.
                        require(_srcAddress.length == trustedRemote.length && trustedRemote.length > 0 && keccak256(_srcAddress) == keccak256(trustedRemote), "LzApp: invalid source sending contract");
                        _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                    }
                    // abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging
                    function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
                    function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint _nativeFee) internal virtual {
                        bytes memory trustedRemote = trustedRemoteLookup[_dstChainId];
                        require(trustedRemote.length != 0, "LzApp: destination chain is not a trusted source");
                        _checkPayloadSize(_dstChainId, _payload.length);
                        lzEndpoint.send{value: _nativeFee}(_dstChainId, trustedRemote, _payload, _refundAddress, _zroPaymentAddress, _adapterParams);
                    }
                    function _checkGasLimit(uint16 _dstChainId, uint16 _type, bytes memory _adapterParams, uint _extraGas) internal view virtual {
                        uint providedGasLimit = _getGasLimit(_adapterParams);
                        uint minGasLimit = minDstGasLookup[_dstChainId][_type] + _extraGas;
                        require(minGasLimit > 0, "LzApp: minGasLimit not set");
                        require(providedGasLimit >= minGasLimit, "LzApp: gas limit is too low");
                    }
                    function _getGasLimit(bytes memory _adapterParams) internal pure virtual returns (uint gasLimit) {
                        require(_adapterParams.length >= 34, "LzApp: invalid adapterParams");
                        assembly {
                            gasLimit := mload(add(_adapterParams, 34))
                        }
                    }
                    function _checkPayloadSize(uint16 _dstChainId, uint _payloadSize) internal view virtual {
                        uint payloadSizeLimit = payloadSizeLimitLookup[_dstChainId];
                        if (payloadSizeLimit == 0) { // use default if not set
                            payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT;
                        }
                        require(_payloadSize <= payloadSizeLimit, "LzApp: payload size is too large");
                    }
                    //---------------------------UserApplication config----------------------------------------
                    function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
                        return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
                    }
                    // generic config for LayerZero user Application
                    function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override onlyOwner {
                        lzEndpoint.setConfig(_version, _chainId, _configType, _config);
                    }
                    function setSendVersion(uint16 _version) external override onlyOwner {
                        lzEndpoint.setSendVersion(_version);
                    }
                    function setReceiveVersion(uint16 _version) external override onlyOwner {
                        lzEndpoint.setReceiveVersion(_version);
                    }
                    function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                        lzEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
                    }
                    // _path = abi.encodePacked(remoteAddress, localAddress)
                    // this function set the trusted path for the cross-chain communication
                    function setTrustedRemote(uint16 _remoteChainId, bytes calldata _path) external onlyOwner {
                        trustedRemoteLookup[_remoteChainId] = _path;
                        emit SetTrustedRemote(_remoteChainId, _path);
                    }
                    function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external onlyOwner {
                        trustedRemoteLookup[_remoteChainId] = abi.encodePacked(_remoteAddress, address(this));
                        emit SetTrustedRemoteAddress(_remoteChainId, _remoteAddress);
                    }
                    function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory) {
                        bytes memory path = trustedRemoteLookup[_remoteChainId];
                        require(path.length != 0, "LzApp: no trusted path record");
                        return path.slice(0, path.length - 20); // the last 20 bytes should be address(this)
                    }
                    function setPrecrime(address _precrime) external onlyOwner {
                        precrime = _precrime;
                        emit SetPrecrime(_precrime);
                    }
                    function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint _minGas) external onlyOwner {
                        require(_minGas > 0, "LzApp: invalid minGas");
                        minDstGasLookup[_dstChainId][_packetType] = _minGas;
                        emit SetMinDstGas(_dstChainId, _packetType, _minGas);
                    }
                    // if the size is 0, it means default size limit
                    function setPayloadSizeLimit(uint16 _dstChainId, uint _size) external onlyOwner {
                        payloadSizeLimitLookup[_dstChainId] = _size;
                    }
                    //--------------------------- VIEW FUNCTION ----------------------------------------
                    function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool) {
                        bytes memory trustedSource = trustedRemoteLookup[_srcChainId];
                        return keccak256(trustedSource) == keccak256(_srcAddress);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                interface ILayerZeroUserApplicationConfig {
                    // @notice set the configuration of the LayerZero messaging library of the specified version
                    // @param _version - messaging library version
                    // @param _chainId - the chainId for the pending config change
                    // @param _configType - type of configuration. every messaging library has its own convention.
                    // @param _config - configuration in the bytes. can encode arbitrary content.
                    function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                    // @notice set the send() LayerZero messaging library version to _version
                    // @param _version - new messaging library version
                    function setSendVersion(uint16 _version) external;
                    // @notice set the lzReceive() LayerZero messaging library version to _version
                    // @param _version - new messaging library version
                    function setReceiveVersion(uint16 _version) external;
                    // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                    // @param _srcChainId - the chainId of the source chain
                    // @param _srcAddress - the contract address of the source contract at the source chain
                    function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                interface ILayerZeroReceiver {
                    // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                    // @param _srcChainId - the source endpoint identifier
                    // @param _srcAddress - the source sending contract address from the source chain
                    // @param _nonce - the ordered message nonce
                    // @param _payload - the signed payload is the UA bytes has encoded to be sent
                    function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "./ILayerZeroUserApplicationConfig.sol";
                interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                    // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                    // @param _dstChainId - the destination chain identifier
                    // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                    // @param _payload - a custom bytes payload to send to the destination contract
                    // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                    // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                    // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
                    function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                    // @notice used by the messaging library to publish verified payload
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source contract (as bytes) at the source chain
                    // @param _dstAddress - the address on destination chain
                    // @param _nonce - the unbound message ordering nonce
                    // @param _gasLimit - the gas limit for external contract execution
                    // @param _payload - verified payload to send to the destination contract
                    function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                    // @notice get the inboundNonce of a lzApp from a source chain which could be EVM or non-EVM chain
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                    // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                    // @param _srcAddress - the source chain contract address
                    function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                    // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                    // @param _dstChainId - the destination chain identifier
                    // @param _userApplication - the user app address on this EVM chain
                    // @param _payload - the custom message to send over LayerZero
                    // @param _payInZRO - if false, user app pays the protocol fee in native token
                    // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                    function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                    // @notice get this Endpoint's immutable source identifier
                    function getChainId() external view returns (uint16);
                    // @notice the interface to retry failed message on this Endpoint destination
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    // @param _payload - the payload to be retried
                    function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                    // @notice query if any STORED payload (message blocking) at the endpoint.
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                    // @notice query if the _libraryAddress is valid for sending msgs.
                    // @param _userApplication - the user app address on this EVM chain
                    function getSendLibraryAddress(address _userApplication) external view returns (address);
                    // @notice query if the _libraryAddress is valid for receiving msgs.
                    // @param _userApplication - the user app address on this EVM chain
                    function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                    // @notice query if the non-reentrancy guard for send() is on
                    // @return true if the guard is on. false otherwise
                    function isSendingPayload() external view returns (bool);
                    // @notice query if the non-reentrancy guard for receive() is on
                    // @return true if the guard is on. false otherwise
                    function isReceivingPayload() external view returns (bool);
                    // @notice get the configuration of the LayerZero messaging library of the specified version
                    // @param _version - messaging library version
                    // @param _chainId - the chainId for the pending config change
                    // @param _userApplication - the contract address of the user application
                    // @param _configType - type of configuration. every messaging library has its own convention.
                    function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                    // @notice get the send() LayerZero messaging library version
                    // @param _userApplication - the contract address of the user application
                    function getSendVersion(address _userApplication) external view returns (uint16);
                    // @notice get the lzReceive() LayerZero messaging library version
                    // @param _userApplication - the contract address of the user application
                    function getReceiveVersion(address _userApplication) external view returns (uint16);
                }
                

                File 2 of 9: Stone
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import "@layerzerolabs/solidity-examples/contracts/token/oft/extension/BasedOFT.sol";
                import {Minter} from "./Minter.sol";
                contract Stone is BasedOFT {
                    uint256 public constant DAY_INTERVAL = 24 * 60 * 60;
                    address public minter;
                    uint16 public constant PT_FEED = 1;
                    uint16 public constant PT_SET_ENABLE = 2;
                    uint16 public constant PT_SET_CAP = 3;
                    uint256 public cap;
                    bool public enable = true;
                    mapping(uint256 => uint256) public quota;
                    event FeedToChain(
                        uint16 indexed dstChainId,
                        address indexed from,
                        bytes toAddress,
                        uint price
                    );
                    event SetCapFor(uint16 indexed dstChainId, bytes toAddress, uint cap);
                    event SetEnableFor(uint16 indexed dstChainId, bytes toAddress, bool flag);
                    constructor(
                        address _minter,
                        address _layerZeroEndpoint,
                        uint256 _cap
                    ) BasedOFT("StakeStone Ether", "STONE", _layerZeroEndpoint) {
                        minter = _minter;
                        cap = _cap;
                    }
                    modifier onlyMinter() {
                        require(msg.sender == minter, "NM");
                        _;
                    }
                    function mint(address _to, uint256 _amount) external onlyMinter {
                        _mint(_to, _amount);
                    }
                    function burn(address _from, uint256 _amount) external onlyMinter {
                        _burn(_from, _amount);
                    }
                    function sendFrom(
                        address _from,
                        uint16 _dstChainId,
                        bytes calldata _toAddress,
                        uint _amount,
                        address payable _refundAddress,
                        address _zroPaymentAddress,
                        bytes calldata _adapterParams
                    ) public payable override(IOFTCore, OFTCore) {
                        require(enable, "invalid");
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        require(id != _dstChainId, "same chain");
                        uint256 day = block.timestamp / DAY_INTERVAL;
                        require(_amount + quota[day] <= cap, "Exceed cap");
                        quota[day] = quota[day] + _amount;
                        super.sendFrom(
                            _from,
                            _dstChainId,
                            _toAddress,
                            _amount,
                            _refundAddress,
                            _zroPaymentAddress,
                            _adapterParams
                        );
                    }
                    function updatePrice(
                        uint16 _dstChainId,
                        bytes memory _toAddress
                    ) external payable returns (uint256 price) {
                        require(enable, "invalid");
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        require(id != _dstChainId, "same chain");
                        price = tokenPrice();
                        bytes memory lzPayload = abi.encode(
                            PT_FEED,
                            _toAddress,
                            price,
                            block.timestamp
                        );
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit FeedToChain(_dstChainId, msg.sender, _toAddress, price);
                    }
                    function setEnableFor(
                        uint16 _dstChainId,
                        bool _flag,
                        bytes memory _toAddress
                    ) external payable onlyOwner {
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        if (_dstChainId == id) {
                            enable = _flag;
                            emit SetEnableFor(
                                _dstChainId,
                                abi.encodePacked(address(this)),
                                enable
                            );
                            return;
                        }
                        bytes memory lzPayload = abi.encode(PT_SET_ENABLE, _toAddress, _flag);
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit SetEnableFor(_dstChainId, _toAddress, _flag);
                    }
                    function setCapFor(
                        uint16 _dstChainId,
                        uint256 _cap,
                        bytes memory _toAddress
                    ) external payable onlyOwner {
                        uint256 id;
                        assembly {
                            id := chainid()
                        }
                        if (_dstChainId == id) {
                            cap = _cap;
                            emit SetCapFor(_dstChainId, abi.encodePacked(address(this)), cap);
                            return;
                        }
                        bytes memory lzPayload = abi.encode(PT_SET_CAP, _toAddress, _cap);
                        _lzSend(
                            _dstChainId,
                            lzPayload,
                            payable(msg.sender),
                            address(0),
                            bytes(""),
                            msg.value
                        );
                        emit SetCapFor(_dstChainId, _toAddress, _cap);
                    }
                    function tokenPrice() public returns (uint256 price) {
                        price = Minter(minter).getTokenPrice();
                    }
                    function getQuota() external view returns (uint256) {
                        uint256 amount = quota[block.timestamp / DAY_INTERVAL];
                        if (cap > amount && enable) {
                            return cap - amount;
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {Stone} from "./Stone.sol";
                import {StoneVault} from "../StoneVault.sol";
                contract Minter {
                    // TODO: governable upgrade
                    address public stone;
                    address payable public vault;
                    modifier onlyVault() {
                        require(msg.sender == vault, "not vault");
                        _;
                    }
                    constructor(address _stone, address payable _vault) {
                        stone = _stone;
                        vault = _vault;
                    }
                    function mint(address _to, uint256 _amount) external onlyVault {
                        Stone(stone).mint(_to, _amount);
                    }
                    function burn(address _from, uint256 _amount) external onlyVault {
                        Stone(stone).burn(_from, _amount);
                    }
                    function setNewVault(address _vault) external onlyVault {
                        vault = payable(_vault);
                    }
                    function getTokenPrice() public returns (uint256 price) {
                        price = StoneVault(vault).currentSharePrice();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                import {Strategy} from "./Strategy.sol";
                import {AssetsVault} from "../AssetsVault.sol";
                contract StrategyController {
                    using EnumerableSet for EnumerableSet.AddressSet;
                    uint256 internal constant ONE_HUNDRED_PERCENT = 1e6;
                    address public stoneVault;
                    address payable public immutable assetsVault;
                    EnumerableSet.AddressSet private strategies;
                    mapping(address => uint256) public ratios;
                    struct StrategyDiff {
                        address strategy;
                        bool isDeposit;
                        uint256 amount;
                    }
                    modifier onlyVault() {
                        require(stoneVault == msg.sender, "not vault");
                        _;
                    }
                    constructor(
                        address payable _assetsVault,
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) {
                        require(_assetsVault != address(0), "ZERO ADDRESS");
                        uint256 length = _strategies.length;
                        for (uint256 i; i < length; i++) {
                            require(_strategies[i] != address(0), "ZERO ADDRESS");
                        }
                        stoneVault = msg.sender;
                        assetsVault = _assetsVault;
                        _initStrategies(_strategies, _ratios);
                    }
                    function onlyRebaseStrategies() external {
                        _rebase(0, 0);
                    }
                    function forceWithdraw(
                        uint256 _amount
                    ) external onlyVault returns (uint256 actualAmount) {
                        uint256 balanceBeforeRepay = address(this).balance;
                        if (balanceBeforeRepay >= _amount) {
                            _repayToVault();
                            actualAmount = balanceBeforeRepay;
                        } else {
                            actualAmount =
                                _forceWithdraw(_amount - balanceBeforeRepay) +
                                balanceBeforeRepay;
                        }
                    }
                    function setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) external onlyVault {
                        _setStrategies(_strategies, _ratios);
                    }
                    function addStrategy(address _strategy) external onlyVault {
                        require(!strategies.contains(_strategy), "already exist");
                        strategies.add(_strategy);
                    }
                    function rebaseStrategies(
                        uint256 _in,
                        uint256 _out
                    ) external payable onlyVault {
                        _rebase(_in, _out);
                    }
                    function destroyStrategy(address _strategy) external onlyVault {
                        _destoryStrategy(_strategy);
                    }
                    function _rebase(uint256 _in, uint256 _out) internal {
                        require(_in == 0 || _out == 0, "only deposit or withdraw");
                        if (_in != 0) {
                            AssetsVault(assetsVault).withdraw(address(this), _in);
                        }
                        uint256 total = getAllStrategyValidValue();
                        if (total < _out) {
                            total = 0;
                        } else {
                            total = total + _in - _out;
                        }
                        uint256 length = strategies.length();
                        StrategyDiff[] memory diffs = new StrategyDiff[](length);
                        uint256 head;
                        uint256 tail = length - 1;
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            if (ratios[strategy] == 0) {
                                _clearStrategy(strategy, true);
                                continue;
                            }
                            uint256 newPosition = (total * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            uint256 position = getStrategyValidValue(strategy);
                            if (newPosition < position) {
                                diffs[head] = StrategyDiff(
                                    strategy,
                                    false,
                                    position - newPosition
                                );
                                head++;
                            } else if (newPosition > position) {
                                diffs[tail] = StrategyDiff(
                                    strategy,
                                    true,
                                    newPosition - position
                                );
                                if (tail != 0) {
                                    tail--;
                                }
                            }
                        }
                        length = diffs.length;
                        for (uint256 i; i < length; i++) {
                            StrategyDiff memory diff = diffs[i];
                            if (diff.amount == 0) {
                                continue;
                            }
                            if (diff.isDeposit) {
                                if (address(this).balance < diff.amount) {
                                    diff.amount = address(this).balance;
                                }
                                _depositToStrategy(diff.strategy, diff.amount);
                            } else {
                                _withdrawFromStrategy(diff.strategy, diff.amount);
                            }
                        }
                        _repayToVault();
                    }
                    function _repayToVault() internal {
                        if (address(this).balance != 0) {
                            TransferHelper.safeTransferETH(assetsVault, address(this).balance);
                        }
                    }
                    function _depositToStrategy(address _strategy, uint256 _amount) internal {
                        Strategy(_strategy).deposit{value: _amount}();
                    }
                    function _withdrawFromStrategy(
                        address _strategy,
                        uint256 _amount
                    ) internal {
                        Strategy(_strategy).withdraw(_amount);
                    }
                    function _forceWithdraw(
                        uint256 _amount
                    ) internal returns (uint256 actualAmount) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            uint256 withAmount = (_amount * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            if (withAmount != 0) {
                                actualAmount =
                                    Strategy(strategy).instantWithdraw(withAmount) +
                                    actualAmount;
                            }
                        }
                        _repayToVault();
                    }
                    function getStrategyValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getAllValue();
                    }
                    function getStrategyValidValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getInvestedValue();
                    }
                    function getStrategyPendingValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getPendingValue();
                    }
                    function getAllStrategiesValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyValidValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValidValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyPendingValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyPendingValue(strategies.at(i));
                        }
                    }
                    function getStrategies()
                        public
                        view
                        returns (address[] memory addrs, uint256[] memory portions)
                    {
                        uint256 length = strategies.length();
                        addrs = new address[](length);
                        portions = new uint256[](length);
                        for (uint256 i; i < length; i++) {
                            address addr = strategies.at(i);
                            addrs[i] = addr;
                            portions[i] = ratios[addr];
                        }
                    }
                    function _initStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        require(_strategies.length == _ratios.length, "invalid length");
                        uint256 totalRatio;
                        uint256 length = _strategies.length;
                        for (uint i; i < length; i++) {
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function _setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        uint256 length = _strategies.length;
                        require(length == _ratios.length, "invalid length");
                        uint256 oldLength = strategies.length();
                        for (uint i; i < oldLength; i++) {
                            ratios[strategies.at(i)] = 0;
                        }
                        uint256 totalRatio;
                        for (uint i; i < length; i++) {
                            require(
                                Strategy(_strategies[i]).controller() == address(this),
                                "controller mismatch"
                            );
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function clearStrategy(address _strategy) public onlyVault {
                        _clearStrategy(_strategy, false);
                    }
                    function _clearStrategy(address _strategy, bool _isRebase) internal {
                        Strategy(_strategy).clear();
                        if (!_isRebase) {
                            _repayToVault();
                        }
                    }
                    function _destoryStrategy(address _strategy) internal {
                        require(_couldDestroyStrategy(_strategy), "still active");
                        strategies.remove(_strategy);
                        _repayToVault();
                    }
                    function _couldDestroyStrategy(
                        address _strategy
                    ) internal returns (bool status) {
                        return
                            ratios[_strategy] == 0 && Strategy(_strategy).getAllValue() < 1e4;
                    }
                    function setNewVault(address _vault) external onlyVault {
                        stoneVault = _vault;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {StrategyController} from "../strategies/StrategyController.sol";
                abstract contract Strategy {
                    address payable public immutable controller;
                    address public governance;
                    string public name;
                    modifier onlyGovernance() {
                        require(governance == msg.sender, "not governace");
                        _;
                    }
                    event TransferGovernance(address oldOwner, address newOwner);
                    constructor(address payable _controller, string memory _name) {
                        require(_controller != address(0), "ZERO ADDRESS");
                        governance = msg.sender;
                        controller = _controller;
                        name = _name;
                    }
                    modifier onlyController() {
                        require(controller == msg.sender, "not controller");
                        _;
                    }
                    function deposit() public payable virtual onlyController {}
                    function withdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function instantWithdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function clear() public virtual onlyController returns (uint256 amount) {}
                    function execPendingRequest(
                        uint256 _amount
                    ) public virtual returns (uint256 amount) {}
                    function getAllValue() public virtual returns (uint256 value) {}
                    function getPendingValue() public virtual returns (uint256 value) {}
                    function getInvestedValue() public virtual returns (uint256 value) {}
                    function checkPendingStatus()
                        public
                        virtual
                        returns (uint256 pending, uint256 executable)
                    {}
                    function setGovernance(address governance_) external onlyGovernance {
                        emit TransferGovernance(governance, governance_);
                        governance = governance_;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                library VaultMath {
                    uint256 internal constant DECIMALS = 18;
                    function assetToShares(
                        uint256 _assetAmount,
                        uint256 _assetPerShare
                    ) internal pure returns (uint256) {
                        require(_assetPerShare > 1, "Vault Lib: invalid assetPerShare");
                        return (_assetAmount * (10 ** DECIMALS)) / _assetPerShare;
                    }
                    function sharesToAsset(
                        uint256 _shares,
                        uint256 _assetPerShare
                    ) internal pure returns (uint256) {
                        require(_assetPerShare > 1, "Vault Lib: invalid assetPerShare");
                        return (_shares * _assetPerShare) / (10 ** DECIMALS);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
                import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                import {Minter} from "./token/Minter.sol";
                import {Stone} from "./token/Stone.sol";
                import {AssetsVault} from "./AssetsVault.sol";
                import {StrategyController} from "./strategies/StrategyController.sol";
                import {VaultMath} from "./libraries/VaultMath.sol";
                contract StoneVault is ReentrancyGuard, Ownable {
                    uint256 internal constant MULTIPLIER = 1e18;
                    uint256 internal constant ONE_HUNDRED_PERCENT = 1e6;
                    uint256 internal constant MAXMIUM_FEE_RATE = ONE_HUNDRED_PERCENT / 100; // 1%
                    uint256 internal constant MINIMUM_REBASE_INTERVAL = 7 * 24 * 60 * 60;
                    uint256 public constant VERSION = 1;
                    uint256 public rebaseTimeInterval = 24 * 60 * 60;
                    address public immutable minter;
                    address public immutable stone;
                    address payable public immutable strategyController;
                    address payable public immutable assetsVault;
                    address public proposal;
                    address public feeRecipient;
                    uint256 public latestRoundID;
                    uint256 public withdrawableAmountInPast;
                    uint256 public withdrawingSharesInPast;
                    uint256 public withdrawingSharesInRound;
                    uint256 public withdrawFeeRate;
                    uint256 public rebaseTime;
                    mapping(uint256 => uint256) public roundPricePerShare;
                    mapping(uint256 => uint256) public settlementTime;
                    mapping(address => UserReceipt) public userReceipts;
                    struct UserReceipt {
                        uint256 withdrawRound;
                        uint256 withdrawShares;
                        uint256 withdrawableAmount;
                    }
                    event Deposit(
                        address indexed account,
                        uint256 amount,
                        uint256 mint,
                        uint256 round
                    );
                    event InitiateWithdraw(
                        address indexed account,
                        uint256 shares,
                        uint256 round
                    );
                    event CancelWithdraw(
                        address indexed account,
                        uint256 amount,
                        uint256 round
                    );
                    event Withdrawn(address indexed account, uint256 amount, uint256 round);
                    event WithdrawnFromStrategy(
                        address indexed account,
                        uint256 amount,
                        uint256 actualAmount,
                        uint256 round
                    );
                    event RollToNextRound(
                        uint256 round,
                        uint256 vaultIn,
                        uint256 vaultOut,
                        uint256 sharePrice
                    );
                    event StragetyAdded(address strategy);
                    event StragetyDestroyed(address strategy);
                    event StragetyCleared(address strategy);
                    event PortfolioConfigUpdated(address[] strategies, uint256[] ratios);
                    event FeeCharged(address indexed account, uint256 amount);
                    event SetWithdrawFeeRate(uint256 oldRate, uint256 newRate);
                    event SetFeeRecipient(address oldAddr, address newAddr);
                    event SetRebaseInterval(uint256 interval);
                    modifier onlyProposal() {
                        require(proposal == msg.sender, "not proposal");
                        _;
                    }
                    constructor(
                        address _minter,
                        address _proposal,
                        address payable _assetsVault,
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) {
                        require(
                            _minter != address(0) &&
                                _proposal != address(0) &&
                                _assetsVault != address(0),
                            "ZERO ADDRESS"
                        );
                        uint256 length = _strategies.length;
                        for (uint256 i; i < length; i++) {
                            require(_strategies[i] != address(0), "ZERO ADDRESS");
                        }
                        minter = _minter;
                        proposal = _proposal;
                        assetsVault = _assetsVault;
                        feeRecipient = msg.sender;
                        StrategyController controller = new StrategyController(
                            _assetsVault,
                            _strategies,
                            _ratios
                        );
                        strategyController = payable(address(controller));
                        stone = Minter(_minter).stone();
                        roundPricePerShare[0] = MULTIPLIER;
                        latestRoundID = 0;
                    }
                    function deposit()
                        external
                        payable
                        nonReentrant
                        returns (uint256 mintAmount)
                    {
                        mintAmount = _depositFor(msg.value, msg.sender);
                    }
                    function depositFor(
                        address _user
                    ) external payable nonReentrant returns (uint256 mintAmount) {
                        mintAmount = _depositFor(msg.value, _user);
                    }
                    function _depositFor(
                        uint256 _amount,
                        address _user
                    ) internal returns (uint256 mintAmount) {
                        require(_amount != 0, "too small");
                        uint256 sharePrice;
                        uint256 currSharePrice = currentSharePrice();
                        if (latestRoundID == 0) {
                            sharePrice = MULTIPLIER;
                        } else {
                            uint256 latestSharePrice = roundPricePerShare[latestRoundID - 1];
                            sharePrice = latestSharePrice > currSharePrice
                                ? latestSharePrice
                                : currSharePrice;
                        }
                        mintAmount = (_amount * MULTIPLIER) / sharePrice;
                        AssetsVault(assetsVault).deposit{value: address(this).balance}();
                        Minter(minter).mint(_user, mintAmount);
                        emit Deposit(_user, _amount, mintAmount, latestRoundID);
                    }
                    function requestWithdraw(uint256 _shares) external nonReentrant {
                        require(_shares != 0, "too small");
                        require(latestRoundID != 0, "should withdraw instantly");
                        Stone stoneToken = Stone(stone);
                        Minter stoneMinter = Minter(minter);
                        require(stoneToken.balanceOf(msg.sender) >= _shares, "exceed balance");
                        TransferHelper.safeTransferFrom(
                            stone,
                            msg.sender,
                            address(this),
                            _shares
                        );
                        withdrawingSharesInRound = withdrawingSharesInRound + _shares;
                        UserReceipt storage receipt = userReceipts[msg.sender];
                        if (receipt.withdrawRound == latestRoundID) {
                            receipt.withdrawShares = receipt.withdrawShares + _shares;
                        } else if (receipt.withdrawRound == 0) {
                            receipt.withdrawShares = _shares;
                            receipt.withdrawRound = latestRoundID;
                        } else {
                            // Withdraw previous round share first
                            uint256 withdrawAmount = VaultMath.sharesToAsset(
                                receipt.withdrawShares,
                                roundPricePerShare[receipt.withdrawRound]
                            );
                            stoneMinter.burn(address(this), receipt.withdrawShares);
                            withdrawingSharesInPast =
                                withdrawingSharesInPast -
                                receipt.withdrawShares;
                            receipt.withdrawShares = _shares;
                            receipt.withdrawableAmount =
                                receipt.withdrawableAmount +
                                withdrawAmount;
                            receipt.withdrawRound = latestRoundID;
                        }
                        emit InitiateWithdraw(msg.sender, _shares, latestRoundID);
                    }
                    function cancelWithdraw(uint256 _shares) external nonReentrant {
                        require(_shares != 0, "too small");
                        UserReceipt storage receipt = userReceipts[msg.sender];
                        require(receipt.withdrawRound == latestRoundID, "no pending withdraw");
                        require(receipt.withdrawShares >= _shares, "exceed pending withdraw");
                        receipt.withdrawShares = receipt.withdrawShares - _shares;
                        TransferHelper.safeTransfer(stone, msg.sender, _shares);
                        if (receipt.withdrawShares == 0) {
                            receipt.withdrawRound = 0;
                        }
                        withdrawingSharesInRound = withdrawingSharesInRound - _shares;
                        emit CancelWithdraw(msg.sender, _shares, latestRoundID);
                    }
                    function instantWithdraw(
                        uint256 _amount,
                        uint256 _shares
                    ) external nonReentrant returns (uint256 actualWithdrawn) {
                        require(_amount != 0 || _shares != 0, "too small");
                        AssetsVault aVault = AssetsVault(assetsVault);
                        Minter stoneMinter = Minter(minter);
                        (uint256 idleAmount, ) = getVaultAvailableAmount();
                        if (_amount != 0) {
                            UserReceipt storage receipt = userReceipts[msg.sender];
                            if (
                                receipt.withdrawRound != latestRoundID &&
                                receipt.withdrawRound != 0
                            ) {
                                // Withdraw previous round share first
                                uint256 withdrawAmount = VaultMath.sharesToAsset(
                                    receipt.withdrawShares,
                                    roundPricePerShare[receipt.withdrawRound]
                                );
                                stoneMinter.burn(address(this), receipt.withdrawShares);
                                withdrawingSharesInPast =
                                    withdrawingSharesInPast -
                                    receipt.withdrawShares;
                                receipt.withdrawShares = 0;
                                receipt.withdrawableAmount =
                                    receipt.withdrawableAmount +
                                    withdrawAmount;
                                receipt.withdrawRound = 0;
                            }
                            require(
                                receipt.withdrawableAmount >= _amount,
                                "exceed withdrawable"
                            );
                            receipt.withdrawableAmount = receipt.withdrawableAmount - _amount;
                            withdrawableAmountInPast = withdrawableAmountInPast - _amount;
                            actualWithdrawn = _amount;
                            emit Withdrawn(msg.sender, _amount, latestRoundID);
                        }
                        if (_shares != 0) {
                            uint256 sharePrice;
                            if (latestRoundID == 0) {
                                sharePrice = MULTIPLIER;
                            } else {
                                uint256 currSharePrice = currentSharePrice();
                                uint256 latestSharePrice = roundPricePerShare[
                                    latestRoundID - 1
                                ];
                                sharePrice = latestSharePrice < currSharePrice
                                    ? latestSharePrice
                                    : currSharePrice;
                            }
                            uint256 ethAmount = VaultMath.sharesToAsset(_shares, sharePrice);
                            stoneMinter.burn(msg.sender, _shares);
                            if (ethAmount <= idleAmount) {
                                actualWithdrawn = actualWithdrawn + ethAmount;
                                emit Withdrawn(msg.sender, ethAmount, latestRoundID);
                            } else {
                                actualWithdrawn = actualWithdrawn + idleAmount;
                                ethAmount = ethAmount - idleAmount;
                                StrategyController controller = StrategyController(
                                    strategyController
                                );
                                uint256 actualAmount = controller.forceWithdraw(ethAmount);
                                actualWithdrawn = actualWithdrawn + actualAmount;
                                emit WithdrawnFromStrategy(
                                    msg.sender,
                                    ethAmount,
                                    actualAmount,
                                    latestRoundID
                                );
                            }
                        }
                        require(aVault.getBalance() >= actualWithdrawn, "still need wait");
                        uint256 withFee;
                        if (withdrawFeeRate != 0) {
                            withFee = (actualWithdrawn * withdrawFeeRate) / ONE_HUNDRED_PERCENT;
                            aVault.withdraw(feeRecipient, withFee);
                            emit FeeCharged(msg.sender, withFee);
                        }
                        aVault.withdraw(msg.sender, actualWithdrawn - withFee);
                    }
                    function rollToNextRound() external {
                        require(
                            block.timestamp > rebaseTime + rebaseTimeInterval,
                            "already rebased"
                        );
                        StrategyController controller = StrategyController(strategyController);
                        AssetsVault aVault = AssetsVault(assetsVault);
                        uint256 previewSharePrice = currentSharePrice();
                        uint256 vaultBalance = aVault.getBalance();
                        uint256 amountToWithdraw = VaultMath.sharesToAsset(
                            withdrawingSharesInRound,
                            previewSharePrice
                        );
                        uint256 amountVaultNeed = withdrawableAmountInPast + amountToWithdraw;
                        uint256 allPendingValue = controller.getAllStrategyPendingValue();
                        uint256 vaultIn;
                        uint256 vaultOut;
                        if (vaultBalance > amountVaultNeed) {
                            vaultIn = vaultBalance - amountVaultNeed;
                        } else if (vaultBalance + allPendingValue < amountVaultNeed) {
                            vaultOut = amountVaultNeed - vaultBalance - allPendingValue;
                        }
                        controller.rebaseStrategies(vaultIn, vaultOut);
                        uint256 newSharePrice = currentSharePrice();
                        roundPricePerShare[latestRoundID] = previewSharePrice < newSharePrice
                            ? previewSharePrice
                            : newSharePrice;
                        settlementTime[latestRoundID] = block.timestamp;
                        latestRoundID = latestRoundID + 1;
                        withdrawingSharesInPast =
                            withdrawingSharesInPast +
                            withdrawingSharesInRound;
                        withdrawableAmountInPast =
                            withdrawableAmountInPast +
                            VaultMath.sharesToAsset(withdrawingSharesInRound, newSharePrice);
                        withdrawingSharesInRound = 0;
                        rebaseTime = block.timestamp;
                        emit RollToNextRound(latestRoundID, vaultIn, vaultOut, newSharePrice);
                    }
                    function addStrategy(address _strategy) external onlyProposal {
                        StrategyController controller = StrategyController(strategyController);
                        controller.addStrategy(_strategy);
                        emit StragetyAdded(_strategy);
                    }
                    function destroyStrategy(address _strategy) external onlyOwner {
                        StrategyController controller = StrategyController(strategyController);
                        controller.destroyStrategy(_strategy);
                        emit StragetyDestroyed(_strategy);
                    }
                    function clearStrategy(address _strategy) external onlyOwner {
                        StrategyController controller = StrategyController(strategyController);
                        controller.clearStrategy(_strategy);
                        emit StragetyCleared(_strategy);
                    }
                    function updatePortfolioConfig(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) external onlyProposal {
                        StrategyController controller = StrategyController(strategyController);
                        controller.setStrategies(_strategies, _ratios);
                        emit PortfolioConfigUpdated(_strategies, _ratios);
                    }
                    function updateProposal(address _proposal) external onlyProposal {
                        proposal = _proposal;
                    }
                    function migrateVault(address _vault) external onlyProposal {
                        Minter(minter).setNewVault(_vault);
                        AssetsVault(assetsVault).setNewVault(_vault);
                        StrategyController(strategyController).setNewVault(_vault);
                    }
                    function currentSharePrice() public returns (uint256 price) {
                        Stone stoneToken = Stone(stone);
                        uint256 totalStone = stoneToken.totalSupply();
                        if (
                            latestRoundID == 0 ||
                            totalStone == 0 ||
                            totalStone == withdrawingSharesInPast
                        ) {
                            return MULTIPLIER;
                        }
                        uint256 etherAmount = AssetsVault(assetsVault).getBalance() +
                            StrategyController(strategyController).getAllStrategiesValue() -
                            withdrawableAmountInPast;
                        uint256 activeShare = totalStone - withdrawingSharesInPast;
                        return (etherAmount * MULTIPLIER) / activeShare;
                    }
                    function getVaultAvailableAmount()
                        public
                        returns (uint256 idleAmount, uint256 investedAmount)
                    {
                        AssetsVault vault = AssetsVault(assetsVault);
                        if (vault.getBalance() > withdrawableAmountInPast) {
                            idleAmount = vault.getBalance() - withdrawableAmountInPast;
                        }
                        investedAmount = StrategyController(strategyController)
                            .getAllStrategyValidValue();
                    }
                    function setWithdrawFeeRate(uint256 _withdrawFeeRate) external onlyOwner {
                        require(_withdrawFeeRate <= MAXMIUM_FEE_RATE, "exceed maximum");
                        emit SetWithdrawFeeRate(withdrawFeeRate, _withdrawFeeRate);
                        withdrawFeeRate = _withdrawFeeRate;
                    }
                    function setFeeRecipient(address _feeRecipient) external onlyOwner {
                        require(_feeRecipient != address(0), "zero address");
                        emit SetFeeRecipient(feeRecipient, _feeRecipient);
                        feeRecipient = _feeRecipient;
                    }
                    function setRebaseInterval(uint256 _interval) external onlyOwner {
                        require(_interval <= MINIMUM_REBASE_INTERVAL, "invalid");
                        rebaseTimeInterval = _interval;
                        emit SetRebaseInterval(rebaseTimeInterval);
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                contract AssetsVault {
                    address public stoneVault;
                    address public strategyController;
                    modifier onlyPermit() {
                        require(
                            stoneVault == msg.sender || strategyController == msg.sender,
                            "not permit"
                        );
                        _;
                    }
                    constructor(address _stoneVault, address _strategyController) {
                        require(
                            _stoneVault != address(0) && _strategyController != address(0),
                            "ZERO ADDRESS"
                        );
                        stoneVault = _stoneVault;
                        strategyController = _strategyController;
                    }
                    function deposit() external payable {
                        require(msg.value != 0, "too small");
                    }
                    function withdraw(address _to, uint256 _amount) external onlyPermit {
                        TransferHelper.safeTransferETH(_to, _amount);
                    }
                    function setNewVault(address _vault) external onlyPermit {
                        stoneVault = _vault;
                    }
                    function getBalance() external view returns (uint256 amount) {
                        amount = address(this).balance;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: GPL-2.0-or-later
                pragma solidity >=0.6.0;
                import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                library TransferHelper {
                    /// @notice Transfers tokens from the targeted address to the given destination
                    /// @notice Errors with 'STF' if transfer fails
                    /// @param token The contract address of the token to be transferred
                    /// @param from The originating address from which the tokens will be transferred
                    /// @param to The destination address of the transfer
                    /// @param value The amount to be transferred
                    function safeTransferFrom(
                        address token,
                        address from,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) =
                            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
                    }
                    /// @notice Transfers tokens from msg.sender to a recipient
                    /// @dev Errors with ST if transfer fails
                    /// @param token The contract address of the token which will be transferred
                    /// @param to The recipient of the transfer
                    /// @param value The value of the transfer
                    function safeTransfer(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
                    }
                    /// @notice Approves the stipulated contract to spend the given allowance in the given token
                    /// @dev Errors with 'SA' if transfer fails
                    /// @param token The contract address of the token to be approved
                    /// @param to The target of the approval
                    /// @param value The amount of the given token the target will be allowed to spend
                    function safeApprove(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
                    }
                    /// @notice Transfers ETH to the recipient address
                    /// @dev Fails with `STE`
                    /// @param to The destination of the transfer
                    /// @param value The value to be transferred
                    function safeTransferETH(address to, uint256 value) internal {
                        (bool success, ) = to.call{value: value}(new bytes(0));
                        require(success, 'STE');
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
                // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for managing
                 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                 * types.
                 *
                 * Sets have the following properties:
                 *
                 * - Elements are added, removed, and checked for existence in constant time
                 * (O(1)).
                 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                 *
                 * ```solidity
                 * contract Example {
                 *     // Add the library methods
                 *     using EnumerableSet for EnumerableSet.AddressSet;
                 *
                 *     // Declare a set state variable
                 *     EnumerableSet.AddressSet private mySet;
                 * }
                 * ```
                 *
                 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                 * and `uint256` (`UintSet`) are supported.
                 *
                 * [WARNING]
                 * ====
                 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
                 * unusable.
                 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
                 *
                 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
                 * array of EnumerableSet.
                 * ====
                 */
                library EnumerableSet {
                    // To implement this library for multiple types with as little code
                    // repetition as possible, we write it in terms of a generic Set type with
                    // bytes32 values.
                    // The Set implementation uses private functions, and user-facing
                    // implementations (such as AddressSet) are just wrappers around the
                    // underlying Set.
                    // This means that we can only create new EnumerableSets for types that fit
                    // in bytes32.
                    struct Set {
                        // Storage of set values
                        bytes32[] _values;
                        // Position of the value in the `values` array, plus 1 because index 0
                        // means a value is not in the set.
                        mapping(bytes32 => uint256) _indexes;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function _add(Set storage set, bytes32 value) private returns (bool) {
                        if (!_contains(set, value)) {
                            set._values.push(value);
                            // The value is stored at length-1, but we add 1 to all indexes
                            // and use 0 as a sentinel value
                            set._indexes[value] = set._values.length;
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function _remove(Set storage set, bytes32 value) private returns (bool) {
                        // We read and store the value's index to prevent multiple reads from the same storage slot
                        uint256 valueIndex = set._indexes[value];
                        if (valueIndex != 0) {
                            // Equivalent to contains(set, value)
                            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                            // the array, and then remove the last element (sometimes called as 'swap and pop').
                            // This modifies the order of the array, as noted in {at}.
                            uint256 toDeleteIndex = valueIndex - 1;
                            uint256 lastIndex = set._values.length - 1;
                            if (lastIndex != toDeleteIndex) {
                                bytes32 lastValue = set._values[lastIndex];
                                // Move the last value to the index where the value to delete is
                                set._values[toDeleteIndex] = lastValue;
                                // Update the index for the moved value
                                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                            }
                            // Delete the slot where the moved value was stored
                            set._values.pop();
                            // Delete the index for the deleted slot
                            delete set._indexes[value];
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function _contains(Set storage set, bytes32 value) private view returns (bool) {
                        return set._indexes[value] != 0;
                    }
                    /**
                     * @dev Returns the number of values on the set. O(1).
                     */
                    function _length(Set storage set) private view returns (uint256) {
                        return set._values.length;
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function _at(Set storage set, uint256 index) private view returns (bytes32) {
                        return set._values[index];
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function _values(Set storage set) private view returns (bytes32[] memory) {
                        return set._values;
                    }
                    // Bytes32Set
                    struct Bytes32Set {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _add(set._inner, value);
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _remove(set._inner, value);
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                        return _contains(set._inner, value);
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(Bytes32Set storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                        return _at(set._inner, index);
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        bytes32[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // AddressSet
                    struct AddressSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(AddressSet storage set, address value) internal returns (bool) {
                        return _add(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(AddressSet storage set, address value) internal returns (bool) {
                        return _remove(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(AddressSet storage set, address value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(AddressSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(AddressSet storage set, uint256 index) internal view returns (address) {
                        return address(uint160(uint256(_at(set._inner, index))));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(AddressSet storage set) internal view returns (address[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        address[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // UintSet
                    struct UintSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(UintSet storage set, uint256 value) internal returns (bool) {
                        return _add(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(UintSet storage set, uint256 value) internal returns (bool) {
                        return _remove(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(UintSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                        return uint256(_at(set._inner, index));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(UintSet storage set) internal view returns (uint256[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        uint256[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC165 standard, as defined in the
                 * https://eips.ethereum.org/EIPS/eip-165[EIP].
                 *
                 * Implementers can declare support of contract interfaces, which can then be
                 * queried by others ({ERC165Checker}).
                 *
                 * For an implementation, see {ERC165}.
                 */
                interface IERC165 {
                    /**
                     * @dev Returns true if this contract implements the interface defined by
                     * `interfaceId`. See the corresponding
                     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                     * to learn more about how these ids are created.
                     *
                     * This function call must use less than 30 000 gas.
                     */
                    function supportsInterface(bytes4 interfaceId) external view returns (bool);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
                pragma solidity ^0.8.0;
                import "./IERC165.sol";
                /**
                 * @dev Implementation of the {IERC165} interface.
                 *
                 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
                 * for the additional interface id that will be supported. For example:
                 *
                 * ```solidity
                 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
                 * }
                 * ```
                 *
                 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
                 */
                abstract contract ERC165 is IERC165 {
                    /**
                     * @dev See {IERC165-supportsInterface}.
                     */
                    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                        return interfaceId == type(IERC165).interfaceId;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Provides information about the current execution context, including the
                 * sender of the transaction and its data. While these are generally available
                 * via msg.sender and msg.data, they should not be accessed in such a direct
                 * manner, since when dealing with meta-transactions the account sending and
                 * paying for execution may not be the actual sender (as far as an application
                 * is concerned).
                 *
                 * This contract is only required for intermediate, library-like contracts.
                 */
                abstract contract Context {
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                pragma solidity ^0.8.0;
                import "../IERC20.sol";
                /**
                 * @dev Interface for the optional metadata functions from the ERC20 standard.
                 *
                 * _Available since v4.1._
                 */
                interface IERC20Metadata is IERC20 {
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() external view returns (string memory);
                    /**
                     * @dev Returns the symbol of the token.
                     */
                    function symbol() external view returns (string memory);
                    /**
                     * @dev Returns the decimals places of the token.
                     */
                    function decimals() external view returns (uint8);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                    /**
                     * @dev Returns the amount of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                    /**
                     * @dev Returns the amount of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * @dev Moves `amount` tokens from the caller's account to `to`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address to, uint256 amount) external returns (bool);
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 amount) external returns (bool);
                    /**
                     * @dev Moves `amount` tokens from `from` to `to` using the
                     * allowance mechanism. `amount` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address from, address to, uint256 amount) external returns (bool);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
                pragma solidity ^0.8.0;
                import "./IERC20.sol";
                import "./extensions/IERC20Metadata.sol";
                import "../../utils/Context.sol";
                /**
                 * @dev Implementation of the {IERC20} interface.
                 *
                 * This implementation is agnostic to the way tokens are created. This means
                 * that a supply mechanism has to be added in a derived contract using {_mint}.
                 * For a generic mechanism see {ERC20PresetMinterPauser}.
                 *
                 * TIP: For a detailed writeup see our guide
                 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                 * to implement supply mechanisms].
                 *
                 * The default value of {decimals} is 18. To change this, you should override
                 * this function so it returns a different value.
                 *
                 * We have followed general OpenZeppelin Contracts guidelines: functions revert
                 * instead returning `false` on failure. This behavior is nonetheless
                 * conventional and does not conflict with the expectations of ERC20
                 * applications.
                 *
                 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                 * This allows applications to reconstruct the allowance for all accounts just
                 * by listening to said events. Other implementations of the EIP may not emit
                 * these events, as it isn't required by the specification.
                 *
                 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                 * functions have been added to mitigate the well-known issues around setting
                 * allowances. See {IERC20-approve}.
                 */
                contract ERC20 is Context, IERC20, IERC20Metadata {
                    mapping(address => uint256) private _balances;
                    mapping(address => mapping(address => uint256)) private _allowances;
                    uint256 private _totalSupply;
                    string private _name;
                    string private _symbol;
                    /**
                     * @dev Sets the values for {name} and {symbol}.
                     *
                     * All two of these values are immutable: they can only be set once during
                     * construction.
                     */
                    constructor(string memory name_, string memory symbol_) {
                        _name = name_;
                        _symbol = symbol_;
                    }
                    /**
                     * @dev Returns the name of the token.
                     */
                    function name() public view virtual override returns (string memory) {
                        return _name;
                    }
                    /**
                     * @dev Returns the symbol of the token, usually a shorter version of the
                     * name.
                     */
                    function symbol() public view virtual override returns (string memory) {
                        return _symbol;
                    }
                    /**
                     * @dev Returns the number of decimals used to get its user representation.
                     * For example, if `decimals` equals `2`, a balance of `505` tokens should
                     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                     *
                     * Tokens usually opt for a value of 18, imitating the relationship between
                     * Ether and Wei. This is the default value returned by this function, unless
                     * it's overridden.
                     *
                     * NOTE: This information is only used for _display_ purposes: it in
                     * no way affects any of the arithmetic of the contract, including
                     * {IERC20-balanceOf} and {IERC20-transfer}.
                     */
                    function decimals() public view virtual override returns (uint8) {
                        return 18;
                    }
                    /**
                     * @dev See {IERC20-totalSupply}.
                     */
                    function totalSupply() public view virtual override returns (uint256) {
                        return _totalSupply;
                    }
                    /**
                     * @dev See {IERC20-balanceOf}.
                     */
                    function balanceOf(address account) public view virtual override returns (uint256) {
                        return _balances[account];
                    }
                    /**
                     * @dev See {IERC20-transfer}.
                     *
                     * Requirements:
                     *
                     * - `to` cannot be the zero address.
                     * - the caller must have a balance of at least `amount`.
                     */
                    function transfer(address to, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _transfer(owner, to, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-allowance}.
                     */
                    function allowance(address owner, address spender) public view virtual override returns (uint256) {
                        return _allowances[owner][spender];
                    }
                    /**
                     * @dev See {IERC20-approve}.
                     *
                     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                     * `transferFrom`. This is semantically equivalent to an infinite approval.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function approve(address spender, uint256 amount) public virtual override returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, amount);
                        return true;
                    }
                    /**
                     * @dev See {IERC20-transferFrom}.
                     *
                     * Emits an {Approval} event indicating the updated allowance. This is not
                     * required by the EIP. See the note at the beginning of {ERC20}.
                     *
                     * NOTE: Does not update the allowance if the current allowance
                     * is the maximum `uint256`.
                     *
                     * Requirements:
                     *
                     * - `from` and `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     * - the caller must have allowance for ``from``'s tokens of at least
                     * `amount`.
                     */
                    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
                        address spender = _msgSender();
                        _spendAllowance(from, spender, amount);
                        _transfer(from, to, amount);
                        return true;
                    }
                    /**
                     * @dev Atomically increases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     */
                    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        _approve(owner, spender, allowance(owner, spender) + addedValue);
                        return true;
                    }
                    /**
                     * @dev Atomically decreases the allowance granted to `spender` by the caller.
                     *
                     * This is an alternative to {approve} that can be used as a mitigation for
                     * problems described in {IERC20-approve}.
                     *
                     * Emits an {Approval} event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `spender` must have allowance for the caller of at least
                     * `subtractedValue`.
                     */
                    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                        address owner = _msgSender();
                        uint256 currentAllowance = allowance(owner, spender);
                        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                        unchecked {
                            _approve(owner, spender, currentAllowance - subtractedValue);
                        }
                        return true;
                    }
                    /**
                     * @dev Moves `amount` of tokens from `from` to `to`.
                     *
                     * This internal function is equivalent to {transfer}, and can be used to
                     * e.g. implement automatic token fees, slashing mechanisms, etc.
                     *
                     * Emits a {Transfer} event.
                     *
                     * Requirements:
                     *
                     * - `from` cannot be the zero address.
                     * - `to` cannot be the zero address.
                     * - `from` must have a balance of at least `amount`.
                     */
                    function _transfer(address from, address to, uint256 amount) internal virtual {
                        require(from != address(0), "ERC20: transfer from the zero address");
                        require(to != address(0), "ERC20: transfer to the zero address");
                        _beforeTokenTransfer(from, to, amount);
                        uint256 fromBalance = _balances[from];
                        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                        unchecked {
                            _balances[from] = fromBalance - amount;
                            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                            // decrementing then incrementing.
                            _balances[to] += amount;
                        }
                        emit Transfer(from, to, amount);
                        _afterTokenTransfer(from, to, amount);
                    }
                    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                     * the total supply.
                     *
                     * Emits a {Transfer} event with `from` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     */
                    function _mint(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: mint to the zero address");
                        _beforeTokenTransfer(address(0), account, amount);
                        _totalSupply += amount;
                        unchecked {
                            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                            _balances[account] += amount;
                        }
                        emit Transfer(address(0), account, amount);
                        _afterTokenTransfer(address(0), account, amount);
                    }
                    /**
                     * @dev Destroys `amount` tokens from `account`, reducing the
                     * total supply.
                     *
                     * Emits a {Transfer} event with `to` set to the zero address.
                     *
                     * Requirements:
                     *
                     * - `account` cannot be the zero address.
                     * - `account` must have at least `amount` tokens.
                     */
                    function _burn(address account, uint256 amount) internal virtual {
                        require(account != address(0), "ERC20: burn from the zero address");
                        _beforeTokenTransfer(account, address(0), amount);
                        uint256 accountBalance = _balances[account];
                        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                        unchecked {
                            _balances[account] = accountBalance - amount;
                            // Overflow not possible: amount <= accountBalance <= totalSupply.
                            _totalSupply -= amount;
                        }
                        emit Transfer(account, address(0), amount);
                        _afterTokenTransfer(account, address(0), amount);
                    }
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                     *
                     * This internal function is equivalent to `approve`, and can be used to
                     * e.g. set automatic allowances for certain subsystems, etc.
                     *
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `owner` cannot be the zero address.
                     * - `spender` cannot be the zero address.
                     */
                    function _approve(address owner, address spender, uint256 amount) internal virtual {
                        require(owner != address(0), "ERC20: approve from the zero address");
                        require(spender != address(0), "ERC20: approve to the zero address");
                        _allowances[owner][spender] = amount;
                        emit Approval(owner, spender, amount);
                    }
                    /**
                     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                     *
                     * Does not update the allowance amount in case of infinite allowance.
                     * Revert if not enough allowance is available.
                     *
                     * Might emit an {Approval} event.
                     */
                    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                        uint256 currentAllowance = allowance(owner, spender);
                        if (currentAllowance != type(uint256).max) {
                            require(currentAllowance >= amount, "ERC20: insufficient allowance");
                            unchecked {
                                _approve(owner, spender, currentAllowance - amount);
                            }
                        }
                    }
                    /**
                     * @dev Hook that is called before any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * will be transferred to `to`.
                     * - when `from` is zero, `amount` tokens will be minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                    /**
                     * @dev Hook that is called after any transfer of tokens. This includes
                     * minting and burning.
                     *
                     * Calling conditions:
                     *
                     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                     * has been transferred to `to`.
                     * - when `from` is zero, `amount` tokens have been minted for `to`.
                     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                     * - `from` and `to` are never both zero.
                     *
                     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                     */
                    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Contract module that helps prevent reentrant calls to a function.
                 *
                 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                 * available, which can be applied to functions to make sure there are no nested
                 * (reentrant) calls to them.
                 *
                 * Note that because there is a single `nonReentrant` guard, functions marked as
                 * `nonReentrant` may not call one another. This can be worked around by making
                 * those functions `private`, and then adding `external` `nonReentrant` entry
                 * points to them.
                 *
                 * TIP: If you would like to learn more about reentrancy and alternative ways
                 * to protect against it, check out our blog post
                 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                 */
                abstract contract ReentrancyGuard {
                    // Booleans are more expensive than uint256 or any type that takes up a full
                    // word because each write operation emits an extra SLOAD to first read the
                    // slot's contents, replace the bits taken up by the boolean, and then write
                    // back. This is the compiler's defense against contract upgrades and
                    // pointer aliasing, and it cannot be disabled.
                    // The values being non-zero value makes deployment a bit more expensive,
                    // but in exchange the refund on every call to nonReentrant will be lower in
                    // amount. Since refunds are capped to a percentage of the total
                    // transaction's gas, it is best to keep them low in cases like this one, to
                    // increase the likelihood of the full refund coming into effect.
                    uint256 private constant _NOT_ENTERED = 1;
                    uint256 private constant _ENTERED = 2;
                    uint256 private _status;
                    constructor() {
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and making it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        _nonReentrantBefore();
                        _;
                        _nonReentrantAfter();
                    }
                    function _nonReentrantBefore() private {
                        // On the first call to nonReentrant, _status will be _NOT_ENTERED
                        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        // Any calls to nonReentrant after this point will fail
                        _status = _ENTERED;
                    }
                    function _nonReentrantAfter() private {
                        // By storing the original value once again, a refund is triggered (see
                        // https://eips.ethereum.org/EIPS/eip-2200)
                        _status = _NOT_ENTERED;
                    }
                    /**
                     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
                     * `nonReentrant` function in the call stack.
                     */
                    function _reentrancyGuardEntered() internal view returns (bool) {
                        return _status == _ENTERED;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
                pragma solidity ^0.8.0;
                import "../utils/Context.sol";
                /**
                 * @dev Contract module which provides a basic access control mechanism, where
                 * there is an account (an owner) that can be granted exclusive access to
                 * specific functions.
                 *
                 * By default, the owner account will be the one that deploys the contract. This
                 * can later be changed with {transferOwnership}.
                 *
                 * This module is used through inheritance. It will make available the modifier
                 * `onlyOwner`, which can be applied to your functions to restrict their use to
                 * the owner.
                 */
                abstract contract Ownable is Context {
                    address private _owner;
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    /**
                     * @dev Initializes the contract setting the deployer as the initial owner.
                     */
                    constructor() {
                        _transferOwnership(_msgSender());
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        _checkOwner();
                        _;
                    }
                    /**
                     * @dev Returns the address of the current owner.
                     */
                    function owner() public view virtual returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if the sender is not the owner.
                     */
                    function _checkOwner() internal view virtual {
                        require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    }
                    /**
                     * @dev Leaves the contract without owner. It will not be possible to call
                     * `onlyOwner` functions. Can only be called by the current owner.
                     *
                     * NOTE: Renouncing ownership will leave the contract without an owner,
                     * thereby disabling any functionality that is only available to the owner.
                     */
                    function renounceOwnership() public virtual onlyOwner {
                        _transferOwnership(address(0));
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Can only be called by the current owner.
                     */
                    function transferOwnership(address newOwner) public virtual onlyOwner {
                        require(newOwner != address(0), "Ownable: new owner is the zero address");
                        _transferOwnership(newOwner);
                    }
                    /**
                     * @dev Transfers ownership of the contract to a new account (`newOwner`).
                     * Internal function without access restriction.
                     */
                    function _transferOwnership(address newOwner) internal virtual {
                        address oldOwner = _owner;
                        _owner = newOwner;
                        emit OwnershipTransferred(oldOwner, newOwner);
                    }
                }
                // SPDX-License-Identifier: MIT OR Apache-2.0
                pragma solidity >=0.7.6;
                library ExcessivelySafeCall {
                    uint256 constant LOW_28_MASK =
                    0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                    /// @notice Use when you _really_ really _really_ don't trust the called
                    /// contract. This prevents the called contract from causing reversion of
                    /// the caller in as many ways as we can.
                    /// @dev The main difference between this and a solidity low-level call is
                    /// that we limit the number of bytes that the callee can cause to be
                    /// copied to caller memory. This prevents stupid things like malicious
                    /// contracts returning 10,000,000 bytes causing a local OOG when copying
                    /// to memory.
                    /// @param _target The address to call
                    /// @param _gas The amount of gas to forward to the remote contract
                    /// @param _maxCopy The maximum number of bytes of returndata to copy
                    /// to memory.
                    /// @param _calldata The data to send to the remote contract
                    /// @return success and returndata, as `.call()`. Returndata is capped to
                    /// `_maxCopy` bytes.
                    function excessivelySafeCall(
                        address _target,
                        uint256 _gas,
                        uint16 _maxCopy,
                        bytes memory _calldata
                    ) internal returns (bool, bytes memory) {
                        // set up for assembly call
                        uint256 _toCopy;
                        bool _success;
                        bytes memory _returnData = new bytes(_maxCopy);
                        // dispatch message to recipient
                        // by assembly calling "handle" function
                        // we call via assembly to avoid memcopying a very large returndata
                        // returned by a malicious contract
                        assembly {
                            _success := call(
                            _gas, // gas
                            _target, // recipient
                            0, // ether value
                            add(_calldata, 0x20), // inloc
                            mload(_calldata), // inlen
                            0, // outloc
                            0 // outlen
                            )
                        // limit our copy to 256 bytes
                            _toCopy := returndatasize()
                            if gt(_toCopy, _maxCopy) {
                                _toCopy := _maxCopy
                            }
                        // Store the length of the copied bytes
                            mstore(_returnData, _toCopy)
                        // copy the bytes from returndata[0:_toCopy]
                            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                        }
                        return (_success, _returnData);
                    }
                    /// @notice Use when you _really_ really _really_ don't trust the called
                    /// contract. This prevents the called contract from causing reversion of
                    /// the caller in as many ways as we can.
                    /// @dev The main difference between this and a solidity low-level call is
                    /// that we limit the number of bytes that the callee can cause to be
                    /// copied to caller memory. This prevents stupid things like malicious
                    /// contracts returning 10,000,000 bytes causing a local OOG when copying
                    /// to memory.
                    /// @param _target The address to call
                    /// @param _gas The amount of gas to forward to the remote contract
                    /// @param _maxCopy The maximum number of bytes of returndata to copy
                    /// to memory.
                    /// @param _calldata The data to send to the remote contract
                    /// @return success and returndata, as `.call()`. Returndata is capped to
                    /// `_maxCopy` bytes.
                    function excessivelySafeStaticCall(
                        address _target,
                        uint256 _gas,
                        uint16 _maxCopy,
                        bytes memory _calldata
                    ) internal view returns (bool, bytes memory) {
                        // set up for assembly call
                        uint256 _toCopy;
                        bool _success;
                        bytes memory _returnData = new bytes(_maxCopy);
                        // dispatch message to recipient
                        // by assembly calling "handle" function
                        // we call via assembly to avoid memcopying a very large returndata
                        // returned by a malicious contract
                        assembly {
                            _success := staticcall(
                            _gas, // gas
                            _target, // recipient
                            add(_calldata, 0x20), // inloc
                            mload(_calldata), // inlen
                            0, // outloc
                            0 // outlen
                            )
                        // limit our copy to 256 bytes
                            _toCopy := returndatasize()
                            if gt(_toCopy, _maxCopy) {
                                _toCopy := _maxCopy
                            }
                        // Store the length of the copied bytes
                            mstore(_returnData, _toCopy)
                        // copy the bytes from returndata[0:_toCopy]
                            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                        }
                        return (_success, _returnData);
                    }
                    /**
                     * @notice Swaps function selectors in encoded contract calls
                     * @dev Allows reuse of encoded calldata for functions with identical
                     * argument types but different names. It simply swaps out the first 4 bytes
                     * for the new selector. This function modifies memory in place, and should
                     * only be used with caution.
                     * @param _newSelector The new 4-byte selector
                     * @param _buf The encoded contract args
                     */
                    function swapSelector(bytes4 _newSelector, bytes memory _buf)
                    internal
                    pure
                    {
                        require(_buf.length >= 4);
                        uint256 _mask = LOW_28_MASK;
                        assembly {
                        // load the first word of
                            let _word := mload(add(_buf, 0x20))
                        // mask out the top 4 bytes
                        // /x
                            _word := and(_word, _mask)
                            _word := or(_newSelector, _word)
                            mstore(add(_buf, 0x20), _word)
                        }
                    }
                }
                // SPDX-License-Identifier: Unlicense
                /*
                 * @title Solidity Bytes Arrays Utils
                 * @author Gonçalo Sá <[email protected]>
                 *
                 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
                 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
                 */
                pragma solidity >=0.8.0 <0.9.0;
                library BytesLib {
                    function concat(
                        bytes memory _preBytes,
                        bytes memory _postBytes
                    )
                    internal
                    pure
                    returns (bytes memory)
                    {
                        bytes memory tempBytes;
                        assembly {
                        // Get a location of some free memory and store it in tempBytes as
                        // Solidity does for memory variables.
                            tempBytes := mload(0x40)
                        // Store the length of the first bytes array at the beginning of
                        // the memory for tempBytes.
                            let length := mload(_preBytes)
                            mstore(tempBytes, length)
                        // Maintain a memory counter for the current write location in the
                        // temp bytes array by adding the 32 bytes for the array length to
                        // the starting location.
                            let mc := add(tempBytes, 0x20)
                        // Stop copying when the memory counter reaches the length of the
                        // first bytes array.
                            let end := add(mc, length)
                            for {
                            // Initialize a copy counter to the start of the _preBytes data,
                            // 32 bytes into its memory.
                                let cc := add(_preBytes, 0x20)
                            } lt(mc, end) {
                            // Increase both counters by 32 bytes each iteration.
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                            // Write the _preBytes data into the tempBytes memory 32 bytes
                            // at a time.
                                mstore(mc, mload(cc))
                            }
                        // Add the length of _postBytes to the current length of tempBytes
                        // and store it as the new length in the first 32 bytes of the
                        // tempBytes memory.
                            length := mload(_postBytes)
                            mstore(tempBytes, add(length, mload(tempBytes)))
                        // Move the memory counter back from a multiple of 0x20 to the
                        // actual end of the _preBytes data.
                            mc := end
                        // Stop copying when the memory counter reaches the new combined
                        // length of the arrays.
                            end := add(mc, length)
                            for {
                                let cc := add(_postBytes, 0x20)
                            } lt(mc, end) {
                                mc := add(mc, 0x20)
                                cc := add(cc, 0x20)
                            } {
                                mstore(mc, mload(cc))
                            }
                        // Update the free-memory pointer by padding our last write location
                        // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                        // next 32 byte block, then round down to the nearest multiple of
                        // 32. If the sum of the length of the two arrays is zero then add
                        // one before rounding down to leave a blank 32 bytes (the length block with 0).
                            mstore(0x40, and(
                            add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                            not(31) // Round down to the nearest 32 bytes.
                            ))
                        }
                        return tempBytes;
                    }
                    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                        assembly {
                        // Read the first 32 bytes of _preBytes storage, which is the length
                        // of the array. (We don't need to use the offset into the slot
                        // because arrays use the entire slot.)
                            let fslot := sload(_preBytes.slot)
                        // Arrays of 31 bytes or less have an even value in their slot,
                        // while longer arrays have an odd value. The actual length is
                        // the slot divided by two for odd values, and the lowest order
                        // byte divided by two for even values.
                        // If the slot is even, bitwise and the slot with 255 and divide by
                        // two to get the length. If the slot is odd, bitwise and the slot
                        // with -1 and divide by two.
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                            let newlength := add(slength, mlength)
                        // slength can contain both the length and contents of the array
                        // if length < 32 bytes so let's prepare for that
                        // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                            switch add(lt(slength, 32), lt(newlength, 32))
                            case 2 {
                            // Since the new array still fits in the slot, we just need to
                            // update the contents of the slot.
                            // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                                sstore(
                                _preBytes.slot,
                                // all the modifications to the slot are inside this
                                // next block
                                add(
                                // we can just add to the slot contents because the
                                // bytes we want to change are the LSBs
                                fslot,
                                add(
                                mul(
                                div(
                                // load the bytes from memory
                                mload(add(_postBytes, 0x20)),
                                // zero all bytes to the right
                                exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                                ),
                                // increase length by the double of the memory
                                // bytes length
                                mul(mlength, 2)
                                )
                                )
                                )
                            }
                            case 1 {
                            // The stored value fits in the slot, but the combined value
                            // will exceed it.
                            // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                            // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                            // The contents of the _postBytes array start 32 bytes into
                            // the structure. Our first read should obtain the `submod`
                            // bytes that can fit into the unused space in the last word
                            // of the stored array. To get this, we read 32 bytes starting
                            // from `submod`, so the data we read overlaps with the array
                            // contents by `submod` bytes. Masking the lowest-order
                            // `submod` bytes allows us to add that value directly to the
                            // stored value.
                                let submod := sub(32, slength)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(
                                sc,
                                add(
                                and(
                                fslot,
                                0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                                ),
                                and(mload(mc), mask)
                                )
                                )
                                for {
                                    mc := add(mc, 0x20)
                                    sc := add(sc, 1)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                            default {
                            // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                            // Start copying to the last used word of the stored array.
                                let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                            // save new length
                                sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                            // Copy over the first `submod` bytes of the new data as in
                            // case 1 above.
                                let slengthmod := mod(slength, 32)
                                let mlengthmod := mod(mlength, 32)
                                let submod := sub(32, slengthmod)
                                let mc := add(_postBytes, submod)
                                let end := add(_postBytes, mlength)
                                let mask := sub(exp(0x100, submod), 1)
                                sstore(sc, add(sload(sc), and(mload(mc), mask)))
                                for {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } lt(mc, end) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    sstore(sc, mload(mc))
                                }
                                mask := exp(0x100, sub(mc, end))
                                sstore(sc, mul(div(mload(mc), mask), mask))
                            }
                        }
                    }
                    function slice(
                        bytes memory _bytes,
                        uint256 _start,
                        uint256 _length
                    )
                    internal
                    pure
                    returns (bytes memory)
                    {
                        require(_length + 31 >= _length, "slice_overflow");
                        require(_bytes.length >= _start + _length, "slice_outOfBounds");
                        bytes memory tempBytes;
                        assembly {
                            switch iszero(_length)
                            case 0 {
                            // Get a location of some free memory and store it in tempBytes as
                            // Solidity does for memory variables.
                                tempBytes := mload(0x40)
                            // The first word of the slice result is potentially a partial
                            // word read from the original array. To read it, we calculate
                            // the length of that partial word and start copying that many
                            // bytes into the array. The first word we copy will start with
                            // data we don't care about, but the last `lengthmod` bytes will
                            // land at the beginning of the contents of the new array. When
                            // we're done copying, we overwrite the full first word with
                            // the actual length of the slice.
                                let lengthmod := and(_length, 31)
                            // The multiplication in the next line is necessary
                            // because when slicing multiples of 32 bytes (lengthmod == 0)
                            // the following copy loop was copying the origin's length
                            // and then ending prematurely not copying everything it should.
                                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                                let end := add(mc, _length)
                                for {
                                // The multiplication in the next line has the same exact purpose
                                // as the one above.
                                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                                } lt(mc, end) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                    mstore(mc, mload(cc))
                                }
                                mstore(tempBytes, _length)
                            //update free-memory pointer
                            //allocating the array padded to 32 bytes like the compiler does now
                                mstore(0x40, and(add(mc, 31), not(31)))
                            }
                            //if we want a zero-length slice let's just return a zero-length array
                            default {
                                tempBytes := mload(0x40)
                            //zero out the 32 bytes slice we are about to return
                            //we need to do it because Solidity does not garbage collect
                                mstore(tempBytes, 0)
                                mstore(0x40, add(tempBytes, 0x20))
                            }
                        }
                        return tempBytes;
                    }
                    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
                        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
                        address tempAddress;
                        assembly {
                            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                        }
                        return tempAddress;
                    }
                    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
                        uint8 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x1), _start))
                        }
                        return tempUint;
                    }
                    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
                        uint16 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x2), _start))
                        }
                        return tempUint;
                    }
                    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
                        uint32 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x4), _start))
                        }
                        return tempUint;
                    }
                    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
                        uint64 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x8), _start))
                        }
                        return tempUint;
                    }
                    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
                        uint96 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0xc), _start))
                        }
                        return tempUint;
                    }
                    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
                        uint128 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x10), _start))
                        }
                        return tempUint;
                    }
                    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
                        uint256 tempUint;
                        assembly {
                            tempUint := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempUint;
                    }
                    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
                        bytes32 tempBytes32;
                        assembly {
                            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                        }
                        return tempBytes32;
                    }
                    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                        bool success = true;
                        assembly {
                            let length := mload(_preBytes)
                        // if lengths don't match the arrays are not equal
                            switch eq(length, mload(_postBytes))
                            case 1 {
                            // cb is a circuit breaker in the for loop since there's
                            //  no said feature for inline assembly loops
                            // cb = 1 - don't breaker
                            // cb = 0 - break
                                let cb := 1
                                let mc := add(_preBytes, 0x20)
                                let end := add(mc, length)
                                for {
                                    let cc := add(_postBytes, 0x20)
                                // the next line is the loop condition:
                                // while(uint256(mc < end) + cb == 2)
                                } eq(add(lt(mc, end), cb), 2) {
                                    mc := add(mc, 0x20)
                                    cc := add(cc, 0x20)
                                } {
                                // if any of these checks fails then arrays are not equal
                                    if iszero(eq(mload(mc), mload(cc))) {
                                    // unsuccess:
                                        success := 0
                                        cb := 0
                                    }
                                }
                            }
                            default {
                            // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                    function equalStorage(
                        bytes storage _preBytes,
                        bytes memory _postBytes
                    )
                    internal
                    view
                    returns (bool)
                    {
                        bool success = true;
                        assembly {
                        // we know _preBytes_offset is 0
                            let fslot := sload(_preBytes.slot)
                        // Decode the length of the stored array like in concatStorage().
                            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                            let mlength := mload(_postBytes)
                        // if lengths don't match the arrays are not equal
                            switch eq(slength, mlength)
                            case 1 {
                            // slength can contain both the length and contents of the array
                            // if length < 32 bytes so let's prepare for that
                            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                                if iszero(iszero(slength)) {
                                    switch lt(slength, 32)
                                    case 1 {
                                    // blank the last byte which is the length
                                        fslot := mul(div(fslot, 0x100), 0x100)
                                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                        // unsuccess:
                                            success := 0
                                        }
                                    }
                                    default {
                                    // cb is a circuit breaker in the for loop since there's
                                    //  no said feature for inline assembly loops
                                    // cb = 1 - don't breaker
                                    // cb = 0 - break
                                        let cb := 1
                                    // get the keccak hash to get the contents of the array
                                        mstore(0x0, _preBytes.slot)
                                        let sc := keccak256(0x0, 0x20)
                                        let mc := add(_postBytes, 0x20)
                                        let end := add(mc, mlength)
                                    // the next line is the loop condition:
                                    // while(uint256(mc < end) + cb == 2)
                                        for {} eq(add(lt(mc, end), cb), 2) {
                                            sc := add(sc, 1)
                                            mc := add(mc, 0x20)
                                        } {
                                            if iszero(eq(sload(sc), mload(mc))) {
                                            // unsuccess:
                                                success := 0
                                                cb := 0
                                            }
                                        }
                                    }
                                }
                            }
                            default {
                            // unsuccess:
                                success := 0
                            }
                        }
                        return success;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../OFT.sol";
                contract BasedOFT is OFT {
                    constructor(string memory _name, string memory _symbol, address _lzEndpoint) OFT(_name, _symbol, _lzEndpoint) {}
                    function circulatingSupply() public view virtual override returns (uint) {
                        unchecked {
                            return totalSupply() - balanceOf(address(this));
                        }
                    }
                    function _debitFrom(address _from, uint16, bytes memory, uint _amount) internal virtual override returns(uint) {
                        address spender = _msgSender();
                        if (_from != spender) _spendAllowance(_from, spender, _amount);
                        _transfer(_from, address(this), _amount);
                        return _amount;
                    }
                    function _creditTo(uint16, address _toAddress, uint _amount) internal virtual override returns(uint) {
                        _transfer(address(this), _toAddress, _amount);
                        return _amount;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../../lzApp/NonblockingLzApp.sol";
                import "./IOFTCore.sol";
                import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
                abstract contract OFTCore is NonblockingLzApp, ERC165, IOFTCore {
                    using BytesLib for bytes;
                    uint public constant NO_EXTRA_GAS = 0;
                    // packet type
                    uint16 public constant PT_SEND = 0;
                    bool public useCustomAdapterParams;
                    constructor(address _lzEndpoint) NonblockingLzApp(_lzEndpoint) {}
                    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
                        return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId);
                    }
                    function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) public view virtual override returns (uint nativeFee, uint zroFee) {
                        // mock the payload for sendFrom()
                        bytes memory payload = abi.encode(PT_SEND, _toAddress, _amount);
                        return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams);
                    }
                    function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {
                        _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);
                    }
                    function setUseCustomAdapterParams(bool _useCustomAdapterParams) public virtual onlyOwner {
                        useCustomAdapterParams = _useCustomAdapterParams;
                        emit SetUseCustomAdapterParams(_useCustomAdapterParams);
                    }
                    function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                        uint16 packetType;
                        assembly {
                            packetType := mload(add(_payload, 32))
                        }
                        if (packetType == PT_SEND) {
                            _sendAck(_srcChainId, _srcAddress, _nonce, _payload);
                        } else {
                            revert("OFTCore: unknown packet type");
                        }
                    }
                    function _send(address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams) internal virtual {
                        _checkAdapterParams(_dstChainId, PT_SEND, _adapterParams, NO_EXTRA_GAS);
                        uint amount = _debitFrom(_from, _dstChainId, _toAddress, _amount);
                        bytes memory lzPayload = abi.encode(PT_SEND, _toAddress, amount);
                        _lzSend(_dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value);
                        emit SendToChain(_dstChainId, _from, _toAddress, amount);
                    }
                    function _sendAck(uint16 _srcChainId, bytes memory, uint64, bytes memory _payload) internal virtual {
                        (, bytes memory toAddressBytes, uint amount) = abi.decode(_payload, (uint16, bytes, uint));
                        address to = toAddressBytes.toAddress(0);
                        amount = _creditTo(_srcChainId, to, amount);
                        emit ReceiveFromChain(_srcChainId, to, amount);
                    }
                    function _checkAdapterParams(uint16 _dstChainId, uint16 _pkType, bytes memory _adapterParams, uint _extraGas) internal virtual {
                        if (useCustomAdapterParams) {
                            _checkGasLimit(_dstChainId, _pkType, _adapterParams, _extraGas);
                        } else {
                            require(_adapterParams.length == 0, "OFTCore: _adapterParams must be empty.");
                        }
                    }
                    function _debitFrom(address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount) internal virtual returns(uint);
                    function _creditTo(uint16 _srcChainId, address _toAddress, uint _amount) internal virtual returns(uint);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
                import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
                import "./IOFT.sol";
                import "./OFTCore.sol";
                // override decimal() function is needed
                contract OFT is OFTCore, ERC20, IOFT {
                    constructor(string memory _name, string memory _symbol, address _lzEndpoint) ERC20(_name, _symbol) OFTCore(_lzEndpoint) {}
                    function supportsInterface(bytes4 interfaceId) public view virtual override(OFTCore, IERC165) returns (bool) {
                        return interfaceId == type(IOFT).interfaceId || interfaceId == type(IERC20).interfaceId || super.supportsInterface(interfaceId);
                    }
                    function token() public view virtual override returns (address) {
                        return address(this);
                    }
                    function circulatingSupply() public view virtual override returns (uint) {
                        return totalSupply();
                    }
                    function _debitFrom(address _from, uint16, bytes memory, uint _amount) internal virtual override returns(uint) {
                        address spender = _msgSender();
                        if (_from != spender) _spendAllowance(_from, spender, _amount);
                        _burn(_from, _amount);
                        return _amount;
                    }
                    function _creditTo(uint16, address _toAddress, uint _amount) internal virtual override returns(uint) {
                        _mint(_toAddress, _amount);
                        return _amount;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
                /**
                 * @dev Interface of the IOFT core standard
                 */
                interface IOFTCore is IERC165 {
                    /**
                     * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
                     * _dstChainId - L0 defined chain id to send tokens too
                     * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
                     * _amount - amount of the tokens to transfer
                     * _useZro - indicates to use zro to pay L0 fees
                     * _adapterParam - flexible bytes array to indicate messaging adapter services in L0
                     */
                    function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
                    /**
                     * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
                     * `_from` the owner of token
                     * `_dstChainId` the destination chain identifier
                     * `_toAddress` can be any size depending on the `dstChainId`.
                     * `_amount` the quantity of tokens in wei
                     * `_refundAddress` the address LayerZero refunds if too much message fee is sent
                     * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
                     * `_adapterParams` is a flexible bytes array to indicate messaging adapter services
                     */
                    function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                    /**
                     * @dev returns the circulating amount of tokens on current chain
                     */
                    function circulatingSupply() external view returns (uint);
                    /**
                     * @dev returns the address of the ERC20 token
                     */
                    function token() external view returns (address);
                    /**
                     * @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`)
                     * `_nonce` is the outbound nonce
                     */
                    event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint _amount);
                    /**
                     * @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain.
                     * `_nonce` is the inbound nonce.
                     */
                    event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint _amount);
                    event SetUseCustomAdapterParams(bool _useCustomAdapterParams);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "./IOFTCore.sol";
                import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                /**
                 * @dev Interface of the OFT standard
                 */
                interface IOFT is IOFTCore, IERC20 {
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./LzApp.sol";
                import "../util/ExcessivelySafeCall.sol";
                /*
                 * the default LayerZero messaging behaviour is blocking, i.e. any failed message will block the channel
                 * this abstract class try-catch all fail messages and store locally for future retry. hence, non-blocking
                 * NOTE: if the srcAddress is not configured properly, it will still block the message pathway from (srcChainId, srcAddress)
                 */
                abstract contract NonblockingLzApp is LzApp {
                    using ExcessivelySafeCall for address;
                    constructor(address _endpoint) LzApp(_endpoint) {}
                    mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages;
                    event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);
                    event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);
                    // overriding the virtual function in LzReceiver
                    function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                        (bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft(), 150, abi.encodeWithSelector(this.nonblockingLzReceive.selector, _srcChainId, _srcAddress, _nonce, _payload));
                        // try-catch all errors/exceptions
                        if (!success) {
                            _storeFailedMessage(_srcChainId, _srcAddress, _nonce, _payload, reason);
                        }
                    }
                    function _storeFailedMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload, bytes memory _reason) internal virtual {
                        failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
                        emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload, _reason);
                    }
                    function nonblockingLzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual {
                        // only internal transaction
                        require(_msgSender() == address(this), "NonblockingLzApp: caller must be LzApp");
                        _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                    }
                    //@notice override this function
                    function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
                    function retryMessage(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public payable virtual {
                        // assert there is message to retry
                        bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce];
                        require(payloadHash != bytes32(0), "NonblockingLzApp: no stored message");
                        require(keccak256(_payload) == payloadHash, "NonblockingLzApp: invalid payload");
                        // clear the stored message
                        failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0);
                        // execute the message. revert if it fails again
                        _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                        emit RetryMessageSuccess(_srcChainId, _srcAddress, _nonce, payloadHash);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/access/Ownable.sol";
                import "../interfaces/ILayerZeroReceiver.sol";
                import "../interfaces/ILayerZeroUserApplicationConfig.sol";
                import "../interfaces/ILayerZeroEndpoint.sol";
                import "../util/BytesLib.sol";
                /*
                 * a generic LzReceiver implementation
                 */
                abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                    using BytesLib for bytes;
                    // ua can not send payload larger than this by default, but it can be changed by the ua owner
                    uint constant public DEFAULT_PAYLOAD_SIZE_LIMIT = 10000;
                    ILayerZeroEndpoint public immutable lzEndpoint;
                    mapping(uint16 => bytes) public trustedRemoteLookup;
                    mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
                    mapping(uint16 => uint) public payloadSizeLimitLookup;
                    address public precrime;
                    event SetPrecrime(address precrime);
                    event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
                    event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
                    event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
                    constructor(address _endpoint) {
                        lzEndpoint = ILayerZeroEndpoint(_endpoint);
                    }
                    function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual override {
                        // lzReceive must be called by the endpoint for security
                        require(_msgSender() == address(lzEndpoint), "LzApp: invalid endpoint caller");
                        bytes memory trustedRemote = trustedRemoteLookup[_srcChainId];
                        // if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.
                        require(_srcAddress.length == trustedRemote.length && trustedRemote.length > 0 && keccak256(_srcAddress) == keccak256(trustedRemote), "LzApp: invalid source sending contract");
                        _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                    }
                    // abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging
                    function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
                    function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint _nativeFee) internal virtual {
                        bytes memory trustedRemote = trustedRemoteLookup[_dstChainId];
                        require(trustedRemote.length != 0, "LzApp: destination chain is not a trusted source");
                        _checkPayloadSize(_dstChainId, _payload.length);
                        lzEndpoint.send{value: _nativeFee}(_dstChainId, trustedRemote, _payload, _refundAddress, _zroPaymentAddress, _adapterParams);
                    }
                    function _checkGasLimit(uint16 _dstChainId, uint16 _type, bytes memory _adapterParams, uint _extraGas) internal view virtual {
                        uint providedGasLimit = _getGasLimit(_adapterParams);
                        uint minGasLimit = minDstGasLookup[_dstChainId][_type] + _extraGas;
                        require(minGasLimit > 0, "LzApp: minGasLimit not set");
                        require(providedGasLimit >= minGasLimit, "LzApp: gas limit is too low");
                    }
                    function _getGasLimit(bytes memory _adapterParams) internal pure virtual returns (uint gasLimit) {
                        require(_adapterParams.length >= 34, "LzApp: invalid adapterParams");
                        assembly {
                            gasLimit := mload(add(_adapterParams, 34))
                        }
                    }
                    function _checkPayloadSize(uint16 _dstChainId, uint _payloadSize) internal view virtual {
                        uint payloadSizeLimit = payloadSizeLimitLookup[_dstChainId];
                        if (payloadSizeLimit == 0) { // use default if not set
                            payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT;
                        }
                        require(_payloadSize <= payloadSizeLimit, "LzApp: payload size is too large");
                    }
                    //---------------------------UserApplication config----------------------------------------
                    function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
                        return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
                    }
                    // generic config for LayerZero user Application
                    function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override onlyOwner {
                        lzEndpoint.setConfig(_version, _chainId, _configType, _config);
                    }
                    function setSendVersion(uint16 _version) external override onlyOwner {
                        lzEndpoint.setSendVersion(_version);
                    }
                    function setReceiveVersion(uint16 _version) external override onlyOwner {
                        lzEndpoint.setReceiveVersion(_version);
                    }
                    function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                        lzEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
                    }
                    // _path = abi.encodePacked(remoteAddress, localAddress)
                    // this function set the trusted path for the cross-chain communication
                    function setTrustedRemote(uint16 _remoteChainId, bytes calldata _path) external onlyOwner {
                        trustedRemoteLookup[_remoteChainId] = _path;
                        emit SetTrustedRemote(_remoteChainId, _path);
                    }
                    function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external onlyOwner {
                        trustedRemoteLookup[_remoteChainId] = abi.encodePacked(_remoteAddress, address(this));
                        emit SetTrustedRemoteAddress(_remoteChainId, _remoteAddress);
                    }
                    function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory) {
                        bytes memory path = trustedRemoteLookup[_remoteChainId];
                        require(path.length != 0, "LzApp: no trusted path record");
                        return path.slice(0, path.length - 20); // the last 20 bytes should be address(this)
                    }
                    function setPrecrime(address _precrime) external onlyOwner {
                        precrime = _precrime;
                        emit SetPrecrime(_precrime);
                    }
                    function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint _minGas) external onlyOwner {
                        require(_minGas > 0, "LzApp: invalid minGas");
                        minDstGasLookup[_dstChainId][_packetType] = _minGas;
                        emit SetMinDstGas(_dstChainId, _packetType, _minGas);
                    }
                    // if the size is 0, it means default size limit
                    function setPayloadSizeLimit(uint16 _dstChainId, uint _size) external onlyOwner {
                        payloadSizeLimitLookup[_dstChainId] = _size;
                    }
                    //--------------------------- VIEW FUNCTION ----------------------------------------
                    function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool) {
                        bytes memory trustedSource = trustedRemoteLookup[_srcChainId];
                        return keccak256(trustedSource) == keccak256(_srcAddress);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                interface ILayerZeroUserApplicationConfig {
                    // @notice set the configuration of the LayerZero messaging library of the specified version
                    // @param _version - messaging library version
                    // @param _chainId - the chainId for the pending config change
                    // @param _configType - type of configuration. every messaging library has its own convention.
                    // @param _config - configuration in the bytes. can encode arbitrary content.
                    function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                    // @notice set the send() LayerZero messaging library version to _version
                    // @param _version - new messaging library version
                    function setSendVersion(uint16 _version) external;
                    // @notice set the lzReceive() LayerZero messaging library version to _version
                    // @param _version - new messaging library version
                    function setReceiveVersion(uint16 _version) external;
                    // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                    // @param _srcChainId - the chainId of the source chain
                    // @param _srcAddress - the contract address of the source contract at the source chain
                    function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                interface ILayerZeroReceiver {
                    // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                    // @param _srcChainId - the source endpoint identifier
                    // @param _srcAddress - the source sending contract address from the source chain
                    // @param _nonce - the ordered message nonce
                    // @param _payload - the signed payload is the UA bytes has encoded to be sent
                    function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.5.0;
                import "./ILayerZeroUserApplicationConfig.sol";
                interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                    // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                    // @param _dstChainId - the destination chain identifier
                    // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                    // @param _payload - a custom bytes payload to send to the destination contract
                    // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                    // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                    // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
                    function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                    // @notice used by the messaging library to publish verified payload
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source contract (as bytes) at the source chain
                    // @param _dstAddress - the address on destination chain
                    // @param _nonce - the unbound message ordering nonce
                    // @param _gasLimit - the gas limit for external contract execution
                    // @param _payload - verified payload to send to the destination contract
                    function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                    // @notice get the inboundNonce of a lzApp from a source chain which could be EVM or non-EVM chain
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                    // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                    // @param _srcAddress - the source chain contract address
                    function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                    // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                    // @param _dstChainId - the destination chain identifier
                    // @param _userApplication - the user app address on this EVM chain
                    // @param _payload - the custom message to send over LayerZero
                    // @param _payInZRO - if false, user app pays the protocol fee in native token
                    // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                    function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                    // @notice get this Endpoint's immutable source identifier
                    function getChainId() external view returns (uint16);
                    // @notice the interface to retry failed message on this Endpoint destination
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    // @param _payload - the payload to be retried
                    function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                    // @notice query if any STORED payload (message blocking) at the endpoint.
                    // @param _srcChainId - the source chain identifier
                    // @param _srcAddress - the source chain contract address
                    function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                    // @notice query if the _libraryAddress is valid for sending msgs.
                    // @param _userApplication - the user app address on this EVM chain
                    function getSendLibraryAddress(address _userApplication) external view returns (address);
                    // @notice query if the _libraryAddress is valid for receiving msgs.
                    // @param _userApplication - the user app address on this EVM chain
                    function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                    // @notice query if the non-reentrancy guard for send() is on
                    // @return true if the guard is on. false otherwise
                    function isSendingPayload() external view returns (bool);
                    // @notice query if the non-reentrancy guard for receive() is on
                    // @return true if the guard is on. false otherwise
                    function isReceivingPayload() external view returns (bool);
                    // @notice get the configuration of the LayerZero messaging library of the specified version
                    // @param _version - messaging library version
                    // @param _chainId - the chainId for the pending config change
                    // @param _userApplication - the contract address of the user application
                    // @param _configType - type of configuration. every messaging library has its own convention.
                    function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                    // @notice get the send() LayerZero messaging library version
                    // @param _userApplication - the contract address of the user application
                    function getSendVersion(address _userApplication) external view returns (uint16);
                    // @notice get the lzReceive() LayerZero messaging library version
                    // @param _userApplication - the contract address of the user application
                    function getReceiveVersion(address _userApplication) external view returns (uint16);
                }
                

                File 3 of 9: AssetsVault
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                contract AssetsVault {
                    address public stoneVault;
                    address public strategyController;
                    modifier onlyPermit() {
                        require(
                            stoneVault == msg.sender || strategyController == msg.sender,
                            "not permit"
                        );
                        _;
                    }
                    constructor(address _stoneVault, address _strategyController) {
                        require(
                            _stoneVault != address(0) && _strategyController != address(0),
                            "ZERO ADDRESS"
                        );
                        stoneVault = _stoneVault;
                        strategyController = _strategyController;
                    }
                    function deposit() external payable {
                        require(msg.value != 0, "too small");
                    }
                    function withdraw(address _to, uint256 _amount) external onlyPermit {
                        TransferHelper.safeTransferETH(_to, _amount);
                    }
                    function setNewVault(address _vault) external onlyPermit {
                        stoneVault = _vault;
                    }
                    function getBalance() external view returns (uint256 amount) {
                        amount = address(this).balance;
                    }
                    receive() external payable {}
                }// SPDX-License-Identifier: GPL-2.0-or-later
                pragma solidity >=0.6.0;
                import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                library TransferHelper {
                    /// @notice Transfers tokens from the targeted address to the given destination
                    /// @notice Errors with 'STF' if transfer fails
                    /// @param token The contract address of the token to be transferred
                    /// @param from The originating address from which the tokens will be transferred
                    /// @param to The destination address of the transfer
                    /// @param value The amount to be transferred
                    function safeTransferFrom(
                        address token,
                        address from,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) =
                            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
                    }
                    /// @notice Transfers tokens from msg.sender to a recipient
                    /// @dev Errors with ST if transfer fails
                    /// @param token The contract address of the token which will be transferred
                    /// @param to The recipient of the transfer
                    /// @param value The value of the transfer
                    function safeTransfer(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
                    }
                    /// @notice Approves the stipulated contract to spend the given allowance in the given token
                    /// @dev Errors with 'SA' if transfer fails
                    /// @param token The contract address of the token to be approved
                    /// @param to The target of the approval
                    /// @param value The amount of the given token the target will be allowed to spend
                    function safeApprove(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
                    }
                    /// @notice Transfers ETH to the recipient address
                    /// @dev Fails with `STE`
                    /// @param to The destination of the transfer
                    /// @param value The value to be transferred
                    function safeTransferETH(address to, uint256 value) internal {
                        (bool success, ) = to.call{value: value}(new bytes(0));
                        require(success, 'STE');
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
                pragma solidity ^0.8.20;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                    /**
                     * @dev Returns the value of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                    /**
                     * @dev Returns the value of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address to, uint256 value) external returns (bool);
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                    /**
                     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
                     * caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 value) external returns (bool);
                    /**
                     * @dev Moves a `value` amount of tokens from `from` to `to` using the
                     * allowance mechanism. `value` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address from, address to, uint256 value) external returns (bool);
                }
                

                File 4 of 9: StrategyController
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                import {Strategy} from "./Strategy.sol";
                import {AssetsVault} from "../AssetsVault.sol";
                contract StrategyController {
                    using EnumerableSet for EnumerableSet.AddressSet;
                    uint256 internal constant ONE_HUNDRED_PERCENT = 1e6;
                    address public stoneVault;
                    address payable public immutable assetsVault;
                    EnumerableSet.AddressSet private strategies;
                    mapping(address => uint256) public ratios;
                    struct StrategyDiff {
                        address strategy;
                        bool isDeposit;
                        uint256 amount;
                    }
                    modifier onlyVault() {
                        require(stoneVault == msg.sender, "not vault");
                        _;
                    }
                    constructor(
                        address payable _assetsVault,
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) {
                        require(_assetsVault != address(0), "ZERO ADDRESS");
                        uint256 length = _strategies.length;
                        for (uint256 i; i < length; i++) {
                            require(_strategies[i] != address(0), "ZERO ADDRESS");
                        }
                        stoneVault = msg.sender;
                        assetsVault = _assetsVault;
                        _initStrategies(_strategies, _ratios);
                    }
                    function onlyRebaseStrategies() external {
                        _rebase(0, 0);
                    }
                    function forceWithdraw(
                        uint256 _amount
                    ) external onlyVault returns (uint256 actualAmount) {
                        uint256 balanceBeforeRepay = address(this).balance;
                        if (balanceBeforeRepay >= _amount) {
                            _repayToVault();
                            actualAmount = balanceBeforeRepay;
                        } else {
                            actualAmount =
                                _forceWithdraw(_amount - balanceBeforeRepay) +
                                balanceBeforeRepay;
                        }
                    }
                    function setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) external onlyVault {
                        _setStrategies(_strategies, _ratios);
                    }
                    function addStrategy(address _strategy) external onlyVault {
                        require(!strategies.contains(_strategy), "already exist");
                        strategies.add(_strategy);
                    }
                    function rebaseStrategies(
                        uint256 _in,
                        uint256 _out
                    ) external payable onlyVault {
                        _rebase(_in, _out);
                    }
                    function destroyStrategy(address _strategy) external onlyVault {
                        _destoryStrategy(_strategy);
                    }
                    function _rebase(uint256 _in, uint256 _out) internal {
                        require(_in == 0 || _out == 0, "only deposit or withdraw");
                        if (_in != 0) {
                            AssetsVault(assetsVault).withdraw(address(this), _in);
                        }
                        uint256 total = getAllStrategyValidValue();
                        if (total < _out) {
                            total = 0;
                        } else {
                            total = total + _in - _out;
                        }
                        uint256 length = strategies.length();
                        StrategyDiff[] memory diffs = new StrategyDiff[](length);
                        uint256 head;
                        uint256 tail = length - 1;
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            if (ratios[strategy] == 0) {
                                _clearStrategy(strategy, true);
                                continue;
                            }
                            uint256 newPosition = (total * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            uint256 position = getStrategyValidValue(strategy);
                            if (newPosition < position) {
                                diffs[head] = StrategyDiff(
                                    strategy,
                                    false,
                                    position - newPosition
                                );
                                head++;
                            } else if (newPosition > position) {
                                diffs[tail] = StrategyDiff(
                                    strategy,
                                    true,
                                    newPosition - position
                                );
                                if (tail != 0) {
                                    tail--;
                                }
                            }
                        }
                        length = diffs.length;
                        for (uint256 i; i < length; i++) {
                            StrategyDiff memory diff = diffs[i];
                            if (diff.amount == 0) {
                                continue;
                            }
                            if (diff.isDeposit) {
                                if (address(this).balance < diff.amount) {
                                    diff.amount = address(this).balance;
                                }
                                _depositToStrategy(diff.strategy, diff.amount);
                            } else {
                                _withdrawFromStrategy(diff.strategy, diff.amount);
                            }
                        }
                        _repayToVault();
                    }
                    function _repayToVault() internal {
                        if (address(this).balance != 0) {
                            TransferHelper.safeTransferETH(assetsVault, address(this).balance);
                        }
                    }
                    function _depositToStrategy(address _strategy, uint256 _amount) internal {
                        Strategy(_strategy).deposit{value: _amount}();
                    }
                    function _withdrawFromStrategy(
                        address _strategy,
                        uint256 _amount
                    ) internal {
                        Strategy(_strategy).withdraw(_amount);
                    }
                    function _forceWithdraw(
                        uint256 _amount
                    ) internal returns (uint256 actualAmount) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            address strategy = strategies.at(i);
                            uint256 withAmount = (_amount * ratios[strategy]) /
                                ONE_HUNDRED_PERCENT;
                            if (withAmount != 0) {
                                actualAmount =
                                    Strategy(strategy).instantWithdraw(withAmount) +
                                    actualAmount;
                            }
                        }
                        _repayToVault();
                    }
                    function getStrategyValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getAllValue();
                    }
                    function getStrategyValidValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getInvestedValue();
                    }
                    function getStrategyPendingValue(
                        address _strategy
                    ) public returns (uint256 _value) {
                        return Strategy(_strategy).getPendingValue();
                    }
                    function getAllStrategiesValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyValidValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyValidValue(strategies.at(i));
                        }
                    }
                    function getAllStrategyPendingValue() public returns (uint256 _value) {
                        uint256 length = strategies.length();
                        for (uint i; i < length; i++) {
                            _value = _value + getStrategyPendingValue(strategies.at(i));
                        }
                    }
                    function getStrategies()
                        public
                        view
                        returns (address[] memory addrs, uint256[] memory portions)
                    {
                        uint256 length = strategies.length();
                        addrs = new address[](length);
                        portions = new uint256[](length);
                        for (uint256 i; i < length; i++) {
                            address addr = strategies.at(i);
                            addrs[i] = addr;
                            portions[i] = ratios[addr];
                        }
                    }
                    function _initStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        require(_strategies.length == _ratios.length, "invalid length");
                        uint256 totalRatio;
                        uint256 length = _strategies.length;
                        for (uint i; i < length; i++) {
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function _setStrategies(
                        address[] memory _strategies,
                        uint256[] memory _ratios
                    ) internal {
                        uint256 length = _strategies.length;
                        require(length == _ratios.length, "invalid length");
                        uint256 oldLength = strategies.length();
                        for (uint i; i < oldLength; i++) {
                            ratios[strategies.at(i)] = 0;
                        }
                        uint256 totalRatio;
                        for (uint i; i < length; i++) {
                            require(
                                Strategy(_strategies[i]).controller() == address(this),
                                "controller mismatch"
                            );
                            strategies.add(_strategies[i]);
                            ratios[_strategies[i]] = _ratios[i];
                            totalRatio = totalRatio + _ratios[i];
                        }
                        require(totalRatio <= ONE_HUNDRED_PERCENT, "exceed 100%");
                    }
                    function clearStrategy(address _strategy) public onlyVault {
                        _clearStrategy(_strategy, false);
                    }
                    function _clearStrategy(address _strategy, bool _isRebase) internal {
                        Strategy(_strategy).clear();
                        if (!_isRebase) {
                            _repayToVault();
                        }
                    }
                    function _destoryStrategy(address _strategy) internal {
                        require(_couldDestroyStrategy(_strategy), "still active");
                        strategies.remove(_strategy);
                        _repayToVault();
                    }
                    function _couldDestroyStrategy(
                        address _strategy
                    ) internal returns (bool status) {
                        return
                            ratios[_strategy] == 0 && Strategy(_strategy).getAllValue() < 1e4;
                    }
                    function setNewVault(address _vault) external onlyVault {
                        stoneVault = _vault;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {StrategyController} from "../strategies/StrategyController.sol";
                abstract contract Strategy {
                    address payable public immutable controller;
                    address public governance;
                    string public name;
                    modifier onlyGovernance() {
                        require(governance == msg.sender, "not governace");
                        _;
                    }
                    event TransferGovernance(address oldOwner, address newOwner);
                    constructor(address payable _controller, string memory _name) {
                        require(_controller != address(0), "ZERO ADDRESS");
                        governance = msg.sender;
                        controller = _controller;
                        name = _name;
                    }
                    modifier onlyController() {
                        require(controller == msg.sender, "not controller");
                        _;
                    }
                    function deposit() public payable virtual onlyController {}
                    function withdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function instantWithdraw(
                        uint256 _amount
                    ) public virtual onlyController returns (uint256 actualAmount) {}
                    function clear() public virtual onlyController returns (uint256 amount) {}
                    function execPendingRequest(
                        uint256 _amount
                    ) public virtual returns (uint256 amount) {}
                    function getAllValue() public virtual returns (uint256 value) {}
                    function getPendingValue() public virtual returns (uint256 value) {}
                    function getInvestedValue() public virtual returns (uint256 value) {}
                    function checkPendingStatus()
                        public
                        virtual
                        returns (uint256 pending, uint256 executable)
                    {}
                    function setGovernance(address governance_) external onlyGovernance {
                        emit TransferGovernance(governance, governance_);
                        governance = governance_;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
                contract AssetsVault {
                    address public stoneVault;
                    address public strategyController;
                    modifier onlyPermit() {
                        require(
                            stoneVault == msg.sender || strategyController == msg.sender,
                            "not permit"
                        );
                        _;
                    }
                    constructor(address _stoneVault, address _strategyController) {
                        require(
                            _stoneVault != address(0) && _strategyController != address(0),
                            "ZERO ADDRESS"
                        );
                        stoneVault = _stoneVault;
                        strategyController = _strategyController;
                    }
                    function deposit() external payable {
                        require(msg.value != 0, "too small");
                    }
                    function withdraw(address _to, uint256 _amount) external onlyPermit {
                        TransferHelper.safeTransferETH(_to, _amount);
                    }
                    function setNewVault(address _vault) external onlyPermit {
                        stoneVault = _vault;
                    }
                    function getBalance() external view returns (uint256 amount) {
                        amount = address(this).balance;
                    }
                    receive() external payable {}
                }
                // SPDX-License-Identifier: GPL-2.0-or-later
                pragma solidity >=0.6.0;
                import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                library TransferHelper {
                    /// @notice Transfers tokens from the targeted address to the given destination
                    /// @notice Errors with 'STF' if transfer fails
                    /// @param token The contract address of the token to be transferred
                    /// @param from The originating address from which the tokens will be transferred
                    /// @param to The destination address of the transfer
                    /// @param value The amount to be transferred
                    function safeTransferFrom(
                        address token,
                        address from,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) =
                            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
                    }
                    /// @notice Transfers tokens from msg.sender to a recipient
                    /// @dev Errors with ST if transfer fails
                    /// @param token The contract address of the token which will be transferred
                    /// @param to The recipient of the transfer
                    /// @param value The value of the transfer
                    function safeTransfer(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
                    }
                    /// @notice Approves the stipulated contract to spend the given allowance in the given token
                    /// @dev Errors with 'SA' if transfer fails
                    /// @param token The contract address of the token to be approved
                    /// @param to The target of the approval
                    /// @param value The amount of the given token the target will be allowed to spend
                    function safeApprove(
                        address token,
                        address to,
                        uint256 value
                    ) internal {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
                    }
                    /// @notice Transfers ETH to the recipient address
                    /// @dev Fails with `STE`
                    /// @param to The destination of the transfer
                    /// @param value The value to be transferred
                    function safeTransferETH(address to, uint256 value) internal {
                        (bool success, ) = to.call{value: value}(new bytes(0));
                        require(success, 'STE');
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
                // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for managing
                 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                 * types.
                 *
                 * Sets have the following properties:
                 *
                 * - Elements are added, removed, and checked for existence in constant time
                 * (O(1)).
                 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                 *
                 * ```solidity
                 * contract Example {
                 *     // Add the library methods
                 *     using EnumerableSet for EnumerableSet.AddressSet;
                 *
                 *     // Declare a set state variable
                 *     EnumerableSet.AddressSet private mySet;
                 * }
                 * ```
                 *
                 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                 * and `uint256` (`UintSet`) are supported.
                 *
                 * [WARNING]
                 * ====
                 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
                 * unusable.
                 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
                 *
                 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
                 * array of EnumerableSet.
                 * ====
                 */
                library EnumerableSet {
                    // To implement this library for multiple types with as little code
                    // repetition as possible, we write it in terms of a generic Set type with
                    // bytes32 values.
                    // The Set implementation uses private functions, and user-facing
                    // implementations (such as AddressSet) are just wrappers around the
                    // underlying Set.
                    // This means that we can only create new EnumerableSets for types that fit
                    // in bytes32.
                    struct Set {
                        // Storage of set values
                        bytes32[] _values;
                        // Position of the value in the `values` array, plus 1 because index 0
                        // means a value is not in the set.
                        mapping(bytes32 => uint256) _indexes;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function _add(Set storage set, bytes32 value) private returns (bool) {
                        if (!_contains(set, value)) {
                            set._values.push(value);
                            // The value is stored at length-1, but we add 1 to all indexes
                            // and use 0 as a sentinel value
                            set._indexes[value] = set._values.length;
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function _remove(Set storage set, bytes32 value) private returns (bool) {
                        // We read and store the value's index to prevent multiple reads from the same storage slot
                        uint256 valueIndex = set._indexes[value];
                        if (valueIndex != 0) {
                            // Equivalent to contains(set, value)
                            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                            // the array, and then remove the last element (sometimes called as 'swap and pop').
                            // This modifies the order of the array, as noted in {at}.
                            uint256 toDeleteIndex = valueIndex - 1;
                            uint256 lastIndex = set._values.length - 1;
                            if (lastIndex != toDeleteIndex) {
                                bytes32 lastValue = set._values[lastIndex];
                                // Move the last value to the index where the value to delete is
                                set._values[toDeleteIndex] = lastValue;
                                // Update the index for the moved value
                                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                            }
                            // Delete the slot where the moved value was stored
                            set._values.pop();
                            // Delete the index for the deleted slot
                            delete set._indexes[value];
                            return true;
                        } else {
                            return false;
                        }
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function _contains(Set storage set, bytes32 value) private view returns (bool) {
                        return set._indexes[value] != 0;
                    }
                    /**
                     * @dev Returns the number of values on the set. O(1).
                     */
                    function _length(Set storage set) private view returns (uint256) {
                        return set._values.length;
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function _at(Set storage set, uint256 index) private view returns (bytes32) {
                        return set._values[index];
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function _values(Set storage set) private view returns (bytes32[] memory) {
                        return set._values;
                    }
                    // Bytes32Set
                    struct Bytes32Set {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _add(set._inner, value);
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                        return _remove(set._inner, value);
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                        return _contains(set._inner, value);
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(Bytes32Set storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                        return _at(set._inner, index);
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        bytes32[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // AddressSet
                    struct AddressSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(AddressSet storage set, address value) internal returns (bool) {
                        return _add(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(AddressSet storage set, address value) internal returns (bool) {
                        return _remove(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(AddressSet storage set, address value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(uint256(uint160(value))));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(AddressSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(AddressSet storage set, uint256 index) internal view returns (address) {
                        return address(uint160(uint256(_at(set._inner, index))));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(AddressSet storage set) internal view returns (address[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        address[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                    // UintSet
                    struct UintSet {
                        Set _inner;
                    }
                    /**
                     * @dev Add a value to a set. O(1).
                     *
                     * Returns true if the value was added to the set, that is if it was not
                     * already present.
                     */
                    function add(UintSet storage set, uint256 value) internal returns (bool) {
                        return _add(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Removes a value from a set. O(1).
                     *
                     * Returns true if the value was removed from the set, that is if it was
                     * present.
                     */
                    function remove(UintSet storage set, uint256 value) internal returns (bool) {
                        return _remove(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns true if the value is in the set. O(1).
                     */
                    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                        return _contains(set._inner, bytes32(value));
                    }
                    /**
                     * @dev Returns the number of values in the set. O(1).
                     */
                    function length(UintSet storage set) internal view returns (uint256) {
                        return _length(set._inner);
                    }
                    /**
                     * @dev Returns the value stored at position `index` in the set. O(1).
                     *
                     * Note that there are no guarantees on the ordering of values inside the
                     * array, and it may change when more values are added or removed.
                     *
                     * Requirements:
                     *
                     * - `index` must be strictly less than {length}.
                     */
                    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                        return uint256(_at(set._inner, index));
                    }
                    /**
                     * @dev Return the entire set in an array
                     *
                     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                     */
                    function values(UintSet storage set) internal view returns (uint256[] memory) {
                        bytes32[] memory store = _values(set._inner);
                        uint256[] memory result;
                        /// @solidity memory-safe-assembly
                        assembly {
                            result := store
                        }
                        return result;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                pragma solidity ^0.8.0;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                    /**
                     * @dev Returns the amount of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                    /**
                     * @dev Returns the amount of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * @dev Moves `amount` tokens from the caller's account to `to`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address to, uint256 amount) external returns (bool);
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 amount) external returns (bool);
                    /**
                     * @dev Moves `amount` tokens from `from` to `to` using the
                     * allowance mechanism. `amount` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address from, address to, uint256 amount) external returns (bool);
                }
                

                File 5 of 9: AppProxyUpgradeable
                // File: contracts/common/UnstructuredStorage.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                library UnstructuredStorage {
                    function getStorageBool(bytes32 position) internal view returns (bool data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageAddress(bytes32 position) internal view returns (address data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                        assembly { data := sload(position) }
                    }
                
                    function setStorageBool(bytes32 position, bool data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageAddress(bytes32 position, address data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageBytes32(bytes32 position, bytes32 data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageUint256(bytes32 position, uint256 data) internal {
                        assembly { sstore(position, data) }
                    }
                }
                
                // File: contracts/acl/IACL.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IACL {
                    function initialize(address permissionsCreator) external;
                
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                }
                
                // File: contracts/common/IVaultRecoverable.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IVaultRecoverable {
                    event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                
                    function transferToVault(address token) external;
                
                    function allowRecoverability(address token) external view returns (bool);
                    function getRecoveryVault() external view returns (address);
                }
                
                // File: contracts/kernel/IKernel.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                interface IKernelEvents {
                    event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                }
                
                
                // This should be an interface, but interfaces can't inherit yet :(
                contract IKernel is IKernelEvents, IVaultRecoverable {
                    function acl() public view returns (IACL);
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                
                    function setApp(bytes32 namespace, bytes32 appId, address app) public;
                    function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                }
                
                // File: contracts/apps/AppStorage.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract AppStorage {
                    using UnstructuredStorage for bytes32;
                
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                    bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                    */
                    bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                    bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                
                    function kernel() public view returns (IKernel) {
                        return IKernel(KERNEL_POSITION.getStorageAddress());
                    }
                
                    function appId() public view returns (bytes32) {
                        return APP_ID_POSITION.getStorageBytes32();
                    }
                
                    function setKernel(IKernel _kernel) internal {
                        KERNEL_POSITION.setStorageAddress(address(_kernel));
                    }
                
                    function setAppId(bytes32 _appId) internal {
                        APP_ID_POSITION.setStorageBytes32(_appId);
                    }
                }
                
                // File: contracts/common/IsContract.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract IsContract {
                    /*
                    * NOTE: this should NEVER be used for authentication
                    * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                    *
                    * This is only intended to be used as a sanity check that an address is actually a contract,
                    * RATHER THAN an address not being a contract.
                    */
                    function isContract(address _target) internal view returns (bool) {
                        if (_target == address(0)) {
                            return false;
                        }
                
                        uint256 size;
                        assembly { size := extcodesize(_target) }
                        return size > 0;
                    }
                }
                
                // File: contracts/lib/misc/ERCProxy.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract ERCProxy {
                    uint256 internal constant FORWARDING = 1;
                    uint256 internal constant UPGRADEABLE = 2;
                
                    function proxyType() public pure returns (uint256 proxyTypeId);
                    function implementation() public view returns (address codeAddr);
                }
                
                // File: contracts/common/DelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DelegateProxy is ERCProxy, IsContract {
                    uint256 internal constant FWD_GAS_LIMIT = 10000;
                
                    /**
                    * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                    * @param _dst Destination address to perform the delegatecall
                    * @param _calldata Calldata for the delegatecall
                    */
                    function delegatedFwd(address _dst, bytes _calldata) internal {
                        require(isContract(_dst));
                        uint256 fwdGasLimit = FWD_GAS_LIMIT;
                
                        assembly {
                            let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                            let size := returndatasize
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, size)
                
                            // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                            // if the call returned error data, forward it
                            switch result case 0 { revert(ptr, size) }
                            default { return(ptr, size) }
                        }
                    }
                }
                
                // File: contracts/common/DepositableStorage.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract DepositableStorage {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.depositableStorage.depositable")
                    bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                
                    function isDepositable() public view returns (bool) {
                        return DEPOSITABLE_POSITION.getStorageBool();
                    }
                
                    function setDepositable(bool _depositable) internal {
                        DEPOSITABLE_POSITION.setStorageBool(_depositable);
                    }
                }
                
                // File: contracts/common/DepositableDelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                    event ProxyDeposit(address sender, uint256 value);
                
                    function () external payable {
                        uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                        bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                
                        // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                        // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                        assembly {
                            // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                            // otherwise continue outside of the assembly block.
                            if lt(gas, forwardGasThreshold) {
                                // Only accept the deposit and emit an event if all of the following are true:
                                // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                    // Equivalent Solidity code for emitting the event:
                                    // emit ProxyDeposit(msg.sender, msg.value);
                
                                    let logData := mload(0x40) // free memory pointer
                                    mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                    mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                
                                    // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                    log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                
                                    stop() // Stop. Exits execution context
                                }
                
                                // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                revert(0, 0)
                            }
                        }
                
                        address target = implementation();
                        delegatedFwd(target, msg.data);
                    }
                }
                
                // File: contracts/kernel/KernelConstants.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract KernelAppIds {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                    */
                    bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                }
                
                
                contract KernelNamespaceConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                    */
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                }
                
                // File: contracts/apps/AppProxyBase.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                    /**
                    * @dev Initialize AppProxy
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                        setKernel(_kernel);
                        setAppId(_appId);
                
                        // Implicit check that kernel is actually a Kernel
                        // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                        // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                        // it.
                        address appCode = getAppBase(_appId);
                
                        // If initialize payload is provided, it will be executed
                        if (_initializePayload.length > 0) {
                            require(isContract(appCode));
                            // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                            // returns ending execution context and halts contract deployment
                            require(appCode.delegatecall(_initializePayload));
                        }
                    }
                
                    function getAppBase(bytes32 _appId) internal view returns (address) {
                        return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                    }
                }
                
                // File: contracts/apps/AppProxyUpgradeable.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract AppProxyUpgradeable is AppProxyBase {
                    /**
                    * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                        AppProxyBase(_kernel, _appId, _initializePayload)
                        public // solium-disable-line visibility-first
                    {
                        // solium-disable-previous-line no-empty-blocks
                    }
                
                    /**
                     * @dev ERC897, the address the proxy would delegate calls to
                     */
                    function implementation() public view returns (address) {
                        return getAppBase(appId());
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return UPGRADEABLE;
                    }
                }

                File 6 of 9: KernelProxy
                /**
                 *Submitted for verification at Etherscan.io on 2020-02-06
                */
                
                // File: contracts/acl/IACL.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IACL {
                    function initialize(address permissionsCreator) external;
                
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                }
                
                // File: contracts/common/IVaultRecoverable.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IVaultRecoverable {
                    event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                
                    function transferToVault(address token) external;
                
                    function allowRecoverability(address token) external view returns (bool);
                    function getRecoveryVault() external view returns (address);
                }
                
                // File: contracts/kernel/IKernel.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                interface IKernelEvents {
                    event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                }
                
                
                // This should be an interface, but interfaces can't inherit yet :(
                contract IKernel is IKernelEvents, IVaultRecoverable {
                    function acl() public view returns (IACL);
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                
                    function setApp(bytes32 namespace, bytes32 appId, address app) public;
                    function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                }
                
                // File: contracts/kernel/KernelConstants.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract KernelAppIds {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                    */
                    bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                }
                
                
                contract KernelNamespaceConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                    */
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                }
                
                // File: contracts/kernel/KernelStorage.sol
                
                pragma solidity 0.4.24;
                
                
                contract KernelStorage {
                    // namespace => app id => address
                    mapping (bytes32 => mapping (bytes32 => address)) public apps;
                    bytes32 public recoveryVaultAppId;
                }
                
                // File: contracts/acl/ACLSyntaxSugar.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract ACLSyntaxSugar {
                    function arr() internal pure returns (uint256[]) {
                        return new uint256[](0);
                    }
                
                    function arr(bytes32 _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                
                    function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                
                    function arr(address _a, address _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c);
                    }
                
                    function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c, _d);
                    }
                
                    function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), _c, _d, _e);
                    }
                
                    function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                
                    function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                
                    function arr(uint256 _a) internal pure returns (uint256[] r) {
                        r = new uint256[](1);
                        r[0] = _a;
                    }
                
                    function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                        r = new uint256[](2);
                        r[0] = _a;
                        r[1] = _b;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        r = new uint256[](3);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        r = new uint256[](4);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        r = new uint256[](5);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                        r[4] = _e;
                    }
                }
                
                
                contract ACLHelpers {
                    function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 30));
                    }
                
                    function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 31));
                    }
                
                    function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                        a = uint32(_x);
                        b = uint32(_x >> (8 * 4));
                        c = uint32(_x >> (8 * 8));
                    }
                }
                
                // File: contracts/common/ConversionHelpers.sol
                
                pragma solidity ^0.4.24;
                
                
                library ConversionHelpers {
                    string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                
                    function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                        // Force cast the uint256[] into a bytes array, by overwriting its length
                        // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 byteLength = _input.length * 32;
                        assembly {
                            output := _input
                            mstore(output, byteLength)
                        }
                    }
                
                    function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                        // Force cast the bytes array into a uint256[], by overwriting its length
                        // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 intsLength = _input.length / 32;
                        require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                
                        assembly {
                            output := _input
                            mstore(output, intsLength)
                        }
                    }
                }
                
                // File: contracts/common/IsContract.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract IsContract {
                    /*
                    * NOTE: this should NEVER be used for authentication
                    * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                    *
                    * This is only intended to be used as a sanity check that an address is actually a contract,
                    * RATHER THAN an address not being a contract.
                    */
                    function isContract(address _target) internal view returns (bool) {
                        if (_target == address(0)) {
                            return false;
                        }
                
                        uint256 size;
                        assembly { size := extcodesize(_target) }
                        return size > 0;
                    }
                }
                
                // File: contracts/common/Uint256Helpers.sol
                
                pragma solidity ^0.4.24;
                
                
                library Uint256Helpers {
                    uint256 private constant MAX_UINT64 = uint64(-1);
                
                    string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                
                    function toUint64(uint256 a) internal pure returns (uint64) {
                        require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                        return uint64(a);
                    }
                }
                
                // File: contracts/common/TimeHelpers.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract TimeHelpers {
                    using Uint256Helpers for uint256;
                
                    /**
                    * @dev Returns the current block number.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber() internal view returns (uint256) {
                        return block.number;
                    }
                
                    /**
                    * @dev Returns the current block number, converted to uint64.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber64() internal view returns (uint64) {
                        return getBlockNumber().toUint64();
                    }
                
                    /**
                    * @dev Returns the current timestamp.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp() internal view returns (uint256) {
                        return block.timestamp; // solium-disable-line security/no-block-members
                    }
                
                    /**
                    * @dev Returns the current timestamp, converted to uint64.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp64() internal view returns (uint64) {
                        return getTimestamp().toUint64();
                    }
                }
                
                // File: contracts/common/UnstructuredStorage.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                library UnstructuredStorage {
                    function getStorageBool(bytes32 position) internal view returns (bool data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageAddress(bytes32 position) internal view returns (address data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                        assembly { data := sload(position) }
                    }
                
                    function setStorageBool(bytes32 position, bool data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageAddress(bytes32 position, address data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageBytes32(bytes32 position, bytes32 data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageUint256(bytes32 position, uint256 data) internal {
                        assembly { sstore(position, data) }
                    }
                }
                
                // File: contracts/common/Initializable.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract Initializable is TimeHelpers {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.initializable.initializationBlock")
                    bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                
                    string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                    string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                
                    modifier onlyInit {
                        require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                        _;
                    }
                
                    modifier isInitialized {
                        require(hasInitialized(), ERROR_NOT_INITIALIZED);
                        _;
                    }
                
                    /**
                    * @return Block number in which the contract was initialized
                    */
                    function getInitializationBlock() public view returns (uint256) {
                        return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                    }
                
                    /**
                    * @return Whether the contract has been initialized by the time of the current block
                    */
                    function hasInitialized() public view returns (bool) {
                        uint256 initializationBlock = getInitializationBlock();
                        return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                    }
                
                    /**
                    * @dev Function to be called by top level contract after initialization has finished.
                    */
                    function initialized() internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                    }
                
                    /**
                    * @dev Function to be called by top level contract after initialization to enable the contract
                    *      at a future block number rather than immediately.
                    */
                    function initializedAt(uint256 _blockNumber) internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                    }
                }
                
                // File: contracts/common/Petrifiable.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract Petrifiable is Initializable {
                    // Use block UINT256_MAX (which should be never) as the initializable date
                    uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                
                    function isPetrified() public view returns (bool) {
                        return getInitializationBlock() == PETRIFIED_BLOCK;
                    }
                
                    /**
                    * @dev Function to be called by top level contract to prevent being initialized.
                    *      Useful for freezing base contracts when they're used behind proxies.
                    */
                    function petrify() internal onlyInit {
                        initializedAt(PETRIFIED_BLOCK);
                    }
                }
                
                // File: contracts/lib/token/ERC20.sol
                
                // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                
                pragma solidity ^0.4.24;
                
                
                /**
                 * @title ERC20 interface
                 * @dev see https://github.com/ethereum/EIPs/issues/20
                 */
                contract ERC20 {
                    function totalSupply() public view returns (uint256);
                
                    function balanceOf(address _who) public view returns (uint256);
                
                    function allowance(address _owner, address _spender)
                        public view returns (uint256);
                
                    function transfer(address _to, uint256 _value) public returns (bool);
                
                    function approve(address _spender, uint256 _value)
                        public returns (bool);
                
                    function transferFrom(address _from, address _to, uint256 _value)
                        public returns (bool);
                
                    event Transfer(
                        address indexed from,
                        address indexed to,
                        uint256 value
                    );
                
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 value
                    );
                }
                
                // File: contracts/common/EtherTokenConstant.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                // contracts where both tokens and ETH are accepted
                contract EtherTokenConstant {
                    address internal constant ETH = address(0);
                }
                
                // File: contracts/common/SafeERC20.sol
                
                // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                
                pragma solidity ^0.4.24;
                
                
                
                library SafeERC20 {
                    // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                    // https://github.com/ethereum/solidity/issues/3544
                    bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                
                    string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                    string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                
                    function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                        private
                        returns (bool)
                    {
                        bool ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                
                            let success := call(
                                gas,                  // forward all gas
                                _addr,                // address
                                0,                    // no value
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                
                            if gt(success, 0) {
                                // Check number of bytes returned from last function call
                                switch returndatasize
                
                                // No bytes returned: assume success
                                case 0 {
                                    ret := 1
                                }
                
                                // 32 bytes returned: check if non-zero
                                case 0x20 {
                                    // Only return success if returned data was true
                                    // Already have output in ptr
                                    ret := eq(mload(ptr), 1)
                                }
                
                                // Not sure what was returned: don't mark as success
                                default { }
                            }
                        }
                        return ret;
                    }
                
                    function staticInvoke(address _addr, bytes memory _calldata)
                        private
                        view
                        returns (bool, uint256)
                    {
                        bool success;
                        uint256 ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                
                            success := staticcall(
                                gas,                  // forward all gas
                                _addr,                // address
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                
                            if gt(success, 0) {
                                ret := mload(ptr)
                            }
                        }
                        return (success, ret);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferCallData = abi.encodeWithSelector(
                            TRANSFER_SELECTOR,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferCallData);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferFromCallData = abi.encodeWithSelector(
                            _token.transferFrom.selector,
                            _from,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferFromCallData);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                        bytes memory approveCallData = abi.encodeWithSelector(
                            _token.approve.selector,
                            _spender,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, approveCallData);
                    }
                
                    /**
                    * @dev Static call into ERC20.balanceOf().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                        bytes memory balanceOfCallData = abi.encodeWithSelector(
                            _token.balanceOf.selector,
                            _owner
                        );
                
                        (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                        require(success, ERROR_TOKEN_BALANCE_REVERTED);
                
                        return tokenBalance;
                    }
                
                    /**
                    * @dev Static call into ERC20.allowance().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                        bytes memory allowanceCallData = abi.encodeWithSelector(
                            _token.allowance.selector,
                            _owner,
                            _spender
                        );
                
                        (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                
                        return allowance;
                    }
                
                    /**
                    * @dev Static call into ERC20.totalSupply().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                        bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                
                        (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                
                        return totalSupply;
                    }
                }
                
                // File: contracts/common/VaultRecoverable.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                
                
                
                contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                    using SafeERC20 for ERC20;
                
                    string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                    string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                    string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                
                    /**
                     * @notice Send funds to recovery Vault. This contract should never receive funds,
                     *         but in case it does, this function allows one to recover them.
                     * @param _token Token balance to be sent to recovery vault.
                     */
                    function transferToVault(address _token) external {
                        require(allowRecoverability(_token), ERROR_DISALLOWED);
                        address vault = getRecoveryVault();
                        require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                
                        uint256 balance;
                        if (_token == ETH) {
                            balance = address(this).balance;
                            vault.transfer(balance);
                        } else {
                            ERC20 token = ERC20(_token);
                            balance = token.staticBalanceOf(this);
                            require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                        }
                
                        emit RecoverToVault(vault, _token, balance);
                    }
                
                    /**
                    * @dev By default deriving from AragonApp makes it recoverable
                    * @param token Token address that would be recovered
                    * @return bool whether the app allows the recovery
                    */
                    function allowRecoverability(address token) public view returns (bool) {
                        return true;
                    }
                
                    // Cast non-implemented interface to be public so we can use it internally
                    function getRecoveryVault() public view returns (address);
                }
                
                // File: contracts/apps/AppStorage.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract AppStorage {
                    using UnstructuredStorage for bytes32;
                
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                    bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                    */
                    bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                    bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                
                    function kernel() public view returns (IKernel) {
                        return IKernel(KERNEL_POSITION.getStorageAddress());
                    }
                
                    function appId() public view returns (bytes32) {
                        return APP_ID_POSITION.getStorageBytes32();
                    }
                
                    function setKernel(IKernel _kernel) internal {
                        KERNEL_POSITION.setStorageAddress(address(_kernel));
                    }
                
                    function setAppId(bytes32 _appId) internal {
                        APP_ID_POSITION.setStorageBytes32(_appId);
                    }
                }
                
                // File: contracts/lib/misc/ERCProxy.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract ERCProxy {
                    uint256 internal constant FORWARDING = 1;
                    uint256 internal constant UPGRADEABLE = 2;
                
                    function proxyType() public pure returns (uint256 proxyTypeId);
                    function implementation() public view returns (address codeAddr);
                }
                
                // File: contracts/common/DelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DelegateProxy is ERCProxy, IsContract {
                    uint256 internal constant FWD_GAS_LIMIT = 10000;
                
                    /**
                    * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                    * @param _dst Destination address to perform the delegatecall
                    * @param _calldata Calldata for the delegatecall
                    */
                    function delegatedFwd(address _dst, bytes _calldata) internal {
                        require(isContract(_dst));
                        uint256 fwdGasLimit = FWD_GAS_LIMIT;
                
                        assembly {
                            let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                            let size := returndatasize
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, size)
                
                            // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                            // if the call returned error data, forward it
                            switch result case 0 { revert(ptr, size) }
                            default { return(ptr, size) }
                        }
                    }
                }
                
                // File: contracts/common/DepositableStorage.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract DepositableStorage {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.depositableStorage.depositable")
                    bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                
                    function isDepositable() public view returns (bool) {
                        return DEPOSITABLE_POSITION.getStorageBool();
                    }
                
                    function setDepositable(bool _depositable) internal {
                        DEPOSITABLE_POSITION.setStorageBool(_depositable);
                    }
                }
                
                // File: contracts/common/DepositableDelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                    event ProxyDeposit(address sender, uint256 value);
                
                    function () external payable {
                        uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                        bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                
                        // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                        // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                        assembly {
                            // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                            // otherwise continue outside of the assembly block.
                            if lt(gas, forwardGasThreshold) {
                                // Only accept the deposit and emit an event if all of the following are true:
                                // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                    // Equivalent Solidity code for emitting the event:
                                    // emit ProxyDeposit(msg.sender, msg.value);
                
                                    let logData := mload(0x40) // free memory pointer
                                    mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                    mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                
                                    // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                    log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                
                                    stop() // Stop. Exits execution context
                                }
                
                                // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                revert(0, 0)
                            }
                        }
                
                        address target = implementation();
                        delegatedFwd(target, msg.data);
                    }
                }
                
                // File: contracts/apps/AppProxyBase.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                    /**
                    * @dev Initialize AppProxy
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                        setKernel(_kernel);
                        setAppId(_appId);
                
                        // Implicit check that kernel is actually a Kernel
                        // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                        // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                        // it.
                        address appCode = getAppBase(_appId);
                
                        // If initialize payload is provided, it will be executed
                        if (_initializePayload.length > 0) {
                            require(isContract(appCode));
                            // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                            // returns ending execution context and halts contract deployment
                            require(appCode.delegatecall(_initializePayload));
                        }
                    }
                
                    function getAppBase(bytes32 _appId) internal view returns (address) {
                        return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                    }
                }
                
                // File: contracts/apps/AppProxyUpgradeable.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract AppProxyUpgradeable is AppProxyBase {
                    /**
                    * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                        AppProxyBase(_kernel, _appId, _initializePayload)
                        public // solium-disable-line visibility-first
                    {
                        // solium-disable-previous-line no-empty-blocks
                    }
                
                    /**
                     * @dev ERC897, the address the proxy would delegate calls to
                     */
                    function implementation() public view returns (address) {
                        return getAppBase(appId());
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return UPGRADEABLE;
                    }
                }
                
                // File: contracts/apps/AppProxyPinned.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                contract AppProxyPinned is IsContract, AppProxyBase {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.appStorage.pinnedCode")
                    bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
                
                    /**
                    * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                        AppProxyBase(_kernel, _appId, _initializePayload)
                        public // solium-disable-line visibility-first
                    {
                        setPinnedCode(getAppBase(_appId));
                        require(isContract(pinnedCode()));
                    }
                
                    /**
                     * @dev ERC897, the address the proxy would delegate calls to
                     */
                    function implementation() public view returns (address) {
                        return pinnedCode();
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return FORWARDING;
                    }
                
                    function setPinnedCode(address _pinnedCode) internal {
                        PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
                    }
                
                    function pinnedCode() internal view returns (address) {
                        return PINNED_CODE_POSITION.getStorageAddress();
                    }
                }
                
                // File: contracts/factory/AppProxyFactory.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract AppProxyFactory {
                    event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
                
                    /**
                    * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyUpgradeable
                    */
                    function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
                        return newAppProxy(_kernel, _appId, new bytes(0));
                    }
                
                    /**
                    * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyUpgradeable
                    */
                    function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
                        AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
                        emit NewAppProxy(address(proxy), true, _appId);
                        return proxy;
                    }
                
                    /**
                    * @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyPinned
                    */
                    function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
                        return newAppProxyPinned(_kernel, _appId, new bytes(0));
                    }
                
                    /**
                    * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @param _initializePayload Proxy initialization payload
                    * @return AppProxyPinned
                    */
                    function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
                        AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
                        emit NewAppProxy(address(proxy), false, _appId);
                        return proxy;
                    }
                }
                
                // File: contracts/kernel/Kernel.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                
                
                
                
                
                
                // solium-disable-next-line max-len
                contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
                    /* Hardcoded constants to save gas
                    bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
                    */
                    bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
                
                    string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
                    string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
                    string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
                
                    /**
                    * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
                    * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
                    */
                    constructor(bool _shouldPetrify) public {
                        if (_shouldPetrify) {
                            petrify();
                        }
                    }
                
                    /**
                    * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                    * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
                    * @param _baseAcl Address of base ACL app
                    * @param _permissionsCreator Entity that will be given permission over createPermission
                    */
                    function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
                        initialized();
                
                        // Set ACL base
                        _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
                
                        // Create ACL instance and attach it as the default ACL app
                        IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
                        acl.initialize(_permissionsCreator);
                        _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
                
                        recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
                    }
                
                    /**
                    * @dev Create a new instance of an app linked to this kernel
                    * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @return AppProxy instance
                    */
                    function newAppInstance(bytes32 _appId, address _appBase)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        return newAppInstance(_appId, _appBase, new bytes(0), false);
                    }
                
                    /**
                    * @dev Create a new instance of an app linked to this kernel and set its base
                    *      implementation if it was not already set
                    * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                    * @param _setDefault Whether the app proxy app is the default one.
                    *        Useful when the Kernel needs to know of an instance of a particular app,
                    *        like Vault for escape hatch mechanism.
                    * @return AppProxy instance
                    */
                    function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                        appProxy = newAppProxy(this, _appId, _initializePayload);
                        // By calling setApp directly and not the internal functions, we make sure the params are checked
                        // and it will only succeed if sender has permissions to set something to the namespace.
                        if (_setDefault) {
                            setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                        }
                    }
                
                    /**
                    * @dev Create a new pinned instance of an app linked to this kernel
                    * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @return AppProxy instance
                    */
                    function newPinnedAppInstance(bytes32 _appId, address _appBase)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
                    }
                
                    /**
                    * @dev Create a new pinned instance of an app linked to this kernel and set
                    *      its base implementation if it was not already set
                    * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                    * @param _setDefault Whether the app proxy app is the default one.
                    *        Useful when the Kernel needs to know of an instance of a particular app,
                    *        like Vault for escape hatch mechanism.
                    * @return AppProxy instance
                    */
                    function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                        appProxy = newAppProxyPinned(this, _appId, _initializePayload);
                        // By calling setApp directly and not the internal functions, we make sure the params are checked
                        // and it will only succeed if sender has permissions to set something to the namespace.
                        if (_setDefault) {
                            setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                        }
                    }
                
                    /**
                    * @dev Set the resolving address of an app instance or base implementation
                    * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
                    * @param _namespace App namespace to use
                    * @param _appId Identifier for app
                    * @param _app Address of the app instance or base implementation
                    * @return ID of app
                    */
                    function setApp(bytes32 _namespace, bytes32 _appId, address _app)
                        public
                        auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
                    {
                        _setApp(_namespace, _appId, _app);
                    }
                
                    /**
                    * @dev Set the default vault id for the escape hatch mechanism
                    * @param _recoveryVaultAppId Identifier of the recovery vault app
                    */
                    function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
                    {
                        recoveryVaultAppId = _recoveryVaultAppId;
                    }
                
                    // External access to default app id and namespace constants to mimic default getters for constants
                    /* solium-disable function-order, mixedcase */
                    function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
                    function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
                    function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
                    function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
                    function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
                    /* solium-enable function-order, mixedcase */
                
                    /**
                    * @dev Get the address of an app instance or base implementation
                    * @param _namespace App namespace to use
                    * @param _appId Identifier for app
                    * @return Address of the app
                    */
                    function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
                        return apps[_namespace][_appId];
                    }
                
                    /**
                    * @dev Get the address of the recovery Vault instance (to recover funds)
                    * @return Address of the Vault
                    */
                    function getRecoveryVault() public view returns (address) {
                        return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
                    }
                
                    /**
                    * @dev Get the installed ACL app
                    * @return ACL app
                    */
                    function acl() public view returns (IACL) {
                        return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
                    }
                
                    /**
                    * @dev Function called by apps to check ACL on kernel or to check permission status
                    * @param _who Sender of the original call
                    * @param _where Address of the app
                    * @param _what Identifier for a group of actions in app
                    * @param _how Extra data for ACL auth
                    * @return Boolean indicating whether the ACL allows the role or not.
                    *         Always returns false if the kernel hasn't been initialized yet.
                    */
                    function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
                        IACL defaultAcl = acl();
                        return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
                            defaultAcl.hasPermission(_who, _where, _what, _how);
                    }
                
                    function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
                        require(isContract(_app), ERROR_APP_NOT_CONTRACT);
                        apps[_namespace][_appId] = _app;
                        emit SetApp(_namespace, _appId, _app);
                    }
                
                    function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
                        address app = getApp(_namespace, _appId);
                        if (app != address(0)) {
                            // The only way to set an app is if it passes the isContract check, so no need to check it again
                            require(app == _app, ERROR_INVALID_APP_CHANGE);
                        } else {
                            _setApp(_namespace, _appId, _app);
                        }
                    }
                
                    modifier auth(bytes32 _role, uint256[] memory _params) {
                        require(
                            hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
                            ERROR_AUTH_FAILED
                        );
                        _;
                    }
                }
                
                // File: contracts/kernel/KernelProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
                    /**
                    * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
                    *      can update the reference, which effectively upgrades the contract
                    * @param _kernelImpl Address of the contract used as implementation for kernel
                    */
                    constructor(IKernel _kernelImpl) public {
                        require(isContract(address(_kernelImpl)));
                        apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
                
                        // Note that emitting this event is important for verifying that a KernelProxy instance
                        // was never upgraded to a malicious Kernel logic contract over its lifespan.
                        // This starts the "chain of trust", that can be followed through later SetApp() events
                        // emitted during kernel upgrades.
                        emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return UPGRADEABLE;
                    }
                
                    /**
                    * @dev ERC897, the address the proxy would delegate calls to
                    */
                    function implementation() public view returns (address) {
                        return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
                    }
                }
                
                // File: contracts/common/Autopetrified.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract Autopetrified is Petrifiable {
                    constructor() public {
                        // Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
                        // This renders them uninitializable (and unusable without a proxy).
                        petrify();
                    }
                }
                
                // File: contracts/common/ReentrancyGuard.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract ReentrancyGuard {
                    using UnstructuredStorage for bytes32;
                
                    /* Hardcoded constants to save gas
                    bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
                    */
                    bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
                
                    string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
                
                    modifier nonReentrant() {
                        // Ensure mutex is unlocked
                        require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
                
                        // Lock mutex before function call
                        REENTRANCY_MUTEX_POSITION.setStorageBool(true);
                
                        // Perform function call
                        _;
                
                        // Unlock mutex after function call
                        REENTRANCY_MUTEX_POSITION.setStorageBool(false);
                    }
                }
                
                // File: contracts/evmscript/IEVMScriptExecutor.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IEVMScriptExecutor {
                    function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
                    function executorType() external pure returns (bytes32);
                }
                
                // File: contracts/evmscript/IEVMScriptRegistry.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract EVMScriptRegistryConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
                    */
                    bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
                }
                
                
                interface IEVMScriptRegistry {
                    function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
                    function disableScriptExecutor(uint256 executorId) external;
                
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
                }
                
                // File: contracts/evmscript/EVMScriptRunner.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                
                
                
                contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
                    string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
                    string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
                
                    /* This is manually crafted in assembly
                    string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
                    */
                
                    event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
                
                    function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                        return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
                    }
                
                    function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
                        address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
                        return IEVMScriptRegistry(registryAddr);
                    }
                
                    function runScript(bytes _script, bytes _input, address[] _blacklist)
                        internal
                        isInitialized
                        protectState
                        returns (bytes)
                    {
                        IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
                        require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
                
                        bytes4 sig = executor.execScript.selector;
                        bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
                
                        bytes memory output;
                        assembly {
                            let success := delegatecall(
                                gas,                // forward all gas
                                executor,           // address
                                add(data, 0x20),    // calldata start
                                mload(data),        // calldata length
                                0,                  // don't write output (we'll handle this ourselves)
                                0                   // don't write output
                            )
                
                            output := mload(0x40) // free mem ptr get
                
                            switch success
                            case 0 {
                                // If the call errored, forward its full error data
                                returndatacopy(output, 0, returndatasize)
                                revert(output, returndatasize)
                            }
                            default {
                                switch gt(returndatasize, 0x3f)
                                case 0 {
                                    // Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
                                    // revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
                                    // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
                                    // this memory layout
                                    mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                    mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                    mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
                                    mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
                
                                    revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                }
                                default {
                                    // Copy result
                                    //
                                    // Needs to perform an ABI decode for the expected `bytes` return type of
                                    // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
                                    //    [ position of the first dynamic length return value = 0x20 (32 bytes) ]
                                    //    [ output length (32 bytes) ]
                                    //    [ output content (N bytes) ]
                                    //
                                    // Perform the ABI decode by ignoring the first 32 bytes of the return data
                                    let copysize := sub(returndatasize, 0x20)
                                    returndatacopy(output, 0x20, copysize)
                
                                    mstore(0x40, add(output, copysize)) // free mem ptr set
                                }
                            }
                        }
                
                        emit ScriptResult(address(executor), _script, _input, output);
                
                        return output;
                    }
                
                    modifier protectState {
                        address preKernel = address(kernel());
                        bytes32 preAppId = appId();
                        _; // exec
                        require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
                        require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
                    }
                }
                
                // File: contracts/apps/AragonApp.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                
                
                
                
                
                // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
                // that they can never be initialized.
                // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
                // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
                // are included so that they are automatically usable by subclassing contracts
                contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
                    string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
                
                    modifier auth(bytes32 _role) {
                        require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
                        _;
                    }
                
                    modifier authP(bytes32 _role, uint256[] _params) {
                        require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
                        _;
                    }
                
                    /**
                    * @dev Check whether an action can be performed by a sender for a particular role on this app
                    * @param _sender Sender of the call
                    * @param _role Role on this app
                    * @param _params Permission params for the role
                    * @return Boolean indicating whether the sender has the permissions to perform the action.
                    *         Always returns false if the app hasn't been initialized yet.
                    */
                    function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
                        if (!hasInitialized()) {
                            return false;
                        }
                
                        IKernel linkedKernel = kernel();
                        if (address(linkedKernel) == address(0)) {
                            return false;
                        }
                
                        return linkedKernel.hasPermission(
                            _sender,
                            address(this),
                            _role,
                            ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
                        );
                    }
                
                    /**
                    * @dev Get the recovery vault for the app
                    * @return Recovery vault address for the app
                    */
                    function getRecoveryVault() public view returns (address) {
                        // Funds recovery via a vault is only available when used with a kernel
                        return kernel().getRecoveryVault(); // if kernel is not set, it will revert
                    }
                }
                
                // File: contracts/acl/IACLOracle.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IACLOracle {
                    function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
                }
                
                // File: contracts/acl/ACL.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                
                /* solium-disable function-order */
                // Allow public initialize() to be first
                contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
                    /* Hardcoded constants to save gas
                    bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
                    */
                    bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
                
                    enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
                
                    struct Param {
                        uint8 id;
                        uint8 op;
                        uint240 value; // even though value is an uint240 it can store addresses
                        // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
                        // op and id take less than 1 byte each so it can be kept in 1 sstore
                    }
                
                    uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
                    uint8 internal constant TIMESTAMP_PARAM_ID    = 201;
                    // 202 is unused
                    uint8 internal constant ORACLE_PARAM_ID       = 203;
                    uint8 internal constant LOGIC_OP_PARAM_ID     = 204;
                    uint8 internal constant PARAM_VALUE_PARAM_ID  = 205;
                    // TODO: Add execution times param type?
                
                    /* Hardcoded constant to save gas
                    bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
                    */
                    bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
                    bytes32 public constant NO_PERMISSION = bytes32(0);
                    address public constant ANY_ENTITY = address(-1);
                    address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
                
                    string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
                    string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
                    string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
                
                    // Whether someone has a permission
                    mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
                    mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
                
                    // Who is the manager of a permission
                    mapping (bytes32 => address) internal permissionManager;
                
                    event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
                    event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
                    event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
                
                    modifier onlyPermissionManager(address _app, bytes32 _role) {
                        require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
                        _;
                    }
                
                    modifier noPermissionManager(address _app, bytes32 _role) {
                        // only allow permission creation (or re-creation) when there is no manager
                        require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
                        _;
                    }
                
                    /**
                    * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                    * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
                    * @param _permissionsCreator Entity that will be given permission over createPermission
                    */
                    function initialize(address _permissionsCreator) public onlyInit {
                        initialized();
                        require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
                
                        _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
                    }
                
                    /**
                    * @dev Creates a permission that wasn't previously set and managed.
                    *      If a created permission is removed it is possible to reset it with createPermission.
                    *      This is the **ONLY** way to create permissions and set managers to permissions that don't
                    *      have a manager.
                    *      In terms of the ACL being initialized, this function implicitly protects all the other
                    *      state-changing external functions, as they all require the sender to be a manager.
                    * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
                    * @param _entity Address of the whitelisted entity that will be able to perform the role
                    * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                    * @param _role Identifier for the group of actions in app given access to perform
                    * @param _manager Address of the entity that will be able to grant and revoke the permission further.
                    */
                    function createPermission(address _entity, address _app, bytes32 _role, address _manager)
                        external
                        auth(CREATE_PERMISSIONS_ROLE)
                        noPermissionManager(_app, _role)
                    {
                        _createPermission(_entity, _app, _role, _manager);
                    }
                
                    /**
                    * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
                    * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
                    * @param _entity Address of the whitelisted entity that will be able to perform the role
                    * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                    * @param _role Identifier for the group of actions in app given access to perform
                    */
                    function grantPermission(address _entity, address _app, bytes32 _role)
                        external
                    {
                        grantPermissionP(_entity, _app, _role, new uint256[](0));
                    }
                
                    /**
                    * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
                    * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
                    * @param _entity Address of the whitelisted entity that will be able to perform the role
                    * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
                    * @param _role Identifier for the group of actions in app given access to perform
                    * @param _params Permission parameters
                    */
                    function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
                        public
                        onlyPermissionManager(_app, _role)
                    {
                        bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
                        _setPermission(_entity, _app, _role, paramsHash);
                    }
                
                    /**
                    * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
                    * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
                    * @param _entity Address of the whitelisted entity to revoke access from
                    * @param _app Address of the app in which the role will be revoked
                    * @param _role Identifier for the group of actions in app being revoked
                    */
                    function revokePermission(address _entity, address _app, bytes32 _role)
                        external
                        onlyPermissionManager(_app, _role)
                    {
                        _setPermission(_entity, _app, _role, NO_PERMISSION);
                    }
                
                    /**
                    * @notice Set `_newManager` as the manager of `_role` in `_app`
                    * @param _newManager Address for the new manager
                    * @param _app Address of the app in which the permission management is being transferred
                    * @param _role Identifier for the group of actions being transferred
                    */
                    function setPermissionManager(address _newManager, address _app, bytes32 _role)
                        external
                        onlyPermissionManager(_app, _role)
                    {
                        _setPermissionManager(_newManager, _app, _role);
                    }
                
                    /**
                    * @notice Remove the manager of `_role` in `_app`
                    * @param _app Address of the app in which the permission is being unmanaged
                    * @param _role Identifier for the group of actions being unmanaged
                    */
                    function removePermissionManager(address _app, bytes32 _role)
                        external
                        onlyPermissionManager(_app, _role)
                    {
                        _setPermissionManager(address(0), _app, _role);
                    }
                
                    /**
                    * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
                    * @param _app Address of the app in which the permission is being burned
                    * @param _role Identifier for the group of actions being burned
                    */
                    function createBurnedPermission(address _app, bytes32 _role)
                        external
                        auth(CREATE_PERMISSIONS_ROLE)
                        noPermissionManager(_app, _role)
                    {
                        _setPermissionManager(BURN_ENTITY, _app, _role);
                    }
                
                    /**
                    * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
                    * @param _app Address of the app in which the permission is being burned
                    * @param _role Identifier for the group of actions being burned
                    */
                    function burnPermissionManager(address _app, bytes32 _role)
                        external
                        onlyPermissionManager(_app, _role)
                    {
                        _setPermissionManager(BURN_ENTITY, _app, _role);
                    }
                
                    /**
                     * @notice Get parameters for permission array length
                     * @param _entity Address of the whitelisted entity that will be able to perform the role
                     * @param _app Address of the app
                     * @param _role Identifier for a group of actions in app
                     * @return Length of the array
                     */
                    function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
                        return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
                    }
                
                    /**
                    * @notice Get parameter for permission
                    * @param _entity Address of the whitelisted entity that will be able to perform the role
                    * @param _app Address of the app
                    * @param _role Identifier for a group of actions in app
                    * @param _index Index of parameter in the array
                    * @return Parameter (id, op, value)
                    */
                    function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
                        external
                        view
                        returns (uint8, uint8, uint240)
                    {
                        Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
                        return (param.id, param.op, param.value);
                    }
                
                    /**
                    * @dev Get manager for permission
                    * @param _app Address of the app
                    * @param _role Identifier for a group of actions in app
                    * @return address of the manager for the permission
                    */
                    function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
                        return permissionManager[roleHash(_app, _role)];
                    }
                
                    /**
                    * @dev Function called by apps to check ACL on kernel or to check permission statu
                    * @param _who Sender of the original call
                    * @param _where Address of the app
                    * @param _where Identifier for a group of actions in app
                    * @param _how Permission parameters
                    * @return boolean indicating whether the ACL allows the role or not
                    */
                    function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
                        return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
                    }
                
                    function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
                        bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
                        if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
                            return true;
                        }
                
                        bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
                        if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
                            return true;
                        }
                
                        return false;
                    }
                
                    function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
                        uint256[] memory empty = new uint256[](0);
                        return hasPermission(_who, _where, _what, empty);
                    }
                
                    function evalParams(
                        bytes32 _paramsHash,
                        address _who,
                        address _where,
                        bytes32 _what,
                        uint256[] _how
                    ) public view returns (bool)
                    {
                        if (_paramsHash == EMPTY_PARAM_HASH) {
                            return true;
                        }
                
                        return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
                    }
                
                    /**
                    * @dev Internal createPermission for access inside the kernel (on instantiation)
                    */
                    function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
                        _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
                        _setPermissionManager(_manager, _app, _role);
                    }
                
                    /**
                    * @dev Internal function called to actually save the permission
                    */
                    function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
                        permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
                        bool entityHasPermission = _paramsHash != NO_PERMISSION;
                        bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
                
                        emit SetPermission(_entity, _app, _role, entityHasPermission);
                        if (permissionHasParams) {
                            emit SetPermissionParams(_entity, _app, _role, _paramsHash);
                        }
                    }
                
                    function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
                        bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
                        Param[] storage params = permissionParams[paramHash];
                
                        if (params.length == 0) { // params not saved before
                            for (uint256 i = 0; i < _encodedParams.length; i++) {
                                uint256 encodedParam = _encodedParams[i];
                                Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
                                params.push(param);
                            }
                        }
                
                        return paramHash;
                    }
                
                    function _evalParam(
                        bytes32 _paramsHash,
                        uint32 _paramId,
                        address _who,
                        address _where,
                        bytes32 _what,
                        uint256[] _how
                    ) internal view returns (bool)
                    {
                        if (_paramId >= permissionParams[_paramsHash].length) {
                            return false; // out of bounds
                        }
                
                        Param memory param = permissionParams[_paramsHash][_paramId];
                
                        if (param.id == LOGIC_OP_PARAM_ID) {
                            return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
                        }
                
                        uint256 value;
                        uint256 comparedTo = uint256(param.value);
                
                        // get value
                        if (param.id == ORACLE_PARAM_ID) {
                            value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
                            comparedTo = 1;
                        } else if (param.id == BLOCK_NUMBER_PARAM_ID) {
                            value = getBlockNumber();
                        } else if (param.id == TIMESTAMP_PARAM_ID) {
                            value = getTimestamp();
                        } else if (param.id == PARAM_VALUE_PARAM_ID) {
                            value = uint256(param.value);
                        } else {
                            if (param.id >= _how.length) {
                                return false;
                            }
                            value = uint256(uint240(_how[param.id])); // force lost precision
                        }
                
                        if (Op(param.op) == Op.RET) {
                            return uint256(value) > 0;
                        }
                
                        return compare(value, Op(param.op), comparedTo);
                    }
                
                    function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
                        internal
                        view
                        returns (bool)
                    {
                        if (Op(_param.op) == Op.IF_ELSE) {
                            uint32 conditionParam;
                            uint32 successParam;
                            uint32 failureParam;
                
                            (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
                            bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
                
                            return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
                        }
                
                        uint32 param1;
                        uint32 param2;
                
                        (param1, param2,) = decodeParamsList(uint256(_param.value));
                        bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
                
                        if (Op(_param.op) == Op.NOT) {
                            return !r1;
                        }
                
                        if (r1 && Op(_param.op) == Op.OR) {
                            return true;
                        }
                
                        if (!r1 && Op(_param.op) == Op.AND) {
                            return false;
                        }
                
                        bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
                
                        if (Op(_param.op) == Op.XOR) {
                            return r1 != r2;
                        }
                
                        return r2; // both or and and depend on result of r2 after checks
                    }
                
                    function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
                        if (_op == Op.EQ)  return _a == _b;                              // solium-disable-line lbrace
                        if (_op == Op.NEQ) return _a != _b;                              // solium-disable-line lbrace
                        if (_op == Op.GT)  return _a > _b;                               // solium-disable-line lbrace
                        if (_op == Op.LT)  return _a < _b;                               // solium-disable-line lbrace
                        if (_op == Op.GTE) return _a >= _b;                              // solium-disable-line lbrace
                        if (_op == Op.LTE) return _a <= _b;                              // solium-disable-line lbrace
                        return false;
                    }
                
                    function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
                        bytes4 sig = _oracleAddr.canPerform.selector;
                
                        // a raw call is required so we can return false if the call reverts, rather than reverting
                        bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
                
                        bool ok;
                        assembly {
                            // send all available gas; if the oracle eats up all the gas, we will eventually revert
                            // note that we are currently guaranteed to still have some gas after the call from
                            // EIP-150's 63/64 gas forward rule
                            ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
                        }
                
                        if (!ok) {
                            return false;
                        }
                
                        uint256 size;
                        assembly { size := returndatasize }
                        if (size != 32) {
                            return false;
                        }
                
                        bool result;
                        assembly {
                            let ptr := mload(0x40)       // get next free memory ptr
                            returndatacopy(ptr, 0, size) // copy return from above `staticcall`
                            result := mload(ptr)         // read data at ptr and set it to result
                            mstore(ptr, 0)               // set pointer memory to 0 so it still is the next free ptr
                        }
                
                        return result;
                    }
                
                    /**
                    * @dev Internal function that sets management
                    */
                    function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
                        permissionManager[roleHash(_app, _role)] = _newManager;
                        emit ChangePermissionManager(_app, _role, _newManager);
                    }
                
                    function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
                        return keccak256(abi.encodePacked("ROLE", _where, _what));
                    }
                
                    function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
                        return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
                    }
                }
                
                // File: contracts/evmscript/ScriptHelpers.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                library ScriptHelpers {
                    function getSpecId(bytes _script) internal pure returns (uint32) {
                        return uint32At(_script, 0);
                    }
                
                    function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
                        assembly {
                            result := mload(add(_data, add(0x20, _location)))
                        }
                    }
                
                    function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
                        uint256 word = uint256At(_data, _location);
                
                        assembly {
                            result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
                            0x1000000000000000000000000)
                        }
                    }
                
                    function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
                        uint256 word = uint256At(_data, _location);
                
                        assembly {
                            result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
                            0x100000000000000000000000000000000000000000000000000000000)
                        }
                    }
                
                    function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
                        assembly {
                            result := add(_data, add(0x20, _location))
                        }
                    }
                
                    function toBytes(bytes4 _sig) internal pure returns (bytes) {
                        bytes memory payload = new bytes(4);
                        assembly { mstore(add(payload, 0x20), _sig) }
                        return payload;
                    }
                }
                
                // File: contracts/evmscript/EVMScriptRegistry.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                /* solium-disable function-order */
                // Allow public initialize() to be first
                contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
                    using ScriptHelpers for bytes;
                
                    /* Hardcoded constants to save gas
                    bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
                    bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
                    */
                    bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
                    // WARN: Manager can censor all votes and the like happening in an org
                    bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
                
                    uint256 internal constant SCRIPT_START_LOCATION = 4;
                
                    string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
                    string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
                    string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
                    string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
                
                    struct ExecutorEntry {
                        IEVMScriptExecutor executor;
                        bool enabled;
                    }
                
                    uint256 private executorsNextIndex;
                    mapping (uint256 => ExecutorEntry) public executors;
                
                    event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
                    event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
                
                    modifier executorExists(uint256 _executorId) {
                        require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
                        _;
                    }
                
                    /**
                    * @notice Initialize the registry
                    */
                    function initialize() public onlyInit {
                        initialized();
                        // Create empty record to begin executor IDs at 1
                        executorsNextIndex = 1;
                    }
                
                    /**
                    * @notice Add a new script executor with address `_executor` to the registry
                    * @param _executor Address of the IEVMScriptExecutor that will be added to the registry
                    * @return id Identifier of the executor in the registry
                    */
                    function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
                        uint256 executorId = executorsNextIndex++;
                        executors[executorId] = ExecutorEntry(_executor, true);
                        emit EnableExecutor(executorId, _executor);
                        return executorId;
                    }
                
                    /**
                    * @notice Disable script executor with ID `_executorId`
                    * @param _executorId Identifier of the executor in the registry
                    */
                    function disableScriptExecutor(uint256 _executorId)
                        external
                        authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
                    {
                        // Note that we don't need to check for an executor's existence in this case, as only
                        // existing executors can be enabled
                        ExecutorEntry storage executorEntry = executors[_executorId];
                        require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
                        executorEntry.enabled = false;
                        emit DisableExecutor(_executorId, executorEntry.executor);
                    }
                
                    /**
                    * @notice Enable script executor with ID `_executorId`
                    * @param _executorId Identifier of the executor in the registry
                    */
                    function enableScriptExecutor(uint256 _executorId)
                        external
                        authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
                        executorExists(_executorId)
                    {
                        ExecutorEntry storage executorEntry = executors[_executorId];
                        require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
                        executorEntry.enabled = true;
                        emit EnableExecutor(_executorId, executorEntry.executor);
                    }
                
                    /**
                    * @dev Get the script executor that can execute a particular script based on its first 4 bytes
                    * @param _script EVMScript being inspected
                    */
                    function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                        require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
                        uint256 id = _script.getSpecId();
                
                        // Note that we don't need to check for an executor's existence in this case, as only
                        // existing executors can be enabled
                        ExecutorEntry storage entry = executors[id];
                        return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
                    }
                }
                
                // File: contracts/evmscript/executors/BaseEVMScriptExecutor.sol
                
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
                    uint256 internal constant SCRIPT_START_LOCATION = 4;
                }
                
                // File: contracts/evmscript/executors/CallsScript.sol
                
                pragma solidity 0.4.24;
                
                // Inspired by https://github.com/reverendus/tx-manager
                
                
                
                
                contract CallsScript is BaseEVMScriptExecutor {
                    using ScriptHelpers for bytes;
                
                    /* Hardcoded constants to save gas
                    bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
                    */
                    bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
                
                    string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
                    string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
                
                    /* This is manually crafted in assembly
                    string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
                    */
                
                    event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
                
                    /**
                    * @notice Executes a number of call scripts
                    * @param _script [ specId (uint32) ] many calls with this structure ->
                    *    [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
                    * @param _blacklist Addresses the script cannot call to, or will revert.
                    * @return Always returns empty byte array
                    */
                    function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
                        uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
                        while (location < _script.length) {
                            // Check there's at least address + calldataLength available
                            require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
                
                            address contractAddress = _script.addressAt(location);
                            // Check address being called is not blacklist
                            for (uint256 i = 0; i < _blacklist.length; i++) {
                                require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
                            }
                
                            // logged before execution to ensure event ordering in receipt
                            // if failed entire execution is reverted regardless
                            emit LogScriptCall(msg.sender, address(this), contractAddress);
                
                            uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
                            uint256 startOffset = location + 0x14 + 0x04;
                            uint256 calldataStart = _script.locationOf(startOffset);
                
                            // compute end of script / next location
                            location = startOffset + calldataLength;
                            require(location <= _script.length, ERROR_INVALID_LENGTH);
                
                            bool success;
                            assembly {
                                success := call(
                                    sub(gas, 5000),       // forward gas left - 5000
                                    contractAddress,      // address
                                    0,                    // no value
                                    calldataStart,        // calldata start
                                    calldataLength,       // calldata length
                                    0,                    // don't write output
                                    0                     // don't write output
                                )
                
                                switch success
                                case 0 {
                                    let ptr := mload(0x40)
                
                                    switch returndatasize
                                    case 0 {
                                        // No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
                                        // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
                                        // this memory layout
                                        mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                        mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                        mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
                                        mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
                
                                        revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                    }
                                    default {
                                        // Forward the full error data
                                        returndatacopy(ptr, 0, returndatasize)
                                        revert(ptr, returndatasize)
                                    }
                                }
                                default { }
                            }
                        }
                        // No need to allocate empty bytes for the return as this can only be called via an delegatecall
                        // (due to the isInitialized modifier)
                    }
                
                    function executorType() external pure returns (bytes32) {
                        return EXECUTOR_TYPE;
                    }
                }
                
                // File: contracts/factory/EVMScriptRegistryFactory.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
                    EVMScriptRegistry public baseReg;
                    IEVMScriptExecutor public baseCallScript;
                
                    /**
                    * @notice Create a new EVMScriptRegistryFactory.
                    */
                    constructor() public {
                        baseReg = new EVMScriptRegistry();
                        baseCallScript = IEVMScriptExecutor(new CallsScript());
                    }
                
                    /**
                    * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
                    * @param _dao Kernel
                    * @return Installed EVMScriptRegistry
                    */
                    function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
                        bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
                        reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
                
                        ACL acl = ACL(_dao.acl());
                
                        acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
                
                        reg.addScriptExecutor(baseCallScript);     // spec 1 = CallsScript
                
                        // Clean up the permissions
                        acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
                        acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
                
                        return reg;
                    }
                }
                
                // File: contracts/factory/DAOFactory.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                
                contract DAOFactory {
                    IKernel public baseKernel;
                    IACL public baseACL;
                    EVMScriptRegistryFactory public regFactory;
                
                    event DeployDAO(address dao);
                    event DeployEVMScriptRegistry(address reg);
                
                    /**
                    * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
                    * @param _baseKernel Base Kernel
                    * @param _baseACL Base ACL
                    * @param _regFactory EVMScriptRegistry factory
                    */
                    constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
                        // No need to init as it cannot be killed by devops199
                        if (address(_regFactory) != address(0)) {
                            regFactory = _regFactory;
                        }
                
                        baseKernel = _baseKernel;
                        baseACL = _baseACL;
                    }
                
                    /**
                    * @notice Create a new DAO with `_root` set as the initial admin
                    * @param _root Address that will be granted control to setup DAO permissions
                    * @return Newly created DAO
                    */
                    function newDAO(address _root) public returns (Kernel) {
                        Kernel dao = Kernel(new KernelProxy(baseKernel));
                
                        if (address(regFactory) == address(0)) {
                            dao.initialize(baseACL, _root);
                        } else {
                            dao.initialize(baseACL, this);
                
                            ACL acl = ACL(dao.acl());
                            bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
                            bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
                
                            acl.grantPermission(regFactory, acl, permRole);
                
                            acl.createPermission(regFactory, dao, appManagerRole, this);
                
                            EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
                            emit DeployEVMScriptRegistry(address(reg));
                
                            // Clean up permissions
                            // First, completely reset the APP_MANAGER_ROLE
                            acl.revokePermission(regFactory, dao, appManagerRole);
                            acl.removePermissionManager(dao, appManagerRole);
                
                            // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
                            acl.revokePermission(regFactory, acl, permRole);
                            acl.revokePermission(this, acl, permRole);
                            acl.grantPermission(_root, acl, permRole);
                            acl.setPermissionManager(_root, acl, permRole);
                        }
                
                        emit DeployDAO(address(dao));
                
                        return dao;
                    }
                }

                File 7 of 9: Kernel
                // File: contracts/acl/IACL.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IACL {
                    function initialize(address permissionsCreator) external;
                
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                }
                
                // File: contracts/common/IVaultRecoverable.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                interface IVaultRecoverable {
                    event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                
                    function transferToVault(address token) external;
                
                    function allowRecoverability(address token) external view returns (bool);
                    function getRecoveryVault() external view returns (address);
                }
                
                // File: contracts/kernel/IKernel.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                interface IKernelEvents {
                    event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                }
                
                
                // This should be an interface, but interfaces can't inherit yet :(
                contract IKernel is IKernelEvents, IVaultRecoverable {
                    function acl() public view returns (IACL);
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                
                    function setApp(bytes32 namespace, bytes32 appId, address app) public;
                    function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                }
                
                // File: contracts/kernel/KernelConstants.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract KernelAppIds {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                    */
                    bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                }
                
                
                contract KernelNamespaceConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                    */
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                }
                
                // File: contracts/kernel/KernelStorage.sol
                
                pragma solidity 0.4.24;
                
                
                contract KernelStorage {
                    // namespace => app id => address
                    mapping (bytes32 => mapping (bytes32 => address)) public apps;
                    bytes32 public recoveryVaultAppId;
                }
                
                // File: contracts/acl/ACLSyntaxSugar.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract ACLSyntaxSugar {
                    function arr() internal pure returns (uint256[]) {
                        return new uint256[](0);
                    }
                
                    function arr(bytes32 _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                
                    function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                
                    function arr(address _a, address _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c);
                    }
                
                    function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c, _d);
                    }
                
                    function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                
                    function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), _c, _d, _e);
                    }
                
                    function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                
                    function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                
                    function arr(uint256 _a) internal pure returns (uint256[] r) {
                        r = new uint256[](1);
                        r[0] = _a;
                    }
                
                    function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                        r = new uint256[](2);
                        r[0] = _a;
                        r[1] = _b;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        r = new uint256[](3);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        r = new uint256[](4);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                    }
                
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        r = new uint256[](5);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                        r[4] = _e;
                    }
                }
                
                
                contract ACLHelpers {
                    function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 30));
                    }
                
                    function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 31));
                    }
                
                    function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                        a = uint32(_x);
                        b = uint32(_x >> (8 * 4));
                        c = uint32(_x >> (8 * 8));
                    }
                }
                
                // File: contracts/common/ConversionHelpers.sol
                
                pragma solidity ^0.4.24;
                
                
                library ConversionHelpers {
                    string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                
                    function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                        // Force cast the uint256[] into a bytes array, by overwriting its length
                        // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 byteLength = _input.length * 32;
                        assembly {
                            output := _input
                            mstore(output, byteLength)
                        }
                    }
                
                    function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                        // Force cast the bytes array into a uint256[], by overwriting its length
                        // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 intsLength = _input.length / 32;
                        require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                
                        assembly {
                            output := _input
                            mstore(output, intsLength)
                        }
                    }
                }
                
                // File: contracts/common/IsContract.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract IsContract {
                    /*
                    * NOTE: this should NEVER be used for authentication
                    * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                    *
                    * This is only intended to be used as a sanity check that an address is actually a contract,
                    * RATHER THAN an address not being a contract.
                    */
                    function isContract(address _target) internal view returns (bool) {
                        if (_target == address(0)) {
                            return false;
                        }
                
                        uint256 size;
                        assembly { size := extcodesize(_target) }
                        return size > 0;
                    }
                }
                
                // File: contracts/common/Uint256Helpers.sol
                
                pragma solidity ^0.4.24;
                
                
                library Uint256Helpers {
                    uint256 private constant MAX_UINT64 = uint64(-1);
                
                    string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                
                    function toUint64(uint256 a) internal pure returns (uint64) {
                        require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                        return uint64(a);
                    }
                }
                
                // File: contracts/common/TimeHelpers.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract TimeHelpers {
                    using Uint256Helpers for uint256;
                
                    /**
                    * @dev Returns the current block number.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber() internal view returns (uint256) {
                        return block.number;
                    }
                
                    /**
                    * @dev Returns the current block number, converted to uint64.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber64() internal view returns (uint64) {
                        return getBlockNumber().toUint64();
                    }
                
                    /**
                    * @dev Returns the current timestamp.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp() internal view returns (uint256) {
                        return block.timestamp; // solium-disable-line security/no-block-members
                    }
                
                    /**
                    * @dev Returns the current timestamp, converted to uint64.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp64() internal view returns (uint64) {
                        return getTimestamp().toUint64();
                    }
                }
                
                // File: contracts/common/UnstructuredStorage.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                library UnstructuredStorage {
                    function getStorageBool(bytes32 position) internal view returns (bool data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageAddress(bytes32 position) internal view returns (address data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                        assembly { data := sload(position) }
                    }
                
                    function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                        assembly { data := sload(position) }
                    }
                
                    function setStorageBool(bytes32 position, bool data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageAddress(bytes32 position, address data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageBytes32(bytes32 position, bytes32 data) internal {
                        assembly { sstore(position, data) }
                    }
                
                    function setStorageUint256(bytes32 position, uint256 data) internal {
                        assembly { sstore(position, data) }
                    }
                }
                
                // File: contracts/common/Initializable.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract Initializable is TimeHelpers {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.initializable.initializationBlock")
                    bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                
                    string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                    string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                
                    modifier onlyInit {
                        require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                        _;
                    }
                
                    modifier isInitialized {
                        require(hasInitialized(), ERROR_NOT_INITIALIZED);
                        _;
                    }
                
                    /**
                    * @return Block number in which the contract was initialized
                    */
                    function getInitializationBlock() public view returns (uint256) {
                        return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                    }
                
                    /**
                    * @return Whether the contract has been initialized by the time of the current block
                    */
                    function hasInitialized() public view returns (bool) {
                        uint256 initializationBlock = getInitializationBlock();
                        return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                    }
                
                    /**
                    * @dev Function to be called by top level contract after initialization has finished.
                    */
                    function initialized() internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                    }
                
                    /**
                    * @dev Function to be called by top level contract after initialization to enable the contract
                    *      at a future block number rather than immediately.
                    */
                    function initializedAt(uint256 _blockNumber) internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                    }
                }
                
                // File: contracts/common/Petrifiable.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                contract Petrifiable is Initializable {
                    // Use block UINT256_MAX (which should be never) as the initializable date
                    uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                
                    function isPetrified() public view returns (bool) {
                        return getInitializationBlock() == PETRIFIED_BLOCK;
                    }
                
                    /**
                    * @dev Function to be called by top level contract to prevent being initialized.
                    *      Useful for freezing base contracts when they're used behind proxies.
                    */
                    function petrify() internal onlyInit {
                        initializedAt(PETRIFIED_BLOCK);
                    }
                }
                
                // File: contracts/lib/token/ERC20.sol
                
                // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                
                pragma solidity ^0.4.24;
                
                
                /**
                 * @title ERC20 interface
                 * @dev see https://github.com/ethereum/EIPs/issues/20
                 */
                contract ERC20 {
                    function totalSupply() public view returns (uint256);
                
                    function balanceOf(address _who) public view returns (uint256);
                
                    function allowance(address _owner, address _spender)
                        public view returns (uint256);
                
                    function transfer(address _to, uint256 _value) public returns (bool);
                
                    function approve(address _spender, uint256 _value)
                        public returns (bool);
                
                    function transferFrom(address _from, address _to, uint256 _value)
                        public returns (bool);
                
                    event Transfer(
                        address indexed from,
                        address indexed to,
                        uint256 value
                    );
                
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 value
                    );
                }
                
                // File: contracts/common/EtherTokenConstant.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                // contracts where both tokens and ETH are accepted
                contract EtherTokenConstant {
                    address internal constant ETH = address(0);
                }
                
                // File: contracts/common/SafeERC20.sol
                
                // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                
                pragma solidity ^0.4.24;
                
                
                
                library SafeERC20 {
                    // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                    // https://github.com/ethereum/solidity/issues/3544
                    bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                
                    string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                    string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                
                    function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                        private
                        returns (bool)
                    {
                        bool ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                
                            let success := call(
                                gas,                  // forward all gas
                                _addr,                // address
                                0,                    // no value
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                
                            if gt(success, 0) {
                                // Check number of bytes returned from last function call
                                switch returndatasize
                
                                // No bytes returned: assume success
                                case 0 {
                                    ret := 1
                                }
                
                                // 32 bytes returned: check if non-zero
                                case 0x20 {
                                    // Only return success if returned data was true
                                    // Already have output in ptr
                                    ret := eq(mload(ptr), 1)
                                }
                
                                // Not sure what was returned: don't mark as success
                                default { }
                            }
                        }
                        return ret;
                    }
                
                    function staticInvoke(address _addr, bytes memory _calldata)
                        private
                        view
                        returns (bool, uint256)
                    {
                        bool success;
                        uint256 ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                
                            success := staticcall(
                                gas,                  // forward all gas
                                _addr,                // address
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                
                            if gt(success, 0) {
                                ret := mload(ptr)
                            }
                        }
                        return (success, ret);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferCallData = abi.encodeWithSelector(
                            TRANSFER_SELECTOR,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferCallData);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferFromCallData = abi.encodeWithSelector(
                            _token.transferFrom.selector,
                            _from,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferFromCallData);
                    }
                
                    /**
                    * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                        bytes memory approveCallData = abi.encodeWithSelector(
                            _token.approve.selector,
                            _spender,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, approveCallData);
                    }
                
                    /**
                    * @dev Static call into ERC20.balanceOf().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                        bytes memory balanceOfCallData = abi.encodeWithSelector(
                            _token.balanceOf.selector,
                            _owner
                        );
                
                        (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                        require(success, ERROR_TOKEN_BALANCE_REVERTED);
                
                        return tokenBalance;
                    }
                
                    /**
                    * @dev Static call into ERC20.allowance().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                        bytes memory allowanceCallData = abi.encodeWithSelector(
                            _token.allowance.selector,
                            _owner,
                            _spender
                        );
                
                        (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                
                        return allowance;
                    }
                
                    /**
                    * @dev Static call into ERC20.totalSupply().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                        bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                
                        (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                
                        return totalSupply;
                    }
                }
                
                // File: contracts/common/VaultRecoverable.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                
                
                
                contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                    using SafeERC20 for ERC20;
                
                    string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                    string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                    string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                
                    /**
                     * @notice Send funds to recovery Vault. This contract should never receive funds,
                     *         but in case it does, this function allows one to recover them.
                     * @param _token Token balance to be sent to recovery vault.
                     */
                    function transferToVault(address _token) external {
                        require(allowRecoverability(_token), ERROR_DISALLOWED);
                        address vault = getRecoveryVault();
                        require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                
                        uint256 balance;
                        if (_token == ETH) {
                            balance = address(this).balance;
                            vault.transfer(balance);
                        } else {
                            ERC20 token = ERC20(_token);
                            balance = token.staticBalanceOf(this);
                            require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                        }
                
                        emit RecoverToVault(vault, _token, balance);
                    }
                
                    /**
                    * @dev By default deriving from AragonApp makes it recoverable
                    * @param token Token address that would be recovered
                    * @return bool whether the app allows the recovery
                    */
                    function allowRecoverability(address token) public view returns (bool) {
                        return true;
                    }
                
                    // Cast non-implemented interface to be public so we can use it internally
                    function getRecoveryVault() public view returns (address);
                }
                
                // File: contracts/apps/AppStorage.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                
                
                contract AppStorage {
                    using UnstructuredStorage for bytes32;
                
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                    bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                    */
                    bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                    bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                
                    function kernel() public view returns (IKernel) {
                        return IKernel(KERNEL_POSITION.getStorageAddress());
                    }
                
                    function appId() public view returns (bytes32) {
                        return APP_ID_POSITION.getStorageBytes32();
                    }
                
                    function setKernel(IKernel _kernel) internal {
                        KERNEL_POSITION.setStorageAddress(address(_kernel));
                    }
                
                    function setAppId(bytes32 _appId) internal {
                        APP_ID_POSITION.setStorageBytes32(_appId);
                    }
                }
                
                // File: contracts/lib/misc/ERCProxy.sol
                
                /*
                 * SPDX-License-Identitifer:    MIT
                 */
                
                pragma solidity ^0.4.24;
                
                
                contract ERCProxy {
                    uint256 internal constant FORWARDING = 1;
                    uint256 internal constant UPGRADEABLE = 2;
                
                    function proxyType() public pure returns (uint256 proxyTypeId);
                    function implementation() public view returns (address codeAddr);
                }
                
                // File: contracts/common/DelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DelegateProxy is ERCProxy, IsContract {
                    uint256 internal constant FWD_GAS_LIMIT = 10000;
                
                    /**
                    * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
                    * @param _dst Destination address to perform the delegatecall
                    * @param _calldata Calldata for the delegatecall
                    */
                    function delegatedFwd(address _dst, bytes _calldata) internal {
                        require(isContract(_dst));
                        uint256 fwdGasLimit = FWD_GAS_LIMIT;
                
                        assembly {
                            let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
                            let size := returndatasize
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, size)
                
                            // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                            // if the call returned error data, forward it
                            switch result case 0 { revert(ptr, size) }
                            default { return(ptr, size) }
                        }
                    }
                }
                
                // File: contracts/common/DepositableStorage.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract DepositableStorage {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.depositableStorage.depositable")
                    bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
                
                    function isDepositable() public view returns (bool) {
                        return DEPOSITABLE_POSITION.getStorageBool();
                    }
                
                    function setDepositable(bool _depositable) internal {
                        DEPOSITABLE_POSITION.setStorageBool(_depositable);
                    }
                }
                
                // File: contracts/common/DepositableDelegateProxy.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
                    event ProxyDeposit(address sender, uint256 value);
                
                    function () external payable {
                        uint256 forwardGasThreshold = FWD_GAS_LIMIT;
                        bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
                
                        // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
                        // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
                        assembly {
                            // Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
                            // otherwise continue outside of the assembly block.
                            if lt(gas, forwardGasThreshold) {
                                // Only accept the deposit and emit an event if all of the following are true:
                                // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
                                if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
                                    // Equivalent Solidity code for emitting the event:
                                    // emit ProxyDeposit(msg.sender, msg.value);
                
                                    let logData := mload(0x40) // free memory pointer
                                    mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
                                    mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
                
                                    // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
                                    log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
                
                                    stop() // Stop. Exits execution context
                                }
                
                                // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
                                revert(0, 0)
                            }
                        }
                
                        address target = implementation();
                        delegatedFwd(target, msg.data);
                    }
                }
                
                // File: contracts/apps/AppProxyBase.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
                    /**
                    * @dev Initialize AppProxy
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
                        setKernel(_kernel);
                        setAppId(_appId);
                
                        // Implicit check that kernel is actually a Kernel
                        // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
                        // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
                        // it.
                        address appCode = getAppBase(_appId);
                
                        // If initialize payload is provided, it will be executed
                        if (_initializePayload.length > 0) {
                            require(isContract(appCode));
                            // Cannot make delegatecall as a delegateproxy.delegatedFwd as it
                            // returns ending execution context and halts contract deployment
                            require(appCode.delegatecall(_initializePayload));
                        }
                    }
                
                    function getAppBase(bytes32 _appId) internal view returns (address) {
                        return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
                    }
                }
                
                // File: contracts/apps/AppProxyUpgradeable.sol
                
                pragma solidity 0.4.24;
                
                
                
                contract AppProxyUpgradeable is AppProxyBase {
                    /**
                    * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                        AppProxyBase(_kernel, _appId, _initializePayload)
                        public // solium-disable-line visibility-first
                    {
                        // solium-disable-previous-line no-empty-blocks
                    }
                
                    /**
                     * @dev ERC897, the address the proxy would delegate calls to
                     */
                    function implementation() public view returns (address) {
                        return getAppBase(appId());
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return UPGRADEABLE;
                    }
                }
                
                // File: contracts/apps/AppProxyPinned.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                contract AppProxyPinned is IsContract, AppProxyBase {
                    using UnstructuredStorage for bytes32;
                
                    // keccak256("aragonOS.appStorage.pinnedCode")
                    bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
                
                    /**
                    * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
                    * @param _kernel Reference to organization kernel for the app
                    * @param _appId Identifier for app
                    * @param _initializePayload Payload for call to be made after setup to initialize
                    */
                    constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
                        AppProxyBase(_kernel, _appId, _initializePayload)
                        public // solium-disable-line visibility-first
                    {
                        setPinnedCode(getAppBase(_appId));
                        require(isContract(pinnedCode()));
                    }
                
                    /**
                     * @dev ERC897, the address the proxy would delegate calls to
                     */
                    function implementation() public view returns (address) {
                        return pinnedCode();
                    }
                
                    /**
                     * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
                     */
                    function proxyType() public pure returns (uint256 proxyTypeId) {
                        return FORWARDING;
                    }
                
                    function setPinnedCode(address _pinnedCode) internal {
                        PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
                    }
                
                    function pinnedCode() internal view returns (address) {
                        return PINNED_CODE_POSITION.getStorageAddress();
                    }
                }
                
                // File: contracts/factory/AppProxyFactory.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                contract AppProxyFactory {
                    event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
                
                    /**
                    * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyUpgradeable
                    */
                    function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
                        return newAppProxy(_kernel, _appId, new bytes(0));
                    }
                
                    /**
                    * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyUpgradeable
                    */
                    function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
                        AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
                        emit NewAppProxy(address(proxy), true, _appId);
                        return proxy;
                    }
                
                    /**
                    * @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @return AppProxyPinned
                    */
                    function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
                        return newAppProxyPinned(_kernel, _appId, new bytes(0));
                    }
                
                    /**
                    * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
                    * @param _kernel App's Kernel reference
                    * @param _appId Identifier for app
                    * @param _initializePayload Proxy initialization payload
                    * @return AppProxyPinned
                    */
                    function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
                        AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
                        emit NewAppProxy(address(proxy), false, _appId);
                        return proxy;
                    }
                }
                
                // File: contracts/kernel/Kernel.sol
                
                pragma solidity 0.4.24;
                
                
                
                
                
                
                
                
                
                
                
                
                
                // solium-disable-next-line max-len
                contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
                    /* Hardcoded constants to save gas
                    bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
                    */
                    bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
                
                    string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
                    string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
                    string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
                
                    /**
                    * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
                    * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
                    */
                    constructor(bool _shouldPetrify) public {
                        if (_shouldPetrify) {
                            petrify();
                        }
                    }
                
                    /**
                    * @dev Initialize can only be called once. It saves the block number in which it was initialized.
                    * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
                    * @param _baseAcl Address of base ACL app
                    * @param _permissionsCreator Entity that will be given permission over createPermission
                    */
                    function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
                        initialized();
                
                        // Set ACL base
                        _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
                
                        // Create ACL instance and attach it as the default ACL app
                        IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
                        acl.initialize(_permissionsCreator);
                        _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
                
                        recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
                    }
                
                    /**
                    * @dev Create a new instance of an app linked to this kernel
                    * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @return AppProxy instance
                    */
                    function newAppInstance(bytes32 _appId, address _appBase)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        return newAppInstance(_appId, _appBase, new bytes(0), false);
                    }
                
                    /**
                    * @dev Create a new instance of an app linked to this kernel and set its base
                    *      implementation if it was not already set
                    * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                    * @param _setDefault Whether the app proxy app is the default one.
                    *        Useful when the Kernel needs to know of an instance of a particular app,
                    *        like Vault for escape hatch mechanism.
                    * @return AppProxy instance
                    */
                    function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                        appProxy = newAppProxy(this, _appId, _initializePayload);
                        // By calling setApp directly and not the internal functions, we make sure the params are checked
                        // and it will only succeed if sender has permissions to set something to the namespace.
                        if (_setDefault) {
                            setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                        }
                    }
                
                    /**
                    * @dev Create a new pinned instance of an app linked to this kernel
                    * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @return AppProxy instance
                    */
                    function newPinnedAppInstance(bytes32 _appId, address _appBase)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
                    }
                
                    /**
                    * @dev Create a new pinned instance of an app linked to this kernel and set
                    *      its base implementation if it was not already set
                    * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
                    * @param _appId Identifier for app
                    * @param _appBase Address of the app's base implementation
                    * @param _initializePayload Payload for call made by the proxy during its construction to initialize
                    * @param _setDefault Whether the app proxy app is the default one.
                    *        Useful when the Kernel needs to know of an instance of a particular app,
                    *        like Vault for escape hatch mechanism.
                    * @return AppProxy instance
                    */
                    function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
                        returns (ERCProxy appProxy)
                    {
                        _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
                        appProxy = newAppProxyPinned(this, _appId, _initializePayload);
                        // By calling setApp directly and not the internal functions, we make sure the params are checked
                        // and it will only succeed if sender has permissions to set something to the namespace.
                        if (_setDefault) {
                            setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
                        }
                    }
                
                    /**
                    * @dev Set the resolving address of an app instance or base implementation
                    * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
                    * @param _namespace App namespace to use
                    * @param _appId Identifier for app
                    * @param _app Address of the app instance or base implementation
                    * @return ID of app
                    */
                    function setApp(bytes32 _namespace, bytes32 _appId, address _app)
                        public
                        auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
                    {
                        _setApp(_namespace, _appId, _app);
                    }
                
                    /**
                    * @dev Set the default vault id for the escape hatch mechanism
                    * @param _recoveryVaultAppId Identifier of the recovery vault app
                    */
                    function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
                        public
                        auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
                    {
                        recoveryVaultAppId = _recoveryVaultAppId;
                    }
                
                    // External access to default app id and namespace constants to mimic default getters for constants
                    /* solium-disable function-order, mixedcase */
                    function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
                    function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
                    function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
                    function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
                    function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
                    /* solium-enable function-order, mixedcase */
                
                    /**
                    * @dev Get the address of an app instance or base implementation
                    * @param _namespace App namespace to use
                    * @param _appId Identifier for app
                    * @return Address of the app
                    */
                    function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
                        return apps[_namespace][_appId];
                    }
                
                    /**
                    * @dev Get the address of the recovery Vault instance (to recover funds)
                    * @return Address of the Vault
                    */
                    function getRecoveryVault() public view returns (address) {
                        return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
                    }
                
                    /**
                    * @dev Get the installed ACL app
                    * @return ACL app
                    */
                    function acl() public view returns (IACL) {
                        return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
                    }
                
                    /**
                    * @dev Function called by apps to check ACL on kernel or to check permission status
                    * @param _who Sender of the original call
                    * @param _where Address of the app
                    * @param _what Identifier for a group of actions in app
                    * @param _how Extra data for ACL auth
                    * @return Boolean indicating whether the ACL allows the role or not.
                    *         Always returns false if the kernel hasn't been initialized yet.
                    */
                    function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
                        IACL defaultAcl = acl();
                        return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
                            defaultAcl.hasPermission(_who, _where, _what, _how);
                    }
                
                    function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
                        require(isContract(_app), ERROR_APP_NOT_CONTRACT);
                        apps[_namespace][_appId] = _app;
                        emit SetApp(_namespace, _appId, _app);
                    }
                
                    function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
                        address app = getApp(_namespace, _appId);
                        if (app != address(0)) {
                            // The only way to set an app is if it passes the isContract check, so no need to check it again
                            require(app == _app, ERROR_INVALID_APP_CHANGE);
                        } else {
                            _setApp(_namespace, _appId, _app);
                        }
                    }
                
                    modifier auth(bytes32 _role, uint256[] memory _params) {
                        require(
                            hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
                            ERROR_AUTH_FAILED
                        );
                        _;
                    }
                }

                File 8 of 9: Lido
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                contract ACLSyntaxSugar {
                    function arr() internal pure returns (uint256[]) {
                        return new uint256[](0);
                    }
                    function arr(bytes32 _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                    function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                    function arr(address _a) internal pure returns (uint256[] r) {
                        return arr(uint256(_a));
                    }
                    function arr(address _a, address _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                    function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c);
                    }
                    function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), _b, _c, _d);
                    }
                    function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b));
                    }
                    function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), _c, _d, _e);
                    }
                    function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                    function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
                        return arr(uint256(_a), uint256(_b), uint256(_c));
                    }
                    function arr(uint256 _a) internal pure returns (uint256[] r) {
                        r = new uint256[](1);
                        r[0] = _a;
                    }
                    function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
                        r = new uint256[](2);
                        r[0] = _a;
                        r[1] = _b;
                    }
                    function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
                        r = new uint256[](3);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                    }
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
                        r = new uint256[](4);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                    }
                    function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
                        r = new uint256[](5);
                        r[0] = _a;
                        r[1] = _b;
                        r[2] = _c;
                        r[3] = _d;
                        r[4] = _e;
                    }
                }
                contract ACLHelpers {
                    function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 30));
                    }
                    function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
                        return uint8(_x >> (8 * 31));
                    }
                    function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
                        a = uint32(_x);
                        b = uint32(_x >> (8 * 4));
                        c = uint32(_x >> (8 * 8));
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                interface IACL {
                    function initialize(address permissionsCreator) external;
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "../common/UnstructuredStorage.sol";
                import "../kernel/IKernel.sol";
                contract AppStorage {
                    using UnstructuredStorage for bytes32;
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
                    bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
                    */
                    bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
                    bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
                    function kernel() public view returns (IKernel) {
                        return IKernel(KERNEL_POSITION.getStorageAddress());
                    }
                    function appId() public view returns (bytes32) {
                        return APP_ID_POSITION.getStorageBytes32();
                    }
                    function setKernel(IKernel _kernel) internal {
                        KERNEL_POSITION.setStorageAddress(address(_kernel));
                    }
                    function setAppId(bytes32 _appId) internal {
                        APP_ID_POSITION.setStorageBytes32(_appId);
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./AppStorage.sol";
                import "../acl/ACLSyntaxSugar.sol";
                import "../common/Autopetrified.sol";
                import "../common/ConversionHelpers.sol";
                import "../common/ReentrancyGuard.sol";
                import "../common/VaultRecoverable.sol";
                import "../evmscript/EVMScriptRunner.sol";
                // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
                // that they can never be initialized.
                // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
                // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
                // are included so that they are automatically usable by subclassing contracts
                contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
                    string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
                    modifier auth(bytes32 _role) {
                        require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
                        _;
                    }
                    modifier authP(bytes32 _role, uint256[] _params) {
                        require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
                        _;
                    }
                    /**
                    * @dev Check whether an action can be performed by a sender for a particular role on this app
                    * @param _sender Sender of the call
                    * @param _role Role on this app
                    * @param _params Permission params for the role
                    * @return Boolean indicating whether the sender has the permissions to perform the action.
                    *         Always returns false if the app hasn't been initialized yet.
                    */
                    function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
                        if (!hasInitialized()) {
                            return false;
                        }
                        IKernel linkedKernel = kernel();
                        if (address(linkedKernel) == address(0)) {
                            return false;
                        }
                        return linkedKernel.hasPermission(
                            _sender,
                            address(this),
                            _role,
                            ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
                        );
                    }
                    /**
                    * @dev Get the recovery vault for the app
                    * @return Recovery vault address for the app
                    */
                    function getRecoveryVault() public view returns (address) {
                        // Funds recovery via a vault is only available when used with a kernel
                        return kernel().getRecoveryVault(); // if kernel is not set, it will revert
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./Petrifiable.sol";
                contract Autopetrified is Petrifiable {
                    constructor() public {
                        // Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
                        // This renders them uninitializable (and unusable without a proxy).
                        petrify();
                    }
                }
                pragma solidity ^0.4.24;
                library ConversionHelpers {
                    string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
                    function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
                        // Force cast the uint256[] into a bytes array, by overwriting its length
                        // Note that the bytes array doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 byteLength = _input.length * 32;
                        assembly {
                            output := _input
                            mstore(output, byteLength)
                        }
                    }
                    function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
                        // Force cast the bytes array into a uint256[], by overwriting its length
                        // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
                        // with the input and a new length. The input becomes invalid from this point forward.
                        uint256 intsLength = _input.length / 32;
                        require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
                        assembly {
                            output := _input
                            mstore(output, intsLength)
                        }
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                // aragonOS and aragon-apps rely on address(0) to denote native ETH, in
                // contracts where both tokens and ETH are accepted
                contract EtherTokenConstant {
                    address internal constant ETH = address(0);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./TimeHelpers.sol";
                import "./UnstructuredStorage.sol";
                contract Initializable is TimeHelpers {
                    using UnstructuredStorage for bytes32;
                    // keccak256("aragonOS.initializable.initializationBlock")
                    bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
                    string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
                    string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
                    modifier onlyInit {
                        require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
                        _;
                    }
                    modifier isInitialized {
                        require(hasInitialized(), ERROR_NOT_INITIALIZED);
                        _;
                    }
                    /**
                    * @return Block number in which the contract was initialized
                    */
                    function getInitializationBlock() public view returns (uint256) {
                        return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
                    }
                    /**
                    * @return Whether the contract has been initialized by the time of the current block
                    */
                    function hasInitialized() public view returns (bool) {
                        uint256 initializationBlock = getInitializationBlock();
                        return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
                    }
                    /**
                    * @dev Function to be called by top level contract after initialization has finished.
                    */
                    function initialized() internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
                    }
                    /**
                    * @dev Function to be called by top level contract after initialization to enable the contract
                    *      at a future block number rather than immediately.
                    */
                    function initializedAt(uint256 _blockNumber) internal onlyInit {
                        INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                contract IsContract {
                    /*
                    * NOTE: this should NEVER be used for authentication
                    * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
                    *
                    * This is only intended to be used as a sanity check that an address is actually a contract,
                    * RATHER THAN an address not being a contract.
                    */
                    function isContract(address _target) internal view returns (bool) {
                        if (_target == address(0)) {
                            return false;
                        }
                        uint256 size;
                        assembly { size := extcodesize(_target) }
                        return size > 0;
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                interface IVaultRecoverable {
                    event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
                    function transferToVault(address token) external;
                    function allowRecoverability(address token) external view returns (bool);
                    function getRecoveryVault() external view returns (address);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./Initializable.sol";
                contract Petrifiable is Initializable {
                    // Use block UINT256_MAX (which should be never) as the initializable date
                    uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
                    function isPetrified() public view returns (bool) {
                        return getInitializationBlock() == PETRIFIED_BLOCK;
                    }
                    /**
                    * @dev Function to be called by top level contract to prevent being initialized.
                    *      Useful for freezing base contracts when they're used behind proxies.
                    */
                    function petrify() internal onlyInit {
                        initializedAt(PETRIFIED_BLOCK);
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "../common/UnstructuredStorage.sol";
                contract ReentrancyGuard {
                    using UnstructuredStorage for bytes32;
                    /* Hardcoded constants to save gas
                    bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
                    */
                    bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
                    string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
                    modifier nonReentrant() {
                        // Ensure mutex is unlocked
                        require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
                        // Lock mutex before function call
                        REENTRANCY_MUTEX_POSITION.setStorageBool(true);
                        // Perform function call
                        _;
                        // Unlock mutex after function call
                        REENTRANCY_MUTEX_POSITION.setStorageBool(false);
                    }
                }
                // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
                // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
                pragma solidity ^0.4.24;
                import "../lib/token/ERC20.sol";
                library SafeERC20 {
                    // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
                    // https://github.com/ethereum/solidity/issues/3544
                    bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
                    string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
                    string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
                    function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
                        private
                        returns (bool)
                    {
                        bool ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                            let success := call(
                                gas,                  // forward all gas
                                _addr,                // address
                                0,                    // no value
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                            if gt(success, 0) {
                                // Check number of bytes returned from last function call
                                switch returndatasize
                                // No bytes returned: assume success
                                case 0 {
                                    ret := 1
                                }
                                // 32 bytes returned: check if non-zero
                                case 0x20 {
                                    // Only return success if returned data was true
                                    // Already have output in ptr
                                    ret := eq(mload(ptr), 1)
                                }
                                // Not sure what was returned: don't mark as success
                                default { }
                            }
                        }
                        return ret;
                    }
                    function staticInvoke(address _addr, bytes memory _calldata)
                        private
                        view
                        returns (bool, uint256)
                    {
                        bool success;
                        uint256 ret;
                        assembly {
                            let ptr := mload(0x40)    // free memory pointer
                            success := staticcall(
                                gas,                  // forward all gas
                                _addr,                // address
                                add(_calldata, 0x20), // calldata start
                                mload(_calldata),     // calldata length
                                ptr,                  // write output over free memory
                                0x20                  // uint256 return
                            )
                            if gt(success, 0) {
                                ret := mload(ptr)
                            }
                        }
                        return (success, ret);
                    }
                    /**
                    * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferCallData = abi.encodeWithSelector(
                            TRANSFER_SELECTOR,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferCallData);
                    }
                    /**
                    * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
                        bytes memory transferFromCallData = abi.encodeWithSelector(
                            _token.transferFrom.selector,
                            _from,
                            _to,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, transferFromCallData);
                    }
                    /**
                    * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
                    *      Note that this makes an external call to the token.
                    */
                    function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
                        bytes memory approveCallData = abi.encodeWithSelector(
                            _token.approve.selector,
                            _spender,
                            _amount
                        );
                        return invokeAndCheckSuccess(_token, approveCallData);
                    }
                    /**
                    * @dev Static call into ERC20.balanceOf().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
                        bytes memory balanceOfCallData = abi.encodeWithSelector(
                            _token.balanceOf.selector,
                            _owner
                        );
                        (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
                        require(success, ERROR_TOKEN_BALANCE_REVERTED);
                        return tokenBalance;
                    }
                    /**
                    * @dev Static call into ERC20.allowance().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
                        bytes memory allowanceCallData = abi.encodeWithSelector(
                            _token.allowance.selector,
                            _owner,
                            _spender
                        );
                        (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                        return allowance;
                    }
                    /**
                    * @dev Static call into ERC20.totalSupply().
                    * Reverts if the call fails for some reason (should never fail).
                    */
                    function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
                        bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
                        (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
                        require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
                        return totalSupply;
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./Uint256Helpers.sol";
                contract TimeHelpers {
                    using Uint256Helpers for uint256;
                    /**
                    * @dev Returns the current block number.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber() internal view returns (uint256) {
                        return block.number;
                    }
                    /**
                    * @dev Returns the current block number, converted to uint64.
                    *      Using a function rather than `block.number` allows us to easily mock the block number in
                    *      tests.
                    */
                    function getBlockNumber64() internal view returns (uint64) {
                        return getBlockNumber().toUint64();
                    }
                    /**
                    * @dev Returns the current timestamp.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp() internal view returns (uint256) {
                        return block.timestamp; // solium-disable-line security/no-block-members
                    }
                    /**
                    * @dev Returns the current timestamp, converted to uint64.
                    *      Using a function rather than `block.timestamp` allows us to easily mock it in
                    *      tests.
                    */
                    function getTimestamp64() internal view returns (uint64) {
                        return getTimestamp().toUint64();
                    }
                }
                pragma solidity ^0.4.24;
                library Uint256Helpers {
                    uint256 private constant MAX_UINT64 = uint64(-1);
                    string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
                    function toUint64(uint256 a) internal pure returns (uint64) {
                        require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
                        return uint64(a);
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                library UnstructuredStorage {
                    function getStorageBool(bytes32 position) internal view returns (bool data) {
                        assembly { data := sload(position) }
                    }
                    function getStorageAddress(bytes32 position) internal view returns (address data) {
                        assembly { data := sload(position) }
                    }
                    function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                        assembly { data := sload(position) }
                    }
                    function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                        assembly { data := sload(position) }
                    }
                    function setStorageBool(bytes32 position, bool data) internal {
                        assembly { sstore(position, data) }
                    }
                    function setStorageAddress(bytes32 position, address data) internal {
                        assembly { sstore(position, data) }
                    }
                    function setStorageBytes32(bytes32 position, bytes32 data) internal {
                        assembly { sstore(position, data) }
                    }
                    function setStorageUint256(bytes32 position, uint256 data) internal {
                        assembly { sstore(position, data) }
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "../lib/token/ERC20.sol";
                import "./EtherTokenConstant.sol";
                import "./IsContract.sol";
                import "./IVaultRecoverable.sol";
                import "./SafeERC20.sol";
                contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
                    using SafeERC20 for ERC20;
                    string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
                    string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
                    string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
                    /**
                     * @notice Send funds to recovery Vault. This contract should never receive funds,
                     *         but in case it does, this function allows one to recover them.
                     * @param _token Token balance to be sent to recovery vault.
                     */
                    function transferToVault(address _token) external {
                        require(allowRecoverability(_token), ERROR_DISALLOWED);
                        address vault = getRecoveryVault();
                        require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
                        uint256 balance;
                        if (_token == ETH) {
                            balance = address(this).balance;
                            vault.transfer(balance);
                        } else {
                            ERC20 token = ERC20(_token);
                            balance = token.staticBalanceOf(this);
                            require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
                        }
                        emit RecoverToVault(vault, _token, balance);
                    }
                    /**
                    * @dev By default deriving from AragonApp makes it recoverable
                    * @param token Token address that would be recovered
                    * @return bool whether the app allows the recovery
                    */
                    function allowRecoverability(address token) public view returns (bool) {
                        return true;
                    }
                    // Cast non-implemented interface to be public so we can use it internally
                    function getRecoveryVault() public view returns (address);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./IEVMScriptExecutor.sol";
                import "./IEVMScriptRegistry.sol";
                import "../apps/AppStorage.sol";
                import "../kernel/KernelConstants.sol";
                import "../common/Initializable.sol";
                contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
                    string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
                    string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
                    /* This is manually crafted in assembly
                    string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
                    */
                    event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
                    function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
                        return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
                    }
                    function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
                        address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
                        return IEVMScriptRegistry(registryAddr);
                    }
                    function runScript(bytes _script, bytes _input, address[] _blacklist)
                        internal
                        isInitialized
                        protectState
                        returns (bytes)
                    {
                        IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
                        require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
                        bytes4 sig = executor.execScript.selector;
                        bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
                        bytes memory output;
                        assembly {
                            let success := delegatecall(
                                gas,                // forward all gas
                                executor,           // address
                                add(data, 0x20),    // calldata start
                                mload(data),        // calldata length
                                0,                  // don't write output (we'll handle this ourselves)
                                0                   // don't write output
                            )
                            output := mload(0x40) // free mem ptr get
                            switch success
                            case 0 {
                                // If the call errored, forward its full error data
                                returndatacopy(output, 0, returndatasize)
                                revert(output, returndatasize)
                            }
                            default {
                                switch gt(returndatasize, 0x3f)
                                case 0 {
                                    // Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
                                    // revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
                                    // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
                                    // this memory layout
                                    mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000)         // error identifier
                                    mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
                                    mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
                                    mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
                                    revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
                                }
                                default {
                                    // Copy result
                                    //
                                    // Needs to perform an ABI decode for the expected `bytes` return type of
                                    // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
                                    //    [ position of the first dynamic length return value = 0x20 (32 bytes) ]
                                    //    [ output length (32 bytes) ]
                                    //    [ output content (N bytes) ]
                                    //
                                    // Perform the ABI decode by ignoring the first 32 bytes of the return data
                                    let copysize := sub(returndatasize, 0x20)
                                    returndatacopy(output, 0x20, copysize)
                                    mstore(0x40, add(output, copysize)) // free mem ptr set
                                }
                            }
                        }
                        emit ScriptResult(address(executor), _script, _input, output);
                        return output;
                    }
                    modifier protectState {
                        address preKernel = address(kernel());
                        bytes32 preAppId = appId();
                        _; // exec
                        require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
                        require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
                    }
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                interface IEVMScriptExecutor {
                    function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
                    function executorType() external pure returns (bytes32);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "./IEVMScriptExecutor.sol";
                contract EVMScriptRegistryConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
                    */
                    bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
                }
                interface IEVMScriptRegistry {
                    function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
                    function disableScriptExecutor(uint256 executorId) external;
                    // TODO: this should be external
                    // See https://github.com/ethereum/solidity/issues/4832
                    function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                import "../acl/IACL.sol";
                import "../common/IVaultRecoverable.sol";
                interface IKernelEvents {
                    event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
                }
                // This should be an interface, but interfaces can't inherit yet :(
                contract IKernel is IKernelEvents, IVaultRecoverable {
                    function acl() public view returns (IACL);
                    function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
                    function setApp(bytes32 namespace, bytes32 appId, address app) public;
                    function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
                }
                /*
                 * SPDX-License-Identifier:    MIT
                 */
                pragma solidity ^0.4.24;
                contract KernelAppIds {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
                    */
                    bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
                    bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
                    bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
                }
                contract KernelNamespaceConstants {
                    /* Hardcoded constants to save gas
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
                    */
                    bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
                    bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
                    bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
                }
                // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
                // Adapted to use pragma ^0.4.24 and satisfy our linter rules
                pragma solidity ^0.4.24;
                /**
                 * @title SafeMath
                 * @dev Math operations with safety checks that revert on error
                 */
                library SafeMath {
                    string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
                    string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
                    string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
                    string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
                    /**
                    * @dev Multiplies two numbers, reverts on overflow.
                    */
                    function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                        if (_a == 0) {
                            return 0;
                        }
                        uint256 c = _a * _b;
                        require(c / _a == _b, ERROR_MUL_OVERFLOW);
                        return c;
                    }
                    /**
                    * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
                    */
                    function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                        require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
                        uint256 c = _a / _b;
                        // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                        return c;
                    }
                    /**
                    * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                    */
                    function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                        require(_b <= _a, ERROR_SUB_UNDERFLOW);
                        uint256 c = _a - _b;
                        return c;
                    }
                    /**
                    * @dev Adds two numbers, reverts on overflow.
                    */
                    function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
                        uint256 c = _a + _b;
                        require(c >= _a, ERROR_ADD_OVERFLOW);
                        return c;
                    }
                    /**
                    * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
                    * reverts when dividing by zero.
                    */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b != 0, ERROR_DIV_ZERO);
                        return a % b;
                    }
                }
                // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
                pragma solidity ^0.4.24;
                /**
                 * @title ERC20 interface
                 * @dev see https://github.com/ethereum/EIPs/issues/20
                 */
                contract ERC20 {
                    function totalSupply() public view returns (uint256);
                    function balanceOf(address _who) public view returns (uint256);
                    function allowance(address _owner, address _spender)
                        public view returns (uint256);
                    function transfer(address _to, uint256 _value) public returns (bool);
                    function approve(address _spender, uint256 _value)
                        public returns (bool);
                    function transferFrom(address _from, address _to, uint256 _value)
                        public returns (bool);
                    event Transfer(
                        address indexed from,
                        address indexed to,
                        uint256 value
                    );
                    event Approval(
                        address indexed owner,
                        address indexed spender,
                        uint256 value
                    );
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                /* See contracts/COMPILERS.md */
                pragma solidity 0.4.24;
                import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                //
                // We need to pack four variables into the same 256bit-wide storage slot
                // to lower the costs per each staking request.
                //
                // As a result, slot's memory aligned as follows:
                //
                // MSB ------------------------------------------------------------------------------> LSB
                // 256____________160_________________________128_______________32_____________________ 0
                // |_______________|___________________________|________________|_______________________|
                // | maxStakeLimit | maxStakeLimitGrowthBlocks | prevStakeLimit | prevStakeBlockNumber  |
                // |<-- 96 bits -->|<---------- 32 bits ------>|<-- 96 bits --->|<----- 32 bits ------->|
                //
                //
                // NB: Internal representation conventions:
                //
                // - the `maxStakeLimitGrowthBlocks` field above represented as follows:
                // `maxStakeLimitGrowthBlocks` = `maxStakeLimit` / `stakeLimitIncreasePerBlock`
                //           32 bits                 96 bits               96 bits
                //
                //
                // - the "staking paused" state is encoded by `prevStakeBlockNumber` being zero,
                // - the "staking unlimited" state is encoded by `maxStakeLimit` being zero and `prevStakeBlockNumber` being non-zero.
                //
                /**
                * @notice Library for the internal structs definitions
                * @dev solidity <0.6 doesn't support top-level structs
                * using the library to have a proper namespace
                */
                library StakeLimitState {
                    /**
                      * @dev Internal representation struct (slot-wide)
                      */
                    struct Data {
                        uint32 prevStakeBlockNumber;      // block number of the previous stake submit
                        uint96 prevStakeLimit;            // limit value (<= `maxStakeLimit`) obtained on the previous stake submit
                        uint32 maxStakeLimitGrowthBlocks; // limit regeneration speed expressed in blocks
                        uint96 maxStakeLimit;             // maximum limit value
                    }
                }
                library StakeLimitUnstructuredStorage {
                    using UnstructuredStorage for bytes32;
                    /// @dev Storage offset for `maxStakeLimit` (bits)
                    uint256 internal constant MAX_STAKE_LIMIT_OFFSET = 160;
                    /// @dev Storage offset for `maxStakeLimitGrowthBlocks` (bits)
                    uint256 internal constant MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET = 128;
                    /// @dev Storage offset for `prevStakeLimit` (bits)
                    uint256 internal constant PREV_STAKE_LIMIT_OFFSET = 32;
                    /// @dev Storage offset for `prevStakeBlockNumber` (bits)
                    uint256 internal constant PREV_STAKE_BLOCK_NUMBER_OFFSET = 0;
                    /**
                    * @dev Read stake limit state from the unstructured storage position
                    * @param _position storage offset
                    */
                    function getStorageStakeLimitStruct(bytes32 _position) internal view returns (StakeLimitState.Data memory stakeLimit) {
                        uint256 slotValue = _position.getStorageUint256();
                        stakeLimit.prevStakeBlockNumber = uint32(slotValue >> PREV_STAKE_BLOCK_NUMBER_OFFSET);
                        stakeLimit.prevStakeLimit = uint96(slotValue >> PREV_STAKE_LIMIT_OFFSET);
                        stakeLimit.maxStakeLimitGrowthBlocks = uint32(slotValue >> MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET);
                        stakeLimit.maxStakeLimit = uint96(slotValue >> MAX_STAKE_LIMIT_OFFSET);
                    }
                     /**
                    * @dev Write stake limit state to the unstructured storage position
                    * @param _position storage offset
                    * @param _data stake limit state structure instance
                    */
                    function setStorageStakeLimitStruct(bytes32 _position, StakeLimitState.Data memory _data) internal {
                        _position.setStorageUint256(
                            uint256(_data.prevStakeBlockNumber) << PREV_STAKE_BLOCK_NUMBER_OFFSET
                                | uint256(_data.prevStakeLimit) << PREV_STAKE_LIMIT_OFFSET
                                | uint256(_data.maxStakeLimitGrowthBlocks) << MAX_STAKE_LIMIT_GROWTH_BLOCKS_OFFSET
                                | uint256(_data.maxStakeLimit) << MAX_STAKE_LIMIT_OFFSET
                        );
                    }
                }
                /**
                * @notice Interface library with helper functions to deal with stake limit struct in a more high-level approach.
                */
                library StakeLimitUtils {
                    /**
                    * @notice Calculate stake limit for the current block.
                    * @dev using `_constGasMin` to make gas consumption independent of the current block number
                    */
                    function calculateCurrentStakeLimit(StakeLimitState.Data memory _data) internal view returns(uint256 limit) {
                        uint256 stakeLimitIncPerBlock;
                        if (_data.maxStakeLimitGrowthBlocks != 0) {
                            stakeLimitIncPerBlock = _data.maxStakeLimit / _data.maxStakeLimitGrowthBlocks;
                        }
                        uint256 blocksPassed = block.number - _data.prevStakeBlockNumber;
                        uint256 projectedLimit = _data.prevStakeLimit + blocksPassed * stakeLimitIncPerBlock;
                        limit = _constGasMin(
                            projectedLimit,
                            _data.maxStakeLimit
                        );
                    }
                    /**
                    * @notice check if staking is on pause
                    */
                    function isStakingPaused(StakeLimitState.Data memory _data) internal pure returns(bool) {
                        return _data.prevStakeBlockNumber == 0;
                    }
                    /**
                    * @notice check if staking limit is set (otherwise staking is unlimited)
                    */
                    function isStakingLimitSet(StakeLimitState.Data memory _data) internal pure returns(bool) {
                        return _data.maxStakeLimit != 0;
                    }
                    /**
                    * @notice update stake limit repr with the desired limits
                    * @dev input `_data` param is mutated and the func returns effectively the same pointer
                    * @param _data stake limit state struct
                    * @param _maxStakeLimit stake limit max value
                    * @param _stakeLimitIncreasePerBlock stake limit increase (restoration) per block
                    */
                    function setStakingLimit(
                        StakeLimitState.Data memory _data,
                        uint256 _maxStakeLimit,
                        uint256 _stakeLimitIncreasePerBlock
                    ) internal view returns (StakeLimitState.Data memory) {
                        require(_maxStakeLimit != 0, "ZERO_MAX_STAKE_LIMIT");
                        require(_maxStakeLimit <= uint96(-1), "TOO_LARGE_MAX_STAKE_LIMIT");
                        require(_maxStakeLimit >= _stakeLimitIncreasePerBlock, "TOO_LARGE_LIMIT_INCREASE");
                        require(
                            (_stakeLimitIncreasePerBlock == 0)
                            || (_maxStakeLimit / _stakeLimitIncreasePerBlock <= uint32(-1)),
                            "TOO_SMALL_LIMIT_INCREASE"
                        );
                        // reset prev stake limit to the new max stake limit if
                        if (
                            // staking was paused or
                            _data.prevStakeBlockNumber == 0 ||
                            // staking was unlimited or
                            _data.maxStakeLimit == 0 ||
                            // new maximum limit value is lower than the value obtained on the previous stake submit
                            _maxStakeLimit < _data.prevStakeLimit
                        ) {
                            _data.prevStakeLimit = uint96(_maxStakeLimit);
                        }
                        _data.maxStakeLimitGrowthBlocks =
                            _stakeLimitIncreasePerBlock != 0 ? uint32(_maxStakeLimit / _stakeLimitIncreasePerBlock) : 0;
                        _data.maxStakeLimit = uint96(_maxStakeLimit);
                        if (_data.prevStakeBlockNumber != 0) {
                            _data.prevStakeBlockNumber = uint32(block.number);
                        }
                        return _data;
                    }
                    /**
                    * @notice update stake limit repr to remove the limit
                    * @dev input `_data` param is mutated and the func returns effectively the same pointer
                    * @param _data stake limit state struct
                    */
                    function removeStakingLimit(
                        StakeLimitState.Data memory _data
                    ) internal pure returns (StakeLimitState.Data memory) {
                        _data.maxStakeLimit = 0;
                        return _data;
                    }
                    /**
                    * @notice update stake limit repr after submitting user's eth
                    * @dev input `_data` param is mutated and the func returns effectively the same pointer
                    * @param _data stake limit state struct
                    * @param _newPrevStakeLimit new value for the `prevStakeLimit` field
                    */
                    function updatePrevStakeLimit(
                        StakeLimitState.Data memory _data,
                        uint256 _newPrevStakeLimit
                    ) internal view returns (StakeLimitState.Data memory) {
                        assert(_newPrevStakeLimit <= uint96(-1));
                        assert(_data.prevStakeBlockNumber != 0);
                        _data.prevStakeLimit = uint96(_newPrevStakeLimit);
                        _data.prevStakeBlockNumber = uint32(block.number);
                        return _data;
                    }
                    /**
                    * @notice set stake limit pause state (on or off)
                    * @dev input `_data` param is mutated and the func returns effectively the same pointer
                    * @param _data stake limit state struct
                    * @param _isPaused pause state flag
                    */
                    function setStakeLimitPauseState(
                        StakeLimitState.Data memory _data,
                        bool _isPaused
                    ) internal view returns (StakeLimitState.Data memory) {
                        _data.prevStakeBlockNumber = uint32(_isPaused ? 0 : block.number);
                        return _data;
                    }
                    /**
                     * @notice find a minimum of two numbers with a constant gas consumption
                     * @dev doesn't use branching logic inside
                     * @param _lhs left hand side value
                     * @param _rhs right hand side value
                     */
                    function _constGasMin(uint256 _lhs, uint256 _rhs) internal pure returns (uint256 min) {
                        uint256 lhsIsLess;
                        assembly {
                            lhsIsLess := lt(_lhs, _rhs) // lhsIsLess = (_lhs < _rhs) ? 1 : 0
                        }
                        min = (_lhs * lhsIsLess) + (_rhs * (1 - lhsIsLess));
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                /* See contracts/COMPILERS.md */
                pragma solidity 0.4.24;
                import "@aragon/os/contracts/apps/AragonApp.sol";
                import "@aragon/os/contracts/lib/math/SafeMath.sol";
                import "../common/interfaces/ILidoLocator.sol";
                import "../common/interfaces/IBurner.sol";
                import "./lib/StakeLimitUtils.sol";
                import "../common/lib/Math256.sol";
                import "./StETHPermit.sol";
                import "./utils/Versioned.sol";
                interface IPostTokenRebaseReceiver {
                    function handlePostTokenRebase(
                        uint256 _reportTimestamp,
                        uint256 _timeElapsed,
                        uint256 _preTotalShares,
                        uint256 _preTotalEther,
                        uint256 _postTotalShares,
                        uint256 _postTotalEther,
                        uint256 _sharesMintedAsFees
                    ) external;
                }
                interface IOracleReportSanityChecker {
                    function checkAccountingOracleReport(
                        uint256 _timeElapsed,
                        uint256 _preCLBalance,
                        uint256 _postCLBalance,
                        uint256 _withdrawalVaultBalance,
                        uint256 _elRewardsVaultBalance,
                        uint256 _sharesRequestedToBurn,
                        uint256 _preCLValidators,
                        uint256 _postCLValidators
                    ) external view;
                    function smoothenTokenRebase(
                        uint256 _preTotalPooledEther,
                        uint256 _preTotalShares,
                        uint256 _preCLBalance,
                        uint256 _postCLBalance,
                        uint256 _withdrawalVaultBalance,
                        uint256 _elRewardsVaultBalance,
                        uint256 _sharesRequestedToBurn,
                        uint256 _etherToLockForWithdrawals,
                        uint256 _newSharesToBurnForWithdrawals
                    ) external view returns (
                        uint256 withdrawals,
                        uint256 elRewards,
                        uint256 simulatedSharesToBurn,
                        uint256 sharesToBurn
                    );
                    function checkWithdrawalQueueOracleReport(
                        uint256 _lastFinalizableRequestId,
                        uint256 _reportTimestamp
                    ) external view;
                    function checkSimulatedShareRate(
                        uint256 _postTotalPooledEther,
                        uint256 _postTotalShares,
                        uint256 _etherLockedOnWithdrawalQueue,
                        uint256 _sharesBurntDueToWithdrawals,
                        uint256 _simulatedShareRate
                    ) external view;
                }
                interface ILidoExecutionLayerRewardsVault {
                    function withdrawRewards(uint256 _maxAmount) external returns (uint256 amount);
                }
                interface IWithdrawalVault {
                    function withdrawWithdrawals(uint256 _amount) external;
                }
                interface IStakingRouter {
                    function deposit(
                        uint256 _depositsCount,
                        uint256 _stakingModuleId,
                        bytes _depositCalldata
                    ) external payable;
                    function getStakingRewardsDistribution()
                        external
                        view
                        returns (
                            address[] memory recipients,
                            uint256[] memory stakingModuleIds,
                            uint96[] memory stakingModuleFees,
                            uint96 totalFee,
                            uint256 precisionPoints
                        );
                    function getWithdrawalCredentials() external view returns (bytes32);
                    function reportRewardsMinted(uint256[] _stakingModuleIds, uint256[] _totalShares) external;
                    function getTotalFeeE4Precision() external view returns (uint16 totalFee);
                    function getStakingFeeAggregateDistributionE4Precision() external view returns (
                        uint16 modulesFee, uint16 treasuryFee
                    );
                    function getStakingModuleMaxDepositsCount(uint256 _stakingModuleId, uint256 _maxDepositsValue)
                        external
                        view
                        returns (uint256);
                    function TOTAL_BASIS_POINTS() external view returns (uint256);
                }
                interface IWithdrawalQueue {
                    function prefinalize(uint256[] _batches, uint256 _maxShareRate)
                        external
                        view
                        returns (uint256 ethToLock, uint256 sharesToBurn);
                    function finalize(uint256 _lastIdToFinalize, uint256 _maxShareRate) external payable;
                    function isPaused() external view returns (bool);
                    function unfinalizedStETH() external view returns (uint256);
                    function isBunkerModeActive() external view returns (bool);
                }
                /**
                * @title Liquid staking pool implementation
                *
                * Lido is an Ethereum liquid staking protocol solving the problem of frozen staked ether on Consensus Layer
                * being unavailable for transfers and DeFi on Execution Layer.
                *
                * Since balances of all token holders change when the amount of total pooled Ether
                * changes, this token cannot fully implement ERC20 standard: it only emits `Transfer`
                * events upon explicit transfer between holders. In contrast, when Lido oracle reports
                * rewards, no Transfer events are generated: doing so would require emitting an event
                * for each token holder and thus running an unbounded loop.
                *
                * ---
                * NB: Order of inheritance must preserve the structured storage layout of the previous versions.
                *
                * @dev Lido is derived from `StETHPermit` that has a structured storage:
                * SLOT 0: mapping (address => uint256) private shares (`StETH`)
                * SLOT 1: mapping (address => mapping (address => uint256)) private allowances (`StETH`)
                * SLOT 2: mapping(address => uint256) internal noncesByAddress (`StETHPermit`)
                *
                * `Versioned` and `AragonApp` both don't have the pre-allocated structured storage.
                */
                contract Lido is Versioned, StETHPermit, AragonApp {
                    using SafeMath for uint256;
                    using UnstructuredStorage for bytes32;
                    using StakeLimitUnstructuredStorage for bytes32;
                    using StakeLimitUtils for StakeLimitState.Data;
                    /// ACL
                    bytes32 public constant PAUSE_ROLE =
                        0x139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d; // keccak256("PAUSE_ROLE");
                    bytes32 public constant RESUME_ROLE =
                        0x2fc10cc8ae19568712f7a176fb4978616a610650813c9d05326c34abb62749c7; // keccak256("RESUME_ROLE");
                    bytes32 public constant STAKING_PAUSE_ROLE =
                        0x84ea57490227bc2be925c684e2a367071d69890b629590198f4125a018eb1de8; // keccak256("STAKING_PAUSE_ROLE")
                    bytes32 public constant STAKING_CONTROL_ROLE =
                        0xa42eee1333c0758ba72be38e728b6dadb32ea767de5b4ddbaea1dae85b1b051f; // keccak256("STAKING_CONTROL_ROLE")
                    bytes32 public constant UNSAFE_CHANGE_DEPOSITED_VALIDATORS_ROLE =
                        0xe6dc5d79630c61871e99d341ad72c5a052bed2fc8c79e5a4480a7cd31117576c; // keccak256("UNSAFE_CHANGE_DEPOSITED_VALIDATORS_ROLE")
                    uint256 private constant DEPOSIT_SIZE = 32 ether;
                    /// @dev storage slot position for the Lido protocol contracts locator
                    bytes32 internal constant LIDO_LOCATOR_POSITION =
                        0x9ef78dff90f100ea94042bd00ccb978430524befc391d3e510b5f55ff3166df7; // keccak256("lido.Lido.lidoLocator")
                    /// @dev storage slot position of the staking rate limit structure
                    bytes32 internal constant STAKING_STATE_POSITION =
                        0xa3678de4a579be090bed1177e0a24f77cc29d181ac22fd7688aca344d8938015; // keccak256("lido.Lido.stakeLimit");
                    /// @dev amount of Ether (on the current Ethereum side) buffered on this smart contract balance
                    bytes32 internal constant BUFFERED_ETHER_POSITION =
                        0xed310af23f61f96daefbcd140b306c0bdbf8c178398299741687b90e794772b0; // keccak256("lido.Lido.bufferedEther");
                    /// @dev number of deposited validators (incrementing counter of deposit operations).
                    bytes32 internal constant DEPOSITED_VALIDATORS_POSITION =
                        0xe6e35175eb53fc006520a2a9c3e9711a7c00de6ff2c32dd31df8c5a24cac1b5c; // keccak256("lido.Lido.depositedValidators");
                    /// @dev total amount of ether on Consensus Layer (sum of all the balances of Lido validators)
                    // "beacon" in the `keccak256()` parameter is staying here for compatibility reason
                    bytes32 internal constant CL_BALANCE_POSITION =
                        0xa66d35f054e68143c18f32c990ed5cb972bb68a68f500cd2dd3a16bbf3686483; // keccak256("lido.Lido.beaconBalance");
                    /// @dev number of Lido's validators available in the Consensus Layer state
                    // "beacon" in the `keccak256()` parameter is staying here for compatibility reason
                    bytes32 internal constant CL_VALIDATORS_POSITION =
                        0x9f70001d82b6ef54e9d3725b46581c3eb9ee3aa02b941b6aa54d678a9ca35b10; // keccak256("lido.Lido.beaconValidators");
                    /// @dev Just a counter of total amount of execution layer rewards received by Lido contract. Not used in the logic.
                    bytes32 internal constant TOTAL_EL_REWARDS_COLLECTED_POSITION =
                        0xafe016039542d12eec0183bb0b1ffc2ca45b027126a494672fba4154ee77facb; // keccak256("lido.Lido.totalELRewardsCollected");
                    // Staking was paused (don't accept user's ether submits)
                    event StakingPaused();
                    // Staking was resumed (accept user's ether submits)
                    event StakingResumed();
                    // Staking limit was set (rate limits user's submits)
                    event StakingLimitSet(uint256 maxStakeLimit, uint256 stakeLimitIncreasePerBlock);
                    // Staking limit was removed
                    event StakingLimitRemoved();
                    // Emits when validators number delivered by the oracle
                    event CLValidatorsUpdated(
                        uint256 indexed reportTimestamp,
                        uint256 preCLValidators,
                        uint256 postCLValidators
                    );
                    // Emits when var at `DEPOSITED_VALIDATORS_POSITION` changed
                    event DepositedValidatorsChanged(
                        uint256 depositedValidators
                    );
                    // Emits when oracle accounting report processed
                    event ETHDistributed(
                        uint256 indexed reportTimestamp,
                        uint256 preCLBalance,
                        uint256 postCLBalance,
                        uint256 withdrawalsWithdrawn,
                        uint256 executionLayerRewardsWithdrawn,
                        uint256 postBufferedEther
                    );
                    // Emits when token rebased (total supply and/or total shares were changed)
                    event TokenRebased(
                        uint256 indexed reportTimestamp,
                        uint256 timeElapsed,
                        uint256 preTotalShares,
                        uint256 preTotalEther,
                        uint256 postTotalShares,
                        uint256 postTotalEther,
                        uint256 sharesMintedAsFees
                    );
                    // Lido locator set
                    event LidoLocatorSet(address lidoLocator);
                    // The amount of ETH withdrawn from LidoExecutionLayerRewardsVault to Lido
                    event ELRewardsReceived(uint256 amount);
                    // The amount of ETH withdrawn from WithdrawalVault to Lido
                    event WithdrawalsReceived(uint256 amount);
                    // Records a deposit made by a user
                    event Submitted(address indexed sender, uint256 amount, address referral);
                    // The `amount` of ether was sent to the deposit_contract.deposit function
                    event Unbuffered(uint256 amount);
                    /**
                    * @dev As AragonApp, Lido contract must be initialized with following variables:
                    *      NB: by default, staking and the whole Lido pool are in paused state
                    *
                    * The contract's balance must be non-zero to allow initial holder bootstrap.
                    *
                    * @param _lidoLocator lido locator contract
                    * @param _eip712StETH eip712 helper contract for StETH
                    */
                    function initialize(address _lidoLocator, address _eip712StETH)
                        public
                        payable
                        onlyInit
                    {
                        _bootstrapInitialHolder();
                        _initialize_v2(_lidoLocator, _eip712StETH);
                        initialized();
                    }
                    /**
                     * initializer for the Lido version "2"
                     */
                    function _initialize_v2(address _lidoLocator, address _eip712StETH) internal {
                        _setContractVersion(2);
                        LIDO_LOCATOR_POSITION.setStorageAddress(_lidoLocator);
                        _initializeEIP712StETH(_eip712StETH);
                        // set infinite allowance for burner from withdrawal queue
                        // to burn finalized requests' shares
                        _approve(
                            ILidoLocator(_lidoLocator).withdrawalQueue(),
                            ILidoLocator(_lidoLocator).burner(),
                            INFINITE_ALLOWANCE
                        );
                        emit LidoLocatorSet(_lidoLocator);
                    }
                    /**
                     * @notice A function to finalize upgrade to v2 (from v1). Can be called only once
                     * @dev Value "1" in CONTRACT_VERSION_POSITION is skipped due to change in numbering
                     *
                     * The initial protocol token holder must exist.
                     *
                     * For more details see https://github.com/lidofinance/lido-improvement-proposals/blob/develop/LIPS/lip-10.md
                     */
                    function finalizeUpgrade_v2(address _lidoLocator, address _eip712StETH) external {
                        _checkContractVersion(0);
                        require(hasInitialized(), "NOT_INITIALIZED");
                        require(_lidoLocator != address(0), "LIDO_LOCATOR_ZERO_ADDRESS");
                        require(_eip712StETH != address(0), "EIP712_STETH_ZERO_ADDRESS");
                        require(_sharesOf(INITIAL_TOKEN_HOLDER) != 0, "INITIAL_HOLDER_EXISTS");
                        _initialize_v2(_lidoLocator, _eip712StETH);
                    }
                    /**
                     * @notice Stops accepting new Ether to the protocol
                     *
                     * @dev While accepting new Ether is stopped, calls to the `submit` function,
                     * as well as to the default payable function, will revert.
                     *
                     * Emits `StakingPaused` event.
                     */
                    function pauseStaking() external {
                        _auth(STAKING_PAUSE_ROLE);
                        _pauseStaking();
                    }
                    /**
                     * @notice Resumes accepting new Ether to the protocol (if `pauseStaking` was called previously)
                     * NB: Staking could be rate-limited by imposing a limit on the stake amount
                     * at each moment in time, see `setStakingLimit()` and `removeStakingLimit()`
                     *
                     * @dev Preserves staking limit if it was set previously
                     *
                     * Emits `StakingResumed` event
                     */
                    function resumeStaking() external {
                        _auth(STAKING_CONTROL_ROLE);
                        require(hasInitialized(), "NOT_INITIALIZED");
                        _resumeStaking();
                    }
                    /**
                     * @notice Sets the staking rate limit
                     *
                     * ▲ Stake limit
                     * │.....  .....   ........ ...            ....     ... Stake limit = max
                     * │      .       .        .   .   .      .    . . .
                     * │     .       .              . .  . . .      . .
                     * │            .                .  . . .
                     * │──────────────────────────────────────────────────> Time
                     * │     ^      ^          ^   ^^^  ^ ^ ^     ^^^ ^     Stake events
                     *
                     * @dev Reverts if:
                     * - `_maxStakeLimit` == 0
                     * - `_maxStakeLimit` >= 2^96
                     * - `_maxStakeLimit` < `_stakeLimitIncreasePerBlock`
                     * - `_maxStakeLimit` / `_stakeLimitIncreasePerBlock` >= 2^32 (only if `_stakeLimitIncreasePerBlock` != 0)
                     *
                     * Emits `StakingLimitSet` event
                     *
                     * @param _maxStakeLimit max stake limit value
                     * @param _stakeLimitIncreasePerBlock stake limit increase per single block
                     */
                    function setStakingLimit(uint256 _maxStakeLimit, uint256 _stakeLimitIncreasePerBlock) external {
                        _auth(STAKING_CONTROL_ROLE);
                        STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                            STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakingLimit(_maxStakeLimit, _stakeLimitIncreasePerBlock)
                        );
                        emit StakingLimitSet(_maxStakeLimit, _stakeLimitIncreasePerBlock);
                    }
                    /**
                     * @notice Removes the staking rate limit
                     *
                     * Emits `StakingLimitRemoved` event
                     */
                    function removeStakingLimit() external {
                        _auth(STAKING_CONTROL_ROLE);
                        STAKING_STATE_POSITION.setStorageStakeLimitStruct(STAKING_STATE_POSITION.getStorageStakeLimitStruct().removeStakingLimit());
                        emit StakingLimitRemoved();
                    }
                    /**
                     * @notice Check staking state: whether it's paused or not
                     */
                    function isStakingPaused() external view returns (bool) {
                        return STAKING_STATE_POSITION.getStorageStakeLimitStruct().isStakingPaused();
                    }
                    /**
                     * @notice Returns how much Ether can be staked in the current block
                     * @dev Special return values:
                     * - 2^256 - 1 if staking is unlimited;
                     * - 0 if staking is paused or if limit is exhausted.
                     */
                    function getCurrentStakeLimit() external view returns (uint256) {
                        return _getCurrentStakeLimit(STAKING_STATE_POSITION.getStorageStakeLimitStruct());
                    }
                    /**
                     * @notice Returns full info about current stake limit params and state
                     * @dev Might be used for the advanced integration requests.
                     * @return isStakingPaused staking pause state (equivalent to return of isStakingPaused())
                     * @return isStakingLimitSet whether the stake limit is set
                     * @return currentStakeLimit current stake limit (equivalent to return of getCurrentStakeLimit())
                     * @return maxStakeLimit max stake limit
                     * @return maxStakeLimitGrowthBlocks blocks needed to restore max stake limit from the fully exhausted state
                     * @return prevStakeLimit previously reached stake limit
                     * @return prevStakeBlockNumber previously seen block number
                     */
                    function getStakeLimitFullInfo()
                        external
                        view
                        returns (
                            bool isStakingPaused,
                            bool isStakingLimitSet,
                            uint256 currentStakeLimit,
                            uint256 maxStakeLimit,
                            uint256 maxStakeLimitGrowthBlocks,
                            uint256 prevStakeLimit,
                            uint256 prevStakeBlockNumber
                        )
                    {
                        StakeLimitState.Data memory stakeLimitData = STAKING_STATE_POSITION.getStorageStakeLimitStruct();
                        isStakingPaused = stakeLimitData.isStakingPaused();
                        isStakingLimitSet = stakeLimitData.isStakingLimitSet();
                        currentStakeLimit = _getCurrentStakeLimit(stakeLimitData);
                        maxStakeLimit = stakeLimitData.maxStakeLimit;
                        maxStakeLimitGrowthBlocks = stakeLimitData.maxStakeLimitGrowthBlocks;
                        prevStakeLimit = stakeLimitData.prevStakeLimit;
                        prevStakeBlockNumber = stakeLimitData.prevStakeBlockNumber;
                    }
                    /**
                    * @notice Send funds to the pool
                    * @dev Users are able to submit their funds by transacting to the fallback function.
                    * Unlike vanilla Ethereum Deposit contract, accepting only 32-Ether transactions, Lido
                    * accepts payments of any size. Submitted Ethers are stored in Buffer until someone calls
                    * deposit() and pushes them to the Ethereum Deposit contract.
                    */
                    // solhint-disable-next-line no-complex-fallback
                    function() external payable {
                        // protection against accidental submissions by calling non-existent function
                        require(msg.data.length == 0, "NON_EMPTY_DATA");
                        _submit(0);
                    }
                    /**
                     * @notice Send funds to the pool with optional _referral parameter
                     * @dev This function is alternative way to submit funds. Supports optional referral address.
                     * @return Amount of StETH shares generated
                     */
                    function submit(address _referral) external payable returns (uint256) {
                        return _submit(_referral);
                    }
                    /**
                     * @notice A payable function for execution layer rewards. Can be called only by `ExecutionLayerRewardsVault`
                     * @dev We need a dedicated function because funds received by the default payable function
                     * are treated as a user deposit
                     */
                    function receiveELRewards() external payable {
                        require(msg.sender == getLidoLocator().elRewardsVault());
                        TOTAL_EL_REWARDS_COLLECTED_POSITION.setStorageUint256(getTotalELRewardsCollected().add(msg.value));
                        emit ELRewardsReceived(msg.value);
                    }
                    /**
                    * @notice A payable function for withdrawals acquisition. Can be called only by `WithdrawalVault`
                    * @dev We need a dedicated function because funds received by the default payable function
                    * are treated as a user deposit
                    */
                    function receiveWithdrawals() external payable {
                        require(msg.sender == getLidoLocator().withdrawalVault());
                        emit WithdrawalsReceived(msg.value);
                    }
                    /**
                     * @notice Stop pool routine operations
                     */
                    function stop() external {
                        _auth(PAUSE_ROLE);
                        _stop();
                        _pauseStaking();
                    }
                    /**
                     * @notice Resume pool routine operations
                     * @dev Staking is resumed after this call using the previously set limits (if any)
                     */
                    function resume() external {
                        _auth(RESUME_ROLE);
                        _resume();
                        _resumeStaking();
                    }
                    /**
                     * The structure is used to aggregate the `handleOracleReport` provided data.
                     * @dev Using the in-memory structure addresses `stack too deep` issues.
                     */
                    struct OracleReportedData {
                        // Oracle timings
                        uint256 reportTimestamp;
                        uint256 timeElapsed;
                        // CL values
                        uint256 clValidators;
                        uint256 postCLBalance;
                        // EL values
                        uint256 withdrawalVaultBalance;
                        uint256 elRewardsVaultBalance;
                        uint256 sharesRequestedToBurn;
                        // Decision about withdrawals processing
                        uint256[] withdrawalFinalizationBatches;
                        uint256 simulatedShareRate;
                    }
                    /**
                     * The structure is used to preload the contract using `getLidoLocator()` via single call
                     */
                    struct OracleReportContracts {
                        address accountingOracle;
                        address elRewardsVault;
                        address oracleReportSanityChecker;
                        address burner;
                        address withdrawalQueue;
                        address withdrawalVault;
                        address postTokenRebaseReceiver;
                    }
                    /**
                    * @notice Updates accounting stats, collects EL rewards and distributes collected rewards
                    *         if beacon balance increased, performs withdrawal requests finalization
                    * @dev periodically called by the AccountingOracle contract
                    *
                    * @param _reportTimestamp the moment of the oracle report calculation
                    * @param _timeElapsed seconds elapsed since the previous report calculation
                    * @param _clValidators number of Lido validators on Consensus Layer
                    * @param _clBalance sum of all Lido validators' balances on Consensus Layer
                    * @param _withdrawalVaultBalance withdrawal vault balance on Execution Layer at `_reportTimestamp`
                    * @param _elRewardsVaultBalance elRewards vault balance on Execution Layer at `_reportTimestamp`
                    * @param _sharesRequestedToBurn shares requested to burn through Burner at `_reportTimestamp`
                    * @param _withdrawalFinalizationBatches the ascendingly-sorted array of withdrawal request IDs obtained by calling
                    * WithdrawalQueue.calculateFinalizationBatches. Empty array means that no withdrawal requests should be finalized
                    * @param _simulatedShareRate share rate that was simulated by oracle when the report data created (1e27 precision)
                    *
                    * NB: `_simulatedShareRate` should be calculated off-chain by calling the method with `eth_call` JSON-RPC API
                    * while passing empty `_withdrawalFinalizationBatches` and `_simulatedShareRate` == 0, plugging the returned values
                    * to the following formula: `_simulatedShareRate = (postTotalPooledEther * 1e27) / postTotalShares`
                    *
                    * @return postRebaseAmounts[0]: `postTotalPooledEther` amount of ether in the protocol after report
                    * @return postRebaseAmounts[1]: `postTotalShares` amount of shares in the protocol after report
                    * @return postRebaseAmounts[2]: `withdrawals` withdrawn from the withdrawals vault
                    * @return postRebaseAmounts[3]: `elRewards` withdrawn from the execution layer rewards vault
                    */
                    function handleOracleReport(
                        // Oracle timings
                        uint256 _reportTimestamp,
                        uint256 _timeElapsed,
                        // CL values
                        uint256 _clValidators,
                        uint256 _clBalance,
                        // EL values
                        uint256 _withdrawalVaultBalance,
                        uint256 _elRewardsVaultBalance,
                        uint256 _sharesRequestedToBurn,
                        // Decision about withdrawals processing
                        uint256[] _withdrawalFinalizationBatches,
                        uint256 _simulatedShareRate
                    ) external returns (uint256[4] postRebaseAmounts) {
                        _whenNotStopped();
                        return _handleOracleReport(
                            OracleReportedData(
                                _reportTimestamp,
                                _timeElapsed,
                                _clValidators,
                                _clBalance,
                                _withdrawalVaultBalance,
                                _elRewardsVaultBalance,
                                _sharesRequestedToBurn,
                                _withdrawalFinalizationBatches,
                                _simulatedShareRate
                            )
                        );
                    }
                    /**
                     * @notice Unsafely change deposited validators
                     *
                     * The method unsafely changes deposited validator counter.
                     * Can be required when onboarding external validators to Lido
                     * (i.e., had deposited before and rotated their type-0x00 withdrawal credentials to Lido)
                     *
                     * @param _newDepositedValidators new value
                     */
                    function unsafeChangeDepositedValidators(uint256 _newDepositedValidators) external {
                        _auth(UNSAFE_CHANGE_DEPOSITED_VALIDATORS_ROLE);
                        DEPOSITED_VALIDATORS_POSITION.setStorageUint256(_newDepositedValidators);
                        emit DepositedValidatorsChanged(_newDepositedValidators);
                    }
                    /**
                     * @notice Overrides default AragonApp behaviour to disallow recovery.
                     */
                    function transferToVault(address /* _token */) external {
                        revert("NOT_SUPPORTED");
                    }
                    /**
                    * @notice Get the amount of Ether temporary buffered on this contract balance
                    * @dev Buffered balance is kept on the contract from the moment the funds are received from user
                    * until the moment they are actually sent to the official Deposit contract.
                    * @return amount of buffered funds in wei
                    */
                    function getBufferedEther() external view returns (uint256) {
                        return _getBufferedEther();
                    }
                    /**
                     * @notice Get total amount of execution layer rewards collected to Lido contract
                     * @dev Ether got through LidoExecutionLayerRewardsVault is kept on this contract's balance the same way
                     * as other buffered Ether is kept (until it gets deposited)
                     * @return amount of funds received as execution layer rewards in wei
                     */
                    function getTotalELRewardsCollected() public view returns (uint256) {
                        return TOTAL_EL_REWARDS_COLLECTED_POSITION.getStorageUint256();
                    }
                    /**
                     * @notice Gets authorized oracle address
                     * @return address of oracle contract
                     */
                    function getLidoLocator() public view returns (ILidoLocator) {
                        return ILidoLocator(LIDO_LOCATOR_POSITION.getStorageAddress());
                    }
                    /**
                    * @notice Returns the key values related to Consensus Layer side of the contract. It historically contains beacon
                    * @return depositedValidators - number of deposited validators from Lido contract side
                    * @return beaconValidators - number of Lido validators visible on Consensus Layer, reported by oracle
                    * @return beaconBalance - total amount of ether on the Consensus Layer side (sum of all the balances of Lido validators)
                    *
                    * @dev `beacon` in naming still here for historical reasons
                    */
                    function getBeaconStat() external view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance) {
                        depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                        beaconValidators = CL_VALIDATORS_POSITION.getStorageUint256();
                        beaconBalance = CL_BALANCE_POSITION.getStorageUint256();
                    }
                    /**
                     * @dev Check that Lido allows depositing buffered ether to the consensus layer
                     * Depends on the bunker state and protocol's pause state
                     */
                    function canDeposit() public view returns (bool) {
                        return !_withdrawalQueue().isBunkerModeActive() && !isStopped();
                    }
                    /**
                     * @dev Returns depositable ether amount.
                     * Takes into account unfinalized stETH required by WithdrawalQueue
                     */
                    function getDepositableEther() public view returns (uint256) {
                        uint256 bufferedEther = _getBufferedEther();
                        uint256 withdrawalReserve = _withdrawalQueue().unfinalizedStETH();
                        return bufferedEther > withdrawalReserve ? bufferedEther - withdrawalReserve : 0;
                    }
                    /**
                     * @dev Invokes a deposit call to the Staking Router contract and updates buffered counters
                     * @param _maxDepositsCount max deposits count
                     * @param _stakingModuleId id of the staking module to be deposited
                     * @param _depositCalldata module calldata
                     */
                    function deposit(uint256 _maxDepositsCount, uint256 _stakingModuleId, bytes _depositCalldata) external {
                        ILidoLocator locator = getLidoLocator();
                        require(msg.sender == locator.depositSecurityModule(), "APP_AUTH_DSM_FAILED");
                        require(canDeposit(), "CAN_NOT_DEPOSIT");
                        IStakingRouter stakingRouter = _stakingRouter();
                        uint256 depositsCount = Math256.min(
                            _maxDepositsCount,
                            stakingRouter.getStakingModuleMaxDepositsCount(_stakingModuleId, getDepositableEther())
                        );
                        uint256 depositsValue;
                        if (depositsCount > 0) {
                            depositsValue = depositsCount.mul(DEPOSIT_SIZE);
                            /// @dev firstly update the local state of the contract to prevent a reentrancy attack,
                            ///     even if the StakingRouter is a trusted contract.
                            BUFFERED_ETHER_POSITION.setStorageUint256(_getBufferedEther().sub(depositsValue));
                            emit Unbuffered(depositsValue);
                            uint256 newDepositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256().add(depositsCount);
                            DEPOSITED_VALIDATORS_POSITION.setStorageUint256(newDepositedValidators);
                            emit DepositedValidatorsChanged(newDepositedValidators);
                        }
                        /// @dev transfer ether to StakingRouter and make a deposit at the same time. All the ether
                        ///     sent to StakingRouter is counted as deposited. If StakingRouter can't deposit all
                        ///     passed ether it MUST revert the whole transaction (never happens in normal circumstances)
                        stakingRouter.deposit.value(depositsValue)(depositsCount, _stakingModuleId, _depositCalldata);
                    }
                    /// DEPRECATED PUBLIC METHODS
                    /**
                     * @notice Returns current withdrawal credentials of deposited validators
                     * @dev DEPRECATED: use StakingRouter.getWithdrawalCredentials() instead
                     */
                    function getWithdrawalCredentials() external view returns (bytes32) {
                        return _stakingRouter().getWithdrawalCredentials();
                    }
                    /**
                     * @notice Returns legacy oracle
                     * @dev DEPRECATED: the `AccountingOracle` superseded the old one
                     */
                    function getOracle() external view returns (address) {
                        return getLidoLocator().legacyOracle();
                    }
                    /**
                     * @notice Returns the treasury address
                     * @dev DEPRECATED: use LidoLocator.treasury()
                     */
                    function getTreasury() external view returns (address) {
                        return _treasury();
                    }
                    /**
                     * @notice Returns current staking rewards fee rate
                     * @dev DEPRECATED: Now fees information is stored in StakingRouter and
                     * with higher precision. Use StakingRouter.getStakingFeeAggregateDistribution() instead.
                     * @return totalFee total rewards fee in 1e4 precision (10000 is 100%). The value might be
                     * inaccurate because the actual value is truncated here to 1e4 precision.
                     */
                    function getFee() external view returns (uint16 totalFee) {
                        totalFee = _stakingRouter().getTotalFeeE4Precision();
                    }
                    /**
                     * @notice Returns current fee distribution, values relative to the total fee (getFee())
                     * @dev DEPRECATED: Now fees information is stored in StakingRouter and
                     * with higher precision. Use StakingRouter.getStakingFeeAggregateDistribution() instead.
                     * @return treasuryFeeBasisPoints return treasury fee in TOTAL_BASIS_POINTS (10000 is 100% fee) precision
                     * @return insuranceFeeBasisPoints always returns 0 because the capability to send fees to
                     * insurance from Lido contract is removed.
                     * @return operatorsFeeBasisPoints return total fee for all operators of all staking modules in
                     * TOTAL_BASIS_POINTS (10000 is 100% fee) precision.
                     * Previously returned total fee of all node operators of NodeOperatorsRegistry (Curated staking module now)
                     * The value might be inaccurate because the actual value is truncated here to 1e4 precision.
                     */
                    function getFeeDistribution()
                        external view
                        returns (
                            uint16 treasuryFeeBasisPoints,
                            uint16 insuranceFeeBasisPoints,
                            uint16 operatorsFeeBasisPoints
                        )
                    {
                        IStakingRouter stakingRouter = _stakingRouter();
                        uint256 totalBasisPoints = stakingRouter.TOTAL_BASIS_POINTS();
                        uint256 totalFee = stakingRouter.getTotalFeeE4Precision();
                        (uint256 treasuryFeeBasisPointsAbs, uint256 operatorsFeeBasisPointsAbs) = stakingRouter
                            .getStakingFeeAggregateDistributionE4Precision();
                        insuranceFeeBasisPoints = 0;  // explicitly set to zero
                        treasuryFeeBasisPoints = uint16((treasuryFeeBasisPointsAbs * totalBasisPoints) / totalFee);
                        operatorsFeeBasisPoints = uint16((operatorsFeeBasisPointsAbs * totalBasisPoints) / totalFee);
                    }
                    /*
                     * @dev updates Consensus Layer state snapshot according to the current report
                     *
                     * NB: conventions and assumptions
                     *
                     * `depositedValidators` are total amount of the **ever** deposited Lido validators
                     * `_postClValidators` are total amount of the **ever** appeared on the CL side Lido validators
                     *
                     * i.e., exited Lido validators persist in the state, just with a different status
                     */
                    function _processClStateUpdate(
                        uint256 _reportTimestamp,
                        uint256 _preClValidators,
                        uint256 _postClValidators,
                        uint256 _postClBalance
                    ) internal returns (uint256 preCLBalance) {
                        uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                        require(_postClValidators <= depositedValidators, "REPORTED_MORE_DEPOSITED");
                        require(_postClValidators >= _preClValidators, "REPORTED_LESS_VALIDATORS");
                        if (_postClValidators > _preClValidators) {
                            CL_VALIDATORS_POSITION.setStorageUint256(_postClValidators);
                        }
                        uint256 appearedValidators = _postClValidators - _preClValidators;
                        preCLBalance = CL_BALANCE_POSITION.getStorageUint256();
                        // Take into account the balance of the newly appeared validators
                        preCLBalance = preCLBalance.add(appearedValidators.mul(DEPOSIT_SIZE));
                        // Save the current CL balance and validators to
                        // calculate rewards on the next push
                        CL_BALANCE_POSITION.setStorageUint256(_postClBalance);
                        emit CLValidatorsUpdated(_reportTimestamp, _preClValidators, _postClValidators);
                    }
                    /**
                     * @dev collect ETH from ELRewardsVault and WithdrawalVault, then send to WithdrawalQueue
                     */
                    function _collectRewardsAndProcessWithdrawals(
                        OracleReportContracts memory _contracts,
                        uint256 _withdrawalsToWithdraw,
                        uint256 _elRewardsToWithdraw,
                        uint256[] _withdrawalFinalizationBatches,
                        uint256 _simulatedShareRate,
                        uint256 _etherToLockOnWithdrawalQueue
                    ) internal {
                        // withdraw execution layer rewards and put them to the buffer
                        if (_elRewardsToWithdraw > 0) {
                            ILidoExecutionLayerRewardsVault(_contracts.elRewardsVault).withdrawRewards(_elRewardsToWithdraw);
                        }
                        // withdraw withdrawals and put them to the buffer
                        if (_withdrawalsToWithdraw > 0) {
                            IWithdrawalVault(_contracts.withdrawalVault).withdrawWithdrawals(_withdrawalsToWithdraw);
                        }
                        // finalize withdrawals (send ether, assign shares for burning)
                        if (_etherToLockOnWithdrawalQueue > 0) {
                            IWithdrawalQueue withdrawalQueue = IWithdrawalQueue(_contracts.withdrawalQueue);
                            withdrawalQueue.finalize.value(_etherToLockOnWithdrawalQueue)(
                                _withdrawalFinalizationBatches[_withdrawalFinalizationBatches.length - 1],
                                _simulatedShareRate
                            );
                        }
                        uint256 postBufferedEther = _getBufferedEther()
                            .add(_elRewardsToWithdraw) // Collected from ELVault
                            .add(_withdrawalsToWithdraw) // Collected from WithdrawalVault
                            .sub(_etherToLockOnWithdrawalQueue); // Sent to WithdrawalQueue
                        _setBufferedEther(postBufferedEther);
                    }
                    /**
                     * @dev return amount to lock on withdrawal queue and shares to burn
                     * depending on the finalization batch parameters
                     */
                    function _calculateWithdrawals(
                        OracleReportContracts memory _contracts,
                        OracleReportedData memory _reportedData
                    ) internal view returns (
                        uint256 etherToLock, uint256 sharesToBurn
                    ) {
                        IWithdrawalQueue withdrawalQueue = IWithdrawalQueue(_contracts.withdrawalQueue);
                        if (!withdrawalQueue.isPaused()) {
                            IOracleReportSanityChecker(_contracts.oracleReportSanityChecker).checkWithdrawalQueueOracleReport(
                                _reportedData.withdrawalFinalizationBatches[_reportedData.withdrawalFinalizationBatches.length - 1],
                                _reportedData.reportTimestamp
                            );
                            (etherToLock, sharesToBurn) = withdrawalQueue.prefinalize(
                                _reportedData.withdrawalFinalizationBatches,
                                _reportedData.simulatedShareRate
                            );
                        }
                    }
                    /**
                     * @dev calculate the amount of rewards and distribute it
                     */
                    function _processRewards(
                        OracleReportContext memory _reportContext,
                        uint256 _postCLBalance,
                        uint256 _withdrawnWithdrawals,
                        uint256 _withdrawnElRewards
                    ) internal returns (uint256 sharesMintedAsFees) {
                        uint256 postCLTotalBalance = _postCLBalance.add(_withdrawnWithdrawals);
                        // Don’t mint/distribute any protocol fee on the non-profitable Lido oracle report
                        // (when consensus layer balance delta is zero or negative).
                        // See LIP-12 for details:
                        // https://research.lido.fi/t/lip-12-on-chain-part-of-the-rewards-distribution-after-the-merge/1625
                        if (postCLTotalBalance > _reportContext.preCLBalance) {
                            uint256 consensusLayerRewards = postCLTotalBalance - _reportContext.preCLBalance;
                            sharesMintedAsFees = _distributeFee(
                                _reportContext.preTotalPooledEther,
                                _reportContext.preTotalShares,
                                consensusLayerRewards.add(_withdrawnElRewards)
                            );
                        }
                    }
                    /**
                     * @dev Process user deposit, mints liquid tokens and increase the pool buffer
                     * @param _referral address of referral.
                     * @return amount of StETH shares generated
                     */
                    function _submit(address _referral) internal returns (uint256) {
                        require(msg.value != 0, "ZERO_DEPOSIT");
                        StakeLimitState.Data memory stakeLimitData = STAKING_STATE_POSITION.getStorageStakeLimitStruct();
                        // There is an invariant that protocol pause also implies staking pause.
                        // Thus, no need to check protocol pause explicitly.
                        require(!stakeLimitData.isStakingPaused(), "STAKING_PAUSED");
                        if (stakeLimitData.isStakingLimitSet()) {
                            uint256 currentStakeLimit = stakeLimitData.calculateCurrentStakeLimit();
                            require(msg.value <= currentStakeLimit, "STAKE_LIMIT");
                            STAKING_STATE_POSITION.setStorageStakeLimitStruct(stakeLimitData.updatePrevStakeLimit(currentStakeLimit - msg.value));
                        }
                        uint256 sharesAmount = getSharesByPooledEth(msg.value);
                        _mintShares(msg.sender, sharesAmount);
                        _setBufferedEther(_getBufferedEther().add(msg.value));
                        emit Submitted(msg.sender, msg.value, _referral);
                        _emitTransferAfterMintingShares(msg.sender, sharesAmount);
                        return sharesAmount;
                    }
                    /**
                     * @dev Staking router rewards distribution.
                     *
                     * Corresponds to the return value of `IStakingRouter.newTotalPooledEtherForRewards()`
                     * Prevents `stack too deep` issue.
                     */
                    struct StakingRewardsDistribution {
                        address[] recipients;
                        uint256[] moduleIds;
                        uint96[] modulesFees;
                        uint96 totalFee;
                        uint256 precisionPoints;
                    }
                    /**
                     * @dev Get staking rewards distribution from staking router.
                     */
                    function _getStakingRewardsDistribution() internal view returns (
                        StakingRewardsDistribution memory ret,
                        IStakingRouter router
                    ) {
                        router = _stakingRouter();
                        (
                            ret.recipients,
                            ret.moduleIds,
                            ret.modulesFees,
                            ret.totalFee,
                            ret.precisionPoints
                        ) = router.getStakingRewardsDistribution();
                        require(ret.recipients.length == ret.modulesFees.length, "WRONG_RECIPIENTS_INPUT");
                        require(ret.moduleIds.length == ret.modulesFees.length, "WRONG_MODULE_IDS_INPUT");
                    }
                    /**
                     * @dev Distributes fee portion of the rewards by minting and distributing corresponding amount of liquid tokens.
                     * @param _preTotalPooledEther Total supply before report-induced changes applied
                     * @param _preTotalShares Total shares before report-induced changes applied
                     * @param _totalRewards Total rewards accrued both on the Execution Layer and the Consensus Layer sides in wei.
                     */
                    function _distributeFee(
                        uint256 _preTotalPooledEther,
                        uint256 _preTotalShares,
                        uint256 _totalRewards
                    ) internal returns (uint256 sharesMintedAsFees) {
                        // We need to take a defined percentage of the reported reward as a fee, and we do
                        // this by minting new token shares and assigning them to the fee recipients (see
                        // StETH docs for the explanation of the shares mechanics). The staking rewards fee
                        // is defined in basis points (1 basis point is equal to 0.01%, 10000 (TOTAL_BASIS_POINTS) is 100%).
                        //
                        // Since we are increasing totalPooledEther by _totalRewards (totalPooledEtherWithRewards),
                        // the combined cost of all holders' shares has became _totalRewards StETH tokens more,
                        // effectively splitting the reward between each token holder proportionally to their token share.
                        //
                        // Now we want to mint new shares to the fee recipient, so that the total cost of the
                        // newly-minted shares exactly corresponds to the fee taken:
                        //
                        // totalPooledEtherWithRewards = _preTotalPooledEther + _totalRewards
                        // shares2mint * newShareCost = (_totalRewards * totalFee) / PRECISION_POINTS
                        // newShareCost = totalPooledEtherWithRewards / (_preTotalShares + shares2mint)
                        //
                        // which follows to:
                        //
                        //                        _totalRewards * totalFee * _preTotalShares
                        // shares2mint = --------------------------------------------------------------
                        //                 (totalPooledEtherWithRewards * PRECISION_POINTS) - (_totalRewards * totalFee)
                        //
                        // The effect is that the given percentage of the reward goes to the fee recipient, and
                        // the rest of the reward is distributed between token holders proportionally to their
                        // token shares.
                        (
                            StakingRewardsDistribution memory rewardsDistribution,
                            IStakingRouter router
                        ) = _getStakingRewardsDistribution();
                        if (rewardsDistribution.totalFee > 0) {
                            uint256 totalPooledEtherWithRewards = _preTotalPooledEther.add(_totalRewards);
                            sharesMintedAsFees =
                                _totalRewards.mul(rewardsDistribution.totalFee).mul(_preTotalShares).div(
                                    totalPooledEtherWithRewards.mul(
                                        rewardsDistribution.precisionPoints
                                    ).sub(_totalRewards.mul(rewardsDistribution.totalFee))
                                );
                            _mintShares(address(this), sharesMintedAsFees);
                            (uint256[] memory moduleRewards, uint256 totalModuleRewards) =
                                _transferModuleRewards(
                                    rewardsDistribution.recipients,
                                    rewardsDistribution.modulesFees,
                                    rewardsDistribution.totalFee,
                                    sharesMintedAsFees
                                );
                            _transferTreasuryRewards(sharesMintedAsFees.sub(totalModuleRewards));
                            router.reportRewardsMinted(
                                rewardsDistribution.moduleIds,
                                moduleRewards
                            );
                        }
                    }
                    function _transferModuleRewards(
                        address[] memory recipients,
                        uint96[] memory modulesFees,
                        uint256 totalFee,
                        uint256 totalRewards
                    ) internal returns (uint256[] memory moduleRewards, uint256 totalModuleRewards) {
                        moduleRewards = new uint256[](recipients.length);
                        for (uint256 i; i < recipients.length; ++i) {
                            if (modulesFees[i] > 0) {
                                uint256 iModuleRewards = totalRewards.mul(modulesFees[i]).div(totalFee);
                                moduleRewards[i] = iModuleRewards;
                                _transferShares(address(this), recipients[i], iModuleRewards);
                                _emitTransferAfterMintingShares(recipients[i], iModuleRewards);
                                totalModuleRewards = totalModuleRewards.add(iModuleRewards);
                            }
                        }
                    }
                    function _transferTreasuryRewards(uint256 treasuryReward) internal {
                        address treasury = _treasury();
                        _transferShares(address(this), treasury, treasuryReward);
                        _emitTransferAfterMintingShares(treasury, treasuryReward);
                    }
                    /**
                     * @dev Gets the amount of Ether temporary buffered on this contract balance
                     */
                    function _getBufferedEther() internal view returns (uint256) {
                        return BUFFERED_ETHER_POSITION.getStorageUint256();
                    }
                    function _setBufferedEther(uint256 _newBufferedEther) internal {
                        BUFFERED_ETHER_POSITION.setStorageUint256(_newBufferedEther);
                    }
                    /// @dev Calculates and returns the total base balance (multiple of 32) of validators in transient state,
                    ///     i.e. submitted to the official Deposit contract but not yet visible in the CL state.
                    /// @return transient balance in wei (1e-18 Ether)
                    function _getTransientBalance() internal view returns (uint256) {
                        uint256 depositedValidators = DEPOSITED_VALIDATORS_POSITION.getStorageUint256();
                        uint256 clValidators = CL_VALIDATORS_POSITION.getStorageUint256();
                        // clValidators can never be less than deposited ones.
                        assert(depositedValidators >= clValidators);
                        return (depositedValidators - clValidators).mul(DEPOSIT_SIZE);
                    }
                    /**
                     * @dev Gets the total amount of Ether controlled by the system
                     * @return total balance in wei
                     */
                    function _getTotalPooledEther() internal view returns (uint256) {
                        return _getBufferedEther()
                            .add(CL_BALANCE_POSITION.getStorageUint256())
                            .add(_getTransientBalance());
                    }
                    function _pauseStaking() internal {
                        STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                            STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakeLimitPauseState(true)
                        );
                        emit StakingPaused();
                    }
                    function _resumeStaking() internal {
                        STAKING_STATE_POSITION.setStorageStakeLimitStruct(
                            STAKING_STATE_POSITION.getStorageStakeLimitStruct().setStakeLimitPauseState(false)
                        );
                        emit StakingResumed();
                    }
                    function _getCurrentStakeLimit(StakeLimitState.Data memory _stakeLimitData) internal view returns (uint256) {
                        if (_stakeLimitData.isStakingPaused()) {
                            return 0;
                        }
                        if (!_stakeLimitData.isStakingLimitSet()) {
                            return uint256(-1);
                        }
                        return _stakeLimitData.calculateCurrentStakeLimit();
                    }
                    /**
                     * @dev Size-efficient analog of the `auth(_role)` modifier
                     * @param _role Permission name
                     */
                    function _auth(bytes32 _role) internal view {
                        require(canPerform(msg.sender, _role, new uint256[](0)), "APP_AUTH_FAILED");
                    }
                    /**
                     * @dev Intermediate data structure for `_handleOracleReport`
                     * Helps to overcome `stack too deep` issue.
                     */
                    struct OracleReportContext {
                        uint256 preCLValidators;
                        uint256 preCLBalance;
                        uint256 preTotalPooledEther;
                        uint256 preTotalShares;
                        uint256 etherToLockOnWithdrawalQueue;
                        uint256 sharesToBurnFromWithdrawalQueue;
                        uint256 simulatedSharesToBurn;
                        uint256 sharesToBurn;
                        uint256 sharesMintedAsFees;
                    }
                    /**
                     * @dev Handle oracle report method operating with the data-packed structs
                     * Using structs helps to overcome 'stack too deep' issue.
                     *
                     * The method updates the protocol's accounting state.
                     * Key steps:
                     * 1. Take a snapshot of the current (pre-) state
                     * 2. Pass the report data to sanity checker (reverts if malformed)
                     * 3. Pre-calculate the ether to lock for withdrawal queue and shares to be burnt
                     * 4. Pass the accounting values to sanity checker to smoothen positive token rebase
                     *    (i.e., postpone the extra rewards to be applied during the next rounds)
                     * 5. Invoke finalization of the withdrawal requests
                     * 6. Burn excess shares within the allowed limit (can postpone some shares to be burnt later)
                     * 7. Distribute protocol fee (treasury & node operators)
                     * 8. Complete token rebase by informing observers (emit an event and call the external receivers if any)
                     * 9. Sanity check for the provided simulated share rate
                     */
                    function _handleOracleReport(OracleReportedData memory _reportedData) internal returns (uint256[4]) {
                        OracleReportContracts memory contracts = _loadOracleReportContracts();
                        require(msg.sender == contracts.accountingOracle, "APP_AUTH_FAILED");
                        require(_reportedData.reportTimestamp <= block.timestamp, "INVALID_REPORT_TIMESTAMP");
                        OracleReportContext memory reportContext;
                        // Step 1.
                        // Take a snapshot of the current (pre-) state
                        reportContext.preTotalPooledEther = _getTotalPooledEther();
                        reportContext.preTotalShares = _getTotalShares();
                        reportContext.preCLValidators = CL_VALIDATORS_POSITION.getStorageUint256();
                        reportContext.preCLBalance = _processClStateUpdate(
                            _reportedData.reportTimestamp,
                            reportContext.preCLValidators,
                            _reportedData.clValidators,
                            _reportedData.postCLBalance
                        );
                        // Step 2.
                        // Pass the report data to sanity checker (reverts if malformed)
                        _checkAccountingOracleReport(contracts, _reportedData, reportContext);
                        // Step 3.
                        // Pre-calculate the ether to lock for withdrawal queue and shares to be burnt
                        // due to withdrawal requests to finalize
                        if (_reportedData.withdrawalFinalizationBatches.length != 0) {
                            (
                                reportContext.etherToLockOnWithdrawalQueue,
                                reportContext.sharesToBurnFromWithdrawalQueue
                            ) = _calculateWithdrawals(contracts, _reportedData);
                            if (reportContext.sharesToBurnFromWithdrawalQueue > 0) {
                                IBurner(contracts.burner).requestBurnShares(
                                    contracts.withdrawalQueue,
                                    reportContext.sharesToBurnFromWithdrawalQueue
                                );
                            }
                        }
                        // Step 4.
                        // Pass the accounting values to sanity checker to smoothen positive token rebase
                        uint256 withdrawals;
                        uint256 elRewards;
                        (
                            withdrawals, elRewards, reportContext.simulatedSharesToBurn, reportContext.sharesToBurn
                        ) = IOracleReportSanityChecker(contracts.oracleReportSanityChecker).smoothenTokenRebase(
                            reportContext.preTotalPooledEther,
                            reportContext.preTotalShares,
                            reportContext.preCLBalance,
                            _reportedData.postCLBalance,
                            _reportedData.withdrawalVaultBalance,
                            _reportedData.elRewardsVaultBalance,
                            _reportedData.sharesRequestedToBurn,
                            reportContext.etherToLockOnWithdrawalQueue,
                            reportContext.sharesToBurnFromWithdrawalQueue
                        );
                        // Step 5.
                        // Invoke finalization of the withdrawal requests (send ether to withdrawal queue, assign shares to be burnt)
                        _collectRewardsAndProcessWithdrawals(
                            contracts,
                            withdrawals,
                            elRewards,
                            _reportedData.withdrawalFinalizationBatches,
                            _reportedData.simulatedShareRate,
                            reportContext.etherToLockOnWithdrawalQueue
                        );
                        emit ETHDistributed(
                            _reportedData.reportTimestamp,
                            reportContext.preCLBalance,
                            _reportedData.postCLBalance,
                            withdrawals,
                            elRewards,
                            _getBufferedEther()
                        );
                        // Step 6.
                        // Burn the previously requested shares
                        if (reportContext.sharesToBurn > 0) {
                            IBurner(contracts.burner).commitSharesToBurn(reportContext.sharesToBurn);
                            _burnShares(contracts.burner, reportContext.sharesToBurn);
                        }
                        // Step 7.
                        // Distribute protocol fee (treasury & node operators)
                        reportContext.sharesMintedAsFees = _processRewards(
                            reportContext,
                            _reportedData.postCLBalance,
                            withdrawals,
                            elRewards
                        );
                        // Step 8.
                        // Complete token rebase by informing observers (emit an event and call the external receivers if any)
                        (
                            uint256 postTotalShares,
                            uint256 postTotalPooledEther
                        ) = _completeTokenRebase(
                            _reportedData,
                            reportContext,
                            IPostTokenRebaseReceiver(contracts.postTokenRebaseReceiver)
                        );
                        // Step 9. Sanity check for the provided simulated share rate
                        if (_reportedData.withdrawalFinalizationBatches.length != 0) {
                            IOracleReportSanityChecker(contracts.oracleReportSanityChecker).checkSimulatedShareRate(
                                postTotalPooledEther,
                                postTotalShares,
                                reportContext.etherToLockOnWithdrawalQueue,
                                reportContext.sharesToBurn.sub(reportContext.simulatedSharesToBurn),
                                _reportedData.simulatedShareRate
                            );
                        }
                        return [postTotalPooledEther, postTotalShares, withdrawals, elRewards];
                    }
                    /**
                     * @dev Pass the provided oracle data to the sanity checker contract
                     * Works with structures to overcome `stack too deep`
                     */
                    function _checkAccountingOracleReport(
                        OracleReportContracts memory _contracts,
                        OracleReportedData memory _reportedData,
                        OracleReportContext memory _reportContext
                    ) internal view {
                        IOracleReportSanityChecker(_contracts.oracleReportSanityChecker).checkAccountingOracleReport(
                            _reportedData.timeElapsed,
                            _reportContext.preCLBalance,
                            _reportedData.postCLBalance,
                            _reportedData.withdrawalVaultBalance,
                            _reportedData.elRewardsVaultBalance,
                            _reportedData.sharesRequestedToBurn,
                            _reportContext.preCLValidators,
                            _reportedData.clValidators
                        );
                    }
                    /**
                     * @dev Notify observers about the completed token rebase.
                     * Emit events and call external receivers.
                     */
                    function _completeTokenRebase(
                        OracleReportedData memory _reportedData,
                        OracleReportContext memory _reportContext,
                        IPostTokenRebaseReceiver _postTokenRebaseReceiver
                    ) internal returns (uint256 postTotalShares, uint256 postTotalPooledEther) {
                        postTotalShares = _getTotalShares();
                        postTotalPooledEther = _getTotalPooledEther();
                        if (_postTokenRebaseReceiver != address(0)) {
                            _postTokenRebaseReceiver.handlePostTokenRebase(
                                _reportedData.reportTimestamp,
                                _reportedData.timeElapsed,
                                _reportContext.preTotalShares,
                                _reportContext.preTotalPooledEther,
                                postTotalShares,
                                postTotalPooledEther,
                                _reportContext.sharesMintedAsFees
                            );
                        }
                        emit TokenRebased(
                            _reportedData.reportTimestamp,
                            _reportedData.timeElapsed,
                            _reportContext.preTotalShares,
                            _reportContext.preTotalPooledEther,
                            postTotalShares,
                            postTotalPooledEther,
                            _reportContext.sharesMintedAsFees
                        );
                    }
                    /**
                     * @dev Load the contracts used for `handleOracleReport` internally.
                     */
                    function _loadOracleReportContracts() internal view returns (OracleReportContracts memory ret) {
                        (
                            ret.accountingOracle,
                            ret.elRewardsVault,
                            ret.oracleReportSanityChecker,
                            ret.burner,
                            ret.withdrawalQueue,
                            ret.withdrawalVault,
                            ret.postTokenRebaseReceiver
                        ) = getLidoLocator().oracleReportComponentsForLido();
                    }
                    function _stakingRouter() internal view returns (IStakingRouter) {
                        return IStakingRouter(getLidoLocator().stakingRouter());
                    }
                    function _withdrawalQueue() internal view returns (IWithdrawalQueue) {
                        return IWithdrawalQueue(getLidoLocator().withdrawalQueue());
                    }
                    function _treasury() internal view returns (address) {
                        return getLidoLocator().treasury();
                    }
                    /**
                     * @notice Mints shares on behalf of 0xdead address,
                     * the shares amount is equal to the contract's balance.     *
                     *
                     * Allows to get rid of zero checks for `totalShares` and `totalPooledEther`
                     * and overcome corner cases.
                     *
                     * NB: reverts if the current contract's balance is zero.
                     *
                     * @dev must be invoked before using the token
                     */
                    function _bootstrapInitialHolder() internal {
                        uint256 balance = address(this).balance;
                        assert(balance != 0);
                        if (_getTotalShares() == 0) {
                            // if protocol is empty bootstrap it with the contract's balance
                            // address(0xdead) is a holder for initial shares
                            _setBufferedEther(balance);
                            // emitting `Submitted` before Transfer events to preserver events order in tx
                            emit Submitted(INITIAL_TOKEN_HOLDER, balance, 0);
                            _mintInitialShares(balance);
                        }
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                /* See contracts/COMPILERS.md */
                pragma solidity 0.4.24;
                import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                import "@aragon/os/contracts/lib/math/SafeMath.sol";
                import "./utils/Pausable.sol";
                /**
                 * @title Interest-bearing ERC20-like token for Lido Liquid Stacking protocol.
                 *
                 * This contract is abstract. To make the contract deployable override the
                 * `_getTotalPooledEther` function. `Lido.sol` contract inherits StETH and defines
                 * the `_getTotalPooledEther` function.
                 *
                 * StETH balances are dynamic and represent the holder's share in the total amount
                 * of Ether controlled by the protocol. Account shares aren't normalized, so the
                 * contract also stores the sum of all shares to calculate each account's token balance
                 * which equals to:
                 *
                 *   shares[account] * _getTotalPooledEther() / _getTotalShares()
                 *
                 * For example, assume that we have:
                 *
                 *   _getTotalPooledEther() -> 10 ETH
                 *   sharesOf(user1) -> 100
                 *   sharesOf(user2) -> 400
                 *
                 * Therefore:
                 *
                 *   balanceOf(user1) -> 2 tokens which corresponds 2 ETH
                 *   balanceOf(user2) -> 8 tokens which corresponds 8 ETH
                 *
                 * Since balances of all token holders change when the amount of total pooled Ether
                 * changes, this token cannot fully implement ERC20 standard: it only emits `Transfer`
                 * events upon explicit transfer between holders. In contrast, when total amount of
                 * pooled Ether increases, no `Transfer` events are generated: doing so would require
                 * emitting an event for each token holder and thus running an unbounded loop.
                 *
                 * The token inherits from `Pausable` and uses `whenNotStopped` modifier for methods
                 * which change `shares` or `allowances`. `_stop` and `_resume` functions are overridden
                 * in `Lido.sol` and might be called by an account with the `PAUSE_ROLE` assigned by the
                 * DAO. This is useful for emergency scenarios, e.g. a protocol bug, where one might want
                 * to freeze all token transfers and approvals until the emergency is resolved.
                 */
                contract StETH is IERC20, Pausable {
                    using SafeMath for uint256;
                    using UnstructuredStorage for bytes32;
                    address constant internal INITIAL_TOKEN_HOLDER = 0xdead;
                    uint256 constant internal INFINITE_ALLOWANCE = ~uint256(0);
                    /**
                     * @dev StETH balances are dynamic and are calculated based on the accounts' shares
                     * and the total amount of Ether controlled by the protocol. Account shares aren't
                     * normalized, so the contract also stores the sum of all shares to calculate
                     * each account's token balance which equals to:
                     *
                     *   shares[account] * _getTotalPooledEther() / _getTotalShares()
                    */
                    mapping (address => uint256) private shares;
                    /**
                     * @dev Allowances are nominated in tokens, not token shares.
                     */
                    mapping (address => mapping (address => uint256)) private allowances;
                    /**
                     * @dev Storage position used for holding the total amount of shares in existence.
                     *
                     * The Lido protocol is built on top of Aragon and uses the Unstructured Storage pattern
                     * for value types:
                     *
                     * https://blog.openzeppelin.com/upgradeability-using-unstructured-storage
                     * https://blog.8bitzen.com/posts/20-02-2020-understanding-how-solidity-upgradeable-unstructured-proxies-work
                     *
                     * For reference types, conventional storage variables are used since it's non-trivial
                     * and error-prone to implement reference-type unstructured storage using Solidity v0.4;
                     * see https://github.com/lidofinance/lido-dao/issues/181#issuecomment-736098834
                     *
                     * keccak256("lido.StETH.totalShares")
                     */
                    bytes32 internal constant TOTAL_SHARES_POSITION =
                        0xe3b4b636e601189b5f4c6742edf2538ac12bb61ed03e6da26949d69838fa447e;
                    /**
                      * @notice An executed shares transfer from `sender` to `recipient`.
                      *
                      * @dev emitted in pair with an ERC20-defined `Transfer` event.
                      */
                    event TransferShares(
                        address indexed from,
                        address indexed to,
                        uint256 sharesValue
                    );
                    /**
                     * @notice An executed `burnShares` request
                     *
                     * @dev Reports simultaneously burnt shares amount
                     * and corresponding stETH amount.
                     * The stETH amount is calculated twice: before and after the burning incurred rebase.
                     *
                     * @param account holder of the burnt shares
                     * @param preRebaseTokenAmount amount of stETH the burnt shares corresponded to before the burn
                     * @param postRebaseTokenAmount amount of stETH the burnt shares corresponded to after the burn
                     * @param sharesAmount amount of burnt shares
                     */
                    event SharesBurnt(
                        address indexed account,
                        uint256 preRebaseTokenAmount,
                        uint256 postRebaseTokenAmount,
                        uint256 sharesAmount
                    );
                    /**
                     * @return the name of the token.
                     */
                    function name() external pure returns (string) {
                        return "Liquid staked Ether 2.0";
                    }
                    /**
                     * @return the symbol of the token, usually a shorter version of the
                     * name.
                     */
                    function symbol() external pure returns (string) {
                        return "stETH";
                    }
                    /**
                     * @return the number of decimals for getting user representation of a token amount.
                     */
                    function decimals() external pure returns (uint8) {
                        return 18;
                    }
                    /**
                     * @return the amount of tokens in existence.
                     *
                     * @dev Always equals to `_getTotalPooledEther()` since token amount
                     * is pegged to the total amount of Ether controlled by the protocol.
                     */
                    function totalSupply() external view returns (uint256) {
                        return _getTotalPooledEther();
                    }
                    /**
                     * @return the entire amount of Ether controlled by the protocol.
                     *
                     * @dev The sum of all ETH balances in the protocol, equals to the total supply of stETH.
                     */
                    function getTotalPooledEther() external view returns (uint256) {
                        return _getTotalPooledEther();
                    }
                    /**
                     * @return the amount of tokens owned by the `_account`.
                     *
                     * @dev Balances are dynamic and equal the `_account`'s share in the amount of the
                     * total Ether controlled by the protocol. See `sharesOf`.
                     */
                    function balanceOf(address _account) external view returns (uint256) {
                        return getPooledEthByShares(_sharesOf(_account));
                    }
                    /**
                     * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account.
                     *
                     * @return a boolean value indicating whether the operation succeeded.
                     * Emits a `Transfer` event.
                     * Emits a `TransferShares` event.
                     *
                     * Requirements:
                     *
                     * - `_recipient` cannot be the zero address.
                     * - the caller must have a balance of at least `_amount`.
                     * - the contract must not be paused.
                     *
                     * @dev The `_amount` argument is the amount of tokens, not shares.
                     */
                    function transfer(address _recipient, uint256 _amount) external returns (bool) {
                        _transfer(msg.sender, _recipient, _amount);
                        return true;
                    }
                    /**
                     * @return the remaining number of tokens that `_spender` is allowed to spend
                     * on behalf of `_owner` through `transferFrom`. This is zero by default.
                     *
                     * @dev This value changes when `approve` or `transferFrom` is called.
                     */
                    function allowance(address _owner, address _spender) external view returns (uint256) {
                        return allowances[_owner][_spender];
                    }
                    /**
                     * @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens.
                     *
                     * @return a boolean value indicating whether the operation succeeded.
                     * Emits an `Approval` event.
                     *
                     * Requirements:
                     *
                     * - `_spender` cannot be the zero address.
                     *
                     * @dev The `_amount` argument is the amount of tokens, not shares.
                     */
                    function approve(address _spender, uint256 _amount) external returns (bool) {
                        _approve(msg.sender, _spender, _amount);
                        return true;
                    }
                    /**
                     * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
                     * allowance mechanism. `_amount` is then deducted from the caller's
                     * allowance.
                     *
                     * @return a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a `Transfer` event.
                     * Emits a `TransferShares` event.
                     * Emits an `Approval` event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `_sender` and `_recipient` cannot be the zero addresses.
                     * - `_sender` must have a balance of at least `_amount`.
                     * - the caller must have allowance for `_sender`'s tokens of at least `_amount`.
                     * - the contract must not be paused.
                     *
                     * @dev The `_amount` argument is the amount of tokens, not shares.
                     */
                    function transferFrom(address _sender, address _recipient, uint256 _amount) external returns (bool) {
                        _spendAllowance(_sender, msg.sender, _amount);
                        _transfer(_sender, _recipient, _amount);
                        return true;
                    }
                    /**
                     * @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`.
                     *
                     * This is an alternative to `approve` that can be used as a mitigation for
                     * problems described in:
                     * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b709eae01d1da91902d06ace340df6b324e6f049/contracts/token/ERC20/IERC20.sol#L57
                     * Emits an `Approval` event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `_spender` cannot be the the zero address.
                     */
                    function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) {
                        _approve(msg.sender, _spender, allowances[msg.sender][_spender].add(_addedValue));
                        return true;
                    }
                    /**
                     * @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`.
                     *
                     * This is an alternative to `approve` that can be used as a mitigation for
                     * problems described in:
                     * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b709eae01d1da91902d06ace340df6b324e6f049/contracts/token/ERC20/IERC20.sol#L57
                     * Emits an `Approval` event indicating the updated allowance.
                     *
                     * Requirements:
                     *
                     * - `_spender` cannot be the zero address.
                     * - `_spender` must have allowance for the caller of at least `_subtractedValue`.
                     */
                    function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) {
                        uint256 currentAllowance = allowances[msg.sender][_spender];
                        require(currentAllowance >= _subtractedValue, "ALLOWANCE_BELOW_ZERO");
                        _approve(msg.sender, _spender, currentAllowance.sub(_subtractedValue));
                        return true;
                    }
                    /**
                     * @return the total amount of shares in existence.
                     *
                     * @dev The sum of all accounts' shares can be an arbitrary number, therefore
                     * it is necessary to store it in order to calculate each account's relative share.
                     */
                    function getTotalShares() external view returns (uint256) {
                        return _getTotalShares();
                    }
                    /**
                     * @return the amount of shares owned by `_account`.
                     */
                    function sharesOf(address _account) external view returns (uint256) {
                        return _sharesOf(_account);
                    }
                    /**
                     * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled Ether.
                     */
                    function getSharesByPooledEth(uint256 _ethAmount) public view returns (uint256) {
                        return _ethAmount
                            .mul(_getTotalShares())
                            .div(_getTotalPooledEther());
                    }
                    /**
                     * @return the amount of Ether that corresponds to `_sharesAmount` token shares.
                     */
                    function getPooledEthByShares(uint256 _sharesAmount) public view returns (uint256) {
                        return _sharesAmount
                            .mul(_getTotalPooledEther())
                            .div(_getTotalShares());
                    }
                    /**
                     * @notice Moves `_sharesAmount` token shares from the caller's account to the `_recipient` account.
                     *
                     * @return amount of transferred tokens.
                     * Emits a `TransferShares` event.
                     * Emits a `Transfer` event.
                     *
                     * Requirements:
                     *
                     * - `_recipient` cannot be the zero address.
                     * - the caller must have at least `_sharesAmount` shares.
                     * - the contract must not be paused.
                     *
                     * @dev The `_sharesAmount` argument is the amount of shares, not tokens.
                     */
                    function transferShares(address _recipient, uint256 _sharesAmount) external returns (uint256) {
                        _transferShares(msg.sender, _recipient, _sharesAmount);
                        uint256 tokensAmount = getPooledEthByShares(_sharesAmount);
                        _emitTransferEvents(msg.sender, _recipient, tokensAmount, _sharesAmount);
                        return tokensAmount;
                    }
                    /**
                     * @notice Moves `_sharesAmount` token shares from the `_sender` account to the `_recipient` account.
                     *
                     * @return amount of transferred tokens.
                     * Emits a `TransferShares` event.
                     * Emits a `Transfer` event.
                     *
                     * Requirements:
                     *
                     * - `_sender` and `_recipient` cannot be the zero addresses.
                     * - `_sender` must have at least `_sharesAmount` shares.
                     * - the caller must have allowance for `_sender`'s tokens of at least `getPooledEthByShares(_sharesAmount)`.
                     * - the contract must not be paused.
                     *
                     * @dev The `_sharesAmount` argument is the amount of shares, not tokens.
                     */
                    function transferSharesFrom(
                        address _sender, address _recipient, uint256 _sharesAmount
                    ) external returns (uint256) {
                        uint256 tokensAmount = getPooledEthByShares(_sharesAmount);
                        _spendAllowance(_sender, msg.sender, tokensAmount);
                        _transferShares(_sender, _recipient, _sharesAmount);
                        _emitTransferEvents(_sender, _recipient, tokensAmount, _sharesAmount);
                        return tokensAmount;
                    }
                    /**
                     * @return the total amount (in wei) of Ether controlled by the protocol.
                     * @dev This is used for calculating tokens from shares and vice versa.
                     * @dev This function is required to be implemented in a derived contract.
                     */
                    function _getTotalPooledEther() internal view returns (uint256);
                    /**
                     * @notice Moves `_amount` tokens from `_sender` to `_recipient`.
                     * Emits a `Transfer` event.
                     * Emits a `TransferShares` event.
                     */
                    function _transfer(address _sender, address _recipient, uint256 _amount) internal {
                        uint256 _sharesToTransfer = getSharesByPooledEth(_amount);
                        _transferShares(_sender, _recipient, _sharesToTransfer);
                        _emitTransferEvents(_sender, _recipient, _amount, _sharesToTransfer);
                    }
                    /**
                     * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens.
                     *
                     * Emits an `Approval` event.
                     *
                     * NB: the method can be invoked even if the protocol paused.
                     *
                     * Requirements:
                     *
                     * - `_owner` cannot be the zero address.
                     * - `_spender` cannot be the zero address.
                     */
                    function _approve(address _owner, address _spender, uint256 _amount) internal {
                        require(_owner != address(0), "APPROVE_FROM_ZERO_ADDR");
                        require(_spender != address(0), "APPROVE_TO_ZERO_ADDR");
                        allowances[_owner][_spender] = _amount;
                        emit Approval(_owner, _spender, _amount);
                    }
                    /**
                     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                     *
                     * Does not update the allowance amount in case of infinite allowance.
                     * Revert if not enough allowance is available.
                     *
                     * Might emit an {Approval} event.
                     */
                    function _spendAllowance(address _owner, address _spender, uint256 _amount) internal {
                        uint256 currentAllowance = allowances[_owner][_spender];
                        if (currentAllowance != INFINITE_ALLOWANCE) {
                            require(currentAllowance >= _amount, "ALLOWANCE_EXCEEDED");
                            _approve(_owner, _spender, currentAllowance - _amount);
                        }
                    }
                    /**
                     * @return the total amount of shares in existence.
                     */
                    function _getTotalShares() internal view returns (uint256) {
                        return TOTAL_SHARES_POSITION.getStorageUint256();
                    }
                    /**
                     * @return the amount of shares owned by `_account`.
                     */
                    function _sharesOf(address _account) internal view returns (uint256) {
                        return shares[_account];
                    }
                    /**
                     * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.
                     *
                     * Requirements:
                     *
                     * - `_sender` cannot be the zero address.
                     * - `_recipient` cannot be the zero address or the `stETH` token contract itself
                     * - `_sender` must hold at least `_sharesAmount` shares.
                     * - the contract must not be paused.
                     */
                    function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal {
                        require(_sender != address(0), "TRANSFER_FROM_ZERO_ADDR");
                        require(_recipient != address(0), "TRANSFER_TO_ZERO_ADDR");
                        require(_recipient != address(this), "TRANSFER_TO_STETH_CONTRACT");
                        _whenNotStopped();
                        uint256 currentSenderShares = shares[_sender];
                        require(_sharesAmount <= currentSenderShares, "BALANCE_EXCEEDED");
                        shares[_sender] = currentSenderShares.sub(_sharesAmount);
                        shares[_recipient] = shares[_recipient].add(_sharesAmount);
                    }
                    /**
                     * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
                     * @dev This doesn't increase the token total supply.
                     *
                     * NB: The method doesn't check protocol pause relying on the external enforcement.
                     *
                     * Requirements:
                     *
                     * - `_recipient` cannot be the zero address.
                     * - the contract must not be paused.
                     */
                    function _mintShares(address _recipient, uint256 _sharesAmount) internal returns (uint256 newTotalShares) {
                        require(_recipient != address(0), "MINT_TO_ZERO_ADDR");
                        newTotalShares = _getTotalShares().add(_sharesAmount);
                        TOTAL_SHARES_POSITION.setStorageUint256(newTotalShares);
                        shares[_recipient] = shares[_recipient].add(_sharesAmount);
                        // Notice: we're not emitting a Transfer event from the zero address here since shares mint
                        // works by taking the amount of tokens corresponding to the minted shares from all other
                        // token holders, proportionally to their share. The total supply of the token doesn't change
                        // as the result. This is equivalent to performing a send from each other token holder's
                        // address to `address`, but we cannot reflect this as it would require sending an unbounded
                        // number of events.
                    }
                    /**
                     * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
                     * @dev This doesn't decrease the token total supply.
                     *
                     * Requirements:
                     *
                     * - `_account` cannot be the zero address.
                     * - `_account` must hold at least `_sharesAmount` shares.
                     * - the contract must not be paused.
                     */
                    function _burnShares(address _account, uint256 _sharesAmount) internal returns (uint256 newTotalShares) {
                        require(_account != address(0), "BURN_FROM_ZERO_ADDR");
                        uint256 accountShares = shares[_account];
                        require(_sharesAmount <= accountShares, "BALANCE_EXCEEDED");
                        uint256 preRebaseTokenAmount = getPooledEthByShares(_sharesAmount);
                        newTotalShares = _getTotalShares().sub(_sharesAmount);
                        TOTAL_SHARES_POSITION.setStorageUint256(newTotalShares);
                        shares[_account] = accountShares.sub(_sharesAmount);
                        uint256 postRebaseTokenAmount = getPooledEthByShares(_sharesAmount);
                        emit SharesBurnt(_account, preRebaseTokenAmount, postRebaseTokenAmount, _sharesAmount);
                        // Notice: we're not emitting a Transfer event to the zero address here since shares burn
                        // works by redistributing the amount of tokens corresponding to the burned shares between
                        // all other token holders. The total supply of the token doesn't change as the result.
                        // This is equivalent to performing a send from `address` to each other token holder address,
                        // but we cannot reflect this as it would require sending an unbounded number of events.
                        // We're emitting `SharesBurnt` event to provide an explicit rebase log record nonetheless.
                    }
                    /**
                     * @dev Emits {Transfer} and {TransferShares} events
                     */
                    function _emitTransferEvents(address _from, address _to, uint _tokenAmount, uint256 _sharesAmount) internal {
                        emit Transfer(_from, _to, _tokenAmount);
                        emit TransferShares(_from, _to, _sharesAmount);
                    }
                    /**
                     * @dev Emits {Transfer} and {TransferShares} events where `from` is 0 address. Indicates mint events.
                     */
                    function _emitTransferAfterMintingShares(address _to, uint256 _sharesAmount) internal {
                        _emitTransferEvents(address(0), _to, getPooledEthByShares(_sharesAmount), _sharesAmount);
                    }
                    /**
                     * @dev Mints shares to INITIAL_TOKEN_HOLDER
                     */
                    function _mintInitialShares(uint256 _sharesAmount) internal {
                        _mintShares(INITIAL_TOKEN_HOLDER, _sharesAmount);
                        _emitTransferAfterMintingShares(INITIAL_TOKEN_HOLDER, _sharesAmount);
                    }
                }
                // SPDX-FileCopyrightText: 2023 OpenZeppelin, Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                /* See contracts/COMPILERS.md */
                pragma solidity 0.4.24;
                import {UnstructuredStorage} from "@aragon/os/contracts/common/UnstructuredStorage.sol";
                import {SignatureUtils} from "../common/lib/SignatureUtils.sol";
                import {IEIP712StETH} from "../common/interfaces/IEIP712StETH.sol";
                import {StETH} from "./StETH.sol";
                /**
                 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                 *
                 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                 * need to send a transaction, and thus is not required to hold Ether at all.
                 */
                interface IERC2612 {
                    /**
                     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                     * given ``owner``'s signed approval.
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `deadline` must be a timestamp in the future.
                     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                     * over the EIP712-formatted function arguments.
                     * - the signature must use ``owner``'s current nonce (see {nonces}).
                     */
                    function permit(
                        address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s
                    ) external;
                    /**
                     * @dev Returns the current nonce for `owner`. This value must be
                     * included whenever a signature is generated for {permit}.
                     *
                     * Every successful call to {permit} increases ``owner``'s nonce by one. This
                     * prevents a signature from being used multiple times.
                     */
                    function nonces(address owner) external view returns (uint256);
                    /**
                     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                     */
                    // solhint-disable-next-line func-name-mixedcase
                    function DOMAIN_SEPARATOR() external view returns (bytes32);
                }
                contract StETHPermit is IERC2612, StETH {
                    using UnstructuredStorage for bytes32;
                    /**
                     * @dev Service event for initialization
                     */
                    event EIP712StETHInitialized(address eip712StETH);
                    /**
                     * @dev Nonces for ERC-2612 (Permit)
                     */
                    mapping(address => uint256) internal noncesByAddress;
                    /**
                     * @dev Storage position used for the EIP712 message utils contract
                     *
                     * keccak256("lido.StETHPermit.eip712StETH")
                     */
                    bytes32 internal constant EIP712_STETH_POSITION =
                        0x42b2d95e1ce15ce63bf9a8d9f6312cf44b23415c977ffa3b884333422af8941c;
                    /**
                     * @dev Typehash constant for ERC-2612 (Permit)
                     *
                     * keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                     */
                    bytes32 internal constant PERMIT_TYPEHASH =
                        0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                    /**
                     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                     * given ``owner``'s signed approval.
                     * Emits an {Approval} event.
                     *
                     * Requirements:
                     *
                     * - `spender` cannot be the zero address.
                     * - `deadline` must be a timestamp in the future.
                     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                     * over the EIP712-formatted function arguments.
                     * - the signature must use ``owner``'s current nonce (see {nonces}).
                     */
                    function permit(
                        address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s
                    ) external {
                        require(block.timestamp <= _deadline, "DEADLINE_EXPIRED");
                        bytes32 structHash = keccak256(
                            abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, _useNonce(_owner), _deadline)
                        );
                        bytes32 hash = IEIP712StETH(getEIP712StETH()).hashTypedDataV4(address(this), structHash);
                        require(SignatureUtils.isValidSignature(_owner, hash, _v, _r, _s), "INVALID_SIGNATURE");
                        _approve(_owner, _spender, _value);
                    }
                    /**
                     * @dev Returns the current nonce for `owner`. This value must be
                     * included whenever a signature is generated for {permit}.
                     *
                     * Every successful call to {permit} increases ``owner``'s nonce by one. This
                     * prevents a signature from being used multiple times.
                     */
                    function nonces(address owner) external view returns (uint256) {
                        return noncesByAddress[owner];
                    }
                    /**
                     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                     */
                    // solhint-disable-next-line func-name-mixedcase
                    function DOMAIN_SEPARATOR() external view returns (bytes32) {
                        return IEIP712StETH(getEIP712StETH()).domainSeparatorV4(address(this));
                    }
                    /**
                     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
                     * signature.
                     *
                     * NB: compairing to the full-fledged ERC-5267 version:
                     * - `salt` and `extensions` are unused
                     * - `flags` is hex"0f" or 01111b
                     *
                     * @dev using shortened returns to reduce a bytecode size
                     */
                    function eip712Domain() external view returns (
                        string memory name,
                        string memory version,
                        uint256 chainId,
                        address verifyingContract
                    ) {
                        return IEIP712StETH(getEIP712StETH()).eip712Domain(address(this));
                    }
                    /**
                     * @dev "Consume a nonce": return the current value and increment.
                     */
                    function _useNonce(address _owner) internal returns (uint256 current) {
                        current = noncesByAddress[_owner];
                        noncesByAddress[_owner] = current.add(1);
                    }
                    /**
                     * @dev Initialize EIP712 message utils contract for stETH
                     */
                    function _initializeEIP712StETH(address _eip712StETH) internal {
                        require(_eip712StETH != address(0), "ZERO_EIP712STETH");
                        require(getEIP712StETH() == address(0), "EIP712STETH_ALREADY_SET");
                        EIP712_STETH_POSITION.setStorageAddress(_eip712StETH);
                        emit EIP712StETHInitialized(_eip712StETH);
                    }
                    /**
                     * @dev Get EIP712 message utils contract
                     */
                    function getEIP712StETH() public view returns (address) {
                        return EIP712_STETH_POSITION.getStorageAddress();
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity 0.4.24;
                import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                contract Pausable {
                    using UnstructuredStorage for bytes32;
                    event Stopped();
                    event Resumed();
                    // keccak256("lido.Pausable.activeFlag")
                    bytes32 internal constant ACTIVE_FLAG_POSITION =
                        0x644132c4ddd5bb6f0655d5fe2870dcec7870e6be4758890f366b83441f9fdece;
                    function _whenNotStopped() internal view {
                        require(ACTIVE_FLAG_POSITION.getStorageBool(), "CONTRACT_IS_STOPPED");
                    }
                    function _whenStopped() internal view {
                        require(!ACTIVE_FLAG_POSITION.getStorageBool(), "CONTRACT_IS_ACTIVE");
                    }
                    function isStopped() public view returns (bool) {
                        return !ACTIVE_FLAG_POSITION.getStorageBool();
                    }
                    function _stop() internal {
                        _whenNotStopped();
                        ACTIVE_FLAG_POSITION.setStorageBool(false);
                        emit Stopped();
                    }
                    function _resume() internal {
                        _whenStopped();
                        ACTIVE_FLAG_POSITION.setStorageBool(true);
                        emit Resumed();
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity 0.4.24;
                import "@aragon/os/contracts/common/UnstructuredStorage.sol";
                /**
                 * @title Adapted code of /contracts/0.8.9/utils/Versioned.sol
                 *
                 * This contract contains only core part of original Versioned.sol
                 * to reduce contract size
                 */
                contract Versioned {
                    using UnstructuredStorage for bytes32;
                    event ContractVersionSet(uint256 version);
                    /// @dev Storage slot: uint256 version
                    /// Version of the initialized contract storage.
                    /// The version stored in CONTRACT_VERSION_POSITION equals to:
                    /// - 0 right after the deployment, before an initializer is invoked (and only at that moment);
                    /// - N after calling initialize(), where N is the initially deployed contract version;
                    /// - N after upgrading contract by calling finalizeUpgrade_vN().
                    bytes32 internal constant CONTRACT_VERSION_POSITION =
                        0x4dd0f6662ba1d6b081f08b350f5e9a6a7b15cf586926ba66f753594928fa64a6; // keccak256("lido.Versioned.contractVersion");
                    uint256 internal constant PETRIFIED_VERSION_MARK = uint256(-1);
                    constructor() public {
                        // lock version in the implementation's storage to prevent initialization
                        CONTRACT_VERSION_POSITION.setStorageUint256(PETRIFIED_VERSION_MARK);
                    }
                    /// @notice Returns the current contract version.
                    function getContractVersion() public view returns (uint256) {
                        return CONTRACT_VERSION_POSITION.getStorageUint256();
                    }
                    function _checkContractVersion(uint256 version) internal view {
                        require(version == getContractVersion(), "UNEXPECTED_CONTRACT_VERSION");
                    }
                    function _setContractVersion(uint256 version) internal {
                        CONTRACT_VERSION_POSITION.setStorageUint256(version);
                        emit ContractVersionSet(version);
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                // See contracts/COMPILERS.md
                // solhint-disable-next-line
                pragma solidity >=0.4.24 <0.9.0;
                interface IBurner {
                    /**
                     * Commit cover/non-cover burning requests and logs cover/non-cover shares amount just burnt.
                     *
                     * NB: The real burn enactment to be invoked after the call (via internal Lido._burnShares())
                     */
                    function commitSharesToBurn(uint256 _stETHSharesToBurn) external;
                    /**
                     * Request burn shares
                     */
                    function requestBurnShares(address _from, uint256 _sharesAmount) external;
                    /**
                      * Returns the current amount of shares locked on the contract to be burnt.
                      */
                    function getSharesRequestedToBurn() external view returns (uint256 coverShares, uint256 nonCoverShares);
                    /**
                      * Returns the total cover shares ever burnt.
                      */
                    function getCoverSharesBurnt() external view returns (uint256);
                    /**
                      * Returns the total non-cover shares ever burnt.
                      */
                    function getNonCoverSharesBurnt() external view returns (uint256);
                }
                // SPDX-FileCopyrightText: 2023 OpenZeppelin, Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                // See contracts/COMPILERS.md
                // solhint-disable-next-line
                pragma solidity >=0.4.24 <0.9.0;
                /**
                 * @dev Helper interface of EIP712 StETH-dedicated helper.
                 *
                 * Has an access to the CHAIN_ID opcode and relies on immutables internally
                 * Both are unavailable for Solidity 0.4.24.
                 */
                interface IEIP712StETH {
                    /**
                     * @dev Returns the domain separator for the current chain.
                     */
                    function domainSeparatorV4(address _stETH) external view returns (bytes32);
                    /**
                     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                     * function returns the hash of the fully encoded EIP712 message for this domain.
                     *
                     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                     *
                     * ```solidity
                     * bytes32 digest = hashTypedDataV4(keccak256(abi.encode(
                     *     keccak256("Mail(address to,string contents)"),
                     *     mailTo,
                     *     keccak256(bytes(mailContents))
                     * )));
                     * address signer = ECDSA.recover(digest, signature);
                     * ```
                     */
                    function hashTypedDataV4(address _stETH, bytes32 _structHash) external view returns (bytes32);
                    /**
                     * @dev returns the fields and values that describe the domain separator
                     * used by stETH for EIP-712 signature.
                     */
                    function eip712Domain(address _stETH) external view returns (
                        string memory name,
                        string memory version,
                        uint256 chainId,
                        address verifyingContract
                    );
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: GPL-3.0
                // See contracts/COMPILERS.md
                // solhint-disable-next-line
                pragma solidity >=0.4.24 <0.9.0;
                interface ILidoLocator {
                    function accountingOracle() external view returns(address);
                    function depositSecurityModule() external view returns(address);
                    function elRewardsVault() external view returns(address);
                    function legacyOracle() external view returns(address);
                    function lido() external view returns(address);
                    function oracleReportSanityChecker() external view returns(address);
                    function burner() external view returns(address);
                    function stakingRouter() external view returns(address);
                    function treasury() external view returns(address);
                    function validatorsExitBusOracle() external view returns(address);
                    function withdrawalQueue() external view returns(address);
                    function withdrawalVault() external view returns(address);
                    function postTokenRebaseReceiver() external view returns(address);
                    function oracleDaemonConfig() external view returns(address);
                    function coreComponents() external view returns(
                        address elRewardsVault,
                        address oracleReportSanityChecker,
                        address stakingRouter,
                        address treasury,
                        address withdrawalQueue,
                        address withdrawalVault
                    );
                    function oracleReportComponentsForLido() external view returns(
                        address accountingOracle,
                        address elRewardsVault,
                        address oracleReportSanityChecker,
                        address burner,
                        address withdrawalQueue,
                        address withdrawalVault,
                        address postTokenRebaseReceiver
                    );
                }
                // SPDX-License-Identifier: MIT
                // Extracted from:
                // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/cryptography/ECDSA.sol#L53
                // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/541e821/contracts/utils/cryptography/ECDSA.sol#L112
                /* See contracts/COMPILERS.md */
                // solhint-disable-next-line
                pragma solidity >=0.4.24 <0.9.0;
                library ECDSA {
                    /**
                     * @dev Returns the address that signed a hashed message (`hash`).
                     * This address can then be used for verification purposes.
                     * Receives the `v`, `r` and `s` signature fields separately.
                     *
                     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                     * this function rejects them by requiring the `s` value to be in the lower
                     * half order, and the `v` value to be either 27 or 28.
                     *
                     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                     * verification to be secure: it is possible to craft signatures that
                     * recover to arbitrary addresses for non-hashed data.
                     */
                    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address)
                    {
                        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                        //
                        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                        // these malleable signatures as well.
                        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
                        // If the signature is valid (and not malleable), return the signer address
                        address signer = ecrecover(hash, v, r, s);
                        require(signer != address(0), "ECDSA: invalid signature");
                        return signer;
                    }
                    /**
                     * @dev Overload of `recover` that receives the `r` and `vs` short-signature fields separately.
                     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
                     */
                    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                        bytes32 s;
                        uint8 v;
                        assembly {
                            s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                            v := add(shr(255, vs), 27)
                        }
                        return recover(hash, v, r, s);
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: MIT
                // Copied from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0457042d93d9dfd760dbaa06a4d2f1216fdbe297/contracts/utils/math/Math.sol
                // See contracts/COMPILERS.md
                // solhint-disable-next-line
                pragma solidity >=0.4.24 <0.9.0;
                library Math256 {
                    /// @dev Returns the largest of two numbers.
                    function max(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a > b ? a : b;
                    }
                    /// @dev Returns the smallest of two numbers.
                    function min(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a < b ? a : b;
                    }
                    /// @dev Returns the largest of two numbers.
                    function max(int256 a, int256 b) internal pure returns (int256) {
                        return a > b ? a : b;
                    }
                    /// @dev Returns the smallest of two numbers.
                    function min(int256 a, int256 b) internal pure returns (int256) {
                        return a < b ? a : b;
                    }
                    /// @dev Returns the ceiling of the division of two numbers.
                    ///
                    /// This differs from standard division with `/` in that it rounds up instead
                    /// of rounding down.
                    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                        // (a + b - 1) / b can overflow on addition, so we distribute.
                        return a == 0 ? 0 : (a - 1) / b + 1;
                    }
                    /// @dev Returns absolute difference of two numbers.
                    function absDiff(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a > b ? a - b : b - a;
                    }
                }
                // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
                // SPDX-License-Identifier: MIT
                /* See contracts/COMPILERS.md */
                // solhint-disable-next-line lido/fixed-compiler-version
                pragma solidity >=0.4.24 <0.9.0;
                import {ECDSA} from "./ECDSA.sol";
                library SignatureUtils {
                    /**
                     * @dev The selector of the ERC1271's `isValidSignature(bytes32 hash, bytes signature)` function,
                     * serving at the same time as the magic value that the function should return upon success.
                     *
                     * See https://eips.ethereum.org/EIPS/eip-1271.
                     *
                     * bytes4(keccak256("isValidSignature(bytes32,bytes)")
                     */
                    bytes4 internal constant ERC1271_IS_VALID_SIGNATURE_SELECTOR = 0x1626ba7e;
                    /**
                     * @dev Checks signature validity.
                     *
                     * If the signer address doesn't contain any code, assumes that the address is externally owned
                     * and the signature is a ECDSA signature generated using its private key. Otherwise, issues a
                     * static call to the signer address to check the signature validity using the ERC-1271 standard.
                     */
                    function isValidSignature(
                        address signer,
                        bytes32 msgHash,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal view returns (bool) {
                        if (_hasCode(signer)) {
                            bytes memory sig = abi.encodePacked(r, s, v);
                            // Solidity <0.5 generates a regular CALL instruction even if the function being called
                            // is marked as `view`, and the only way to perform a STATICCALL is to use assembly
                            bytes memory data = abi.encodeWithSelector(ERC1271_IS_VALID_SIGNATURE_SELECTOR, msgHash, sig);
                            bytes32 retval;
                            /// @solidity memory-safe-assembly
                            assembly {
                                // allocate memory for storing the return value
                                let outDataOffset := mload(0x40)
                                mstore(0x40, add(outDataOffset, 32))
                                // issue a static call and load the result if the call succeeded
                                let success := staticcall(gas(), signer, add(data, 32), mload(data), outDataOffset, 32)
                                if and(eq(success, 1), eq(returndatasize(), 32)) {
                                    retval := mload(outDataOffset)
                                }
                            }
                            return retval == bytes32(ERC1271_IS_VALID_SIGNATURE_SELECTOR);
                        } else {
                            return ECDSA.recover(msgHash, v, r, s) == signer;
                        }
                    }
                    function _hasCode(address addr) internal view returns (bool) {
                        uint256 size;
                        /// @solidity memory-safe-assembly
                        assembly { size := extcodesize(addr) }
                        return size > 0;
                    }
                }
                pragma solidity ^0.4.24;
                /**
                 * @title ERC20 interface
                 * @dev see https://github.com/ethereum/EIPs/issues/20
                 */
                interface IERC20 {
                  function totalSupply() external view returns (uint256);
                  function balanceOf(address who) external view returns (uint256);
                  function allowance(address owner, address spender)
                    external view returns (uint256);
                  function transfer(address to, uint256 value) external returns (bool);
                  function approve(address spender, uint256 value)
                    external returns (bool);
                  function transferFrom(address from, address to, uint256 value)
                    external returns (bool);
                  event Transfer(
                    address indexed from,
                    address indexed to,
                    uint256 value
                  );
                  event Approval(
                    address indexed owner,
                    address indexed spender,
                    uint256 value
                  );
                }
                

                File 9 of 9: Minter
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                import {Stone} from "./Stone.sol";
                import {StoneVault} from "../StoneVault.sol";
                contract Minter {
                    address public stone;
                    address payable public vault;
                    modifier onlyVault() {
                        require(msg.sender == vault, "not vault");
                        _;
                    }
                    constructor(address _stone, address payable _vault) {
                        stone = _stone;
                        vault = _vault;
                    }
                    function mint(address _to, uint256 _amount) external onlyVault {
                        Stone(stone).mint(_to, _amount);
                    }
                    function burn(address _from, uint256 _amount) external onlyVault {
                        Stone(stone).burn(_from, _amount);
                    }
                    function setNewVault(address _vault) external onlyVault {
                        vault = payable(_vault);
                    }
                    function getTokenPrice() public returns (uint256 price) {
                        price = StoneVault(vault).currentSharePrice();
                    }
                }// SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                interface StoneVault {
                    function currentSharePrice() external returns (uint256 price);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity 0.8.21;
                interface Stone {
                    function mint(address _to, uint256 _amount) external;
                    function burn(address _from, uint256 _amount) external;
                }