ETH Price: $1,864.70 (-0.44%)

Transaction Decoder

Block:
20084460 at Jun-13-2024 05:42:35 PM +UTC
Transaction Fee:
0.008391375761270083 ETH $15.65
Gas Used:
588,443 Gas / 14.260303481 Gwei

Emitted Events:

182 WETH9.Deposit( dst=[Receiver] Zapper, wad=200000000000000000 )
183 WETH9.Transfer( src=[Receiver] Zapper, dst=UniswapV2Pair, wad=200000000000000000 )
184 ConvexToken.Transfer( from=UniswapV2Pair, to=[Receiver] Zapper, value=349366059636221192256 )
185 UniswapV2Pair.Sync( reserve0=102239941031938598220498, reserve1=58553247773971608428 )
186 UniswapV2Pair.Swap( sender=AugustusSwapper, amount0In=0, amount1In=200000000000000000, amount0Out=349366059636221192256, amount1Out=0, to=[Receiver] Zapper )
187 ConvexToken.Transfer( from=[Receiver] Zapper, to=WarMinter, value=349366059636221192256 )
188 ConvexToken.Approval( owner=[Receiver] Zapper, spender=WarMinter, value=115792089237316195423570985008687907853269984665640564038487551896549941043624 )
189 ConvexToken.Approval( owner=WarMinter, spender=WarCvxLocker, value=349366059636221192256 )
190 ConvexToken.Transfer( from=WarMinter, to=WarCvxLocker, value=349366059636221192256 )
191 ConvexToken.Approval( owner=WarMinter, spender=WarCvxLocker, value=0 )
192 ConvexToken.Approval( owner=WarCvxLocker, spender=CvxLockerV2, value=349366059636221192256 )
193 ConvexToken.Transfer( from=WarCvxLocker, to=CvxLockerV2, value=349366059636221192256 )
194 ConvexToken.Approval( owner=WarCvxLocker, spender=CvxLockerV2, value=0 )
195 CvxLockerV2.Staked( _user=WarCvxLocker, _epoch=1718841600, _paidAmount=349366059636221192256, _lockedAmount=349366059636221192256, _boostedAmount=349366059636221192256 )
196 WarToken.Transfer( from=0x0000000000000000000000000000000000000000, to=[Receiver] Zapper, amount=705460560214976368453 )
197 WarToken.Transfer( from=[Receiver] Zapper, to=Vault, amount=705460560214976368453 )
198 Vault.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0xe563b9d0533fec743e0ff867b7f3d1460f88798c, amount=670843963439359450714 )
199 Vault.Deposit( by=[Receiver] Zapper, owner=[Sender] 0xe563b9d0533fec743e0ff867b7f3d1460f88798c, assets=705460560214976368453, shares=670843963439359450714 )
200 WarToken.Transfer( from=Vault, to=WarStaker, amount=705460560214976368453 )
201 WarStaker.Transfer( from=0x0000000000000000000000000000000000000000, to=Vault, value=705460560214976368453 )
202 WarStaker.Staked( caller=Vault, receiver=Vault, amount=705460560214976368453 )
203 Zapper.Zapped( mintedAmount=705460560214976368453, receiver=[Sender] 0xe563b9d0533fec743e0ff867b7f3d1460f88798c )

Account State Difference:

  Address   Before After State Difference Code
0x05767d9E...8fb3dE906
0x2fc1E74B...d95ec27e9
(Titan Builder)
5.268332971179792245 Eth5.268362393329792245 Eth0.00002942215
0x4e3FBD56...9da5B9D2B
0x72a19342...5e32db86E
0xa8258deE...D74f0cbC1
0xA86c53AF...4B074758A
0xC02aaA39...83C756Cc2 2,907,077.236052585236184375 Eth2,907,077.436052585236184375 Eth0.2
0xe563b9d0...60f88798c
0.237223712531300271 Eth
Nonce: 7
0.028832336770030188 Eth
Nonce: 8
0.208391375761270083

Execution Trace

ETH 0.2 Zapper.zapEtherToSingleToken( vlToken=0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, receiver=0xe563b9d0533Fec743E0fF867B7F3D1460f88798c, callDatas=0x0B86A4C1000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000002C68AF0BB140000000000000000000000000000000000000000000000000011FE01B3351F27ECA4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A00000000000000000000000000000000000000000000000000000000000000001000000000000000000004DE505767D9EF41DC40689678FFCA0608878FB3DE906 )
  • ETH 0.2 WETH9.CALL( )
  • WETH9.allowance( 0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, 0x216B4B4Ba9F3e719726886d34a177484278Bfcae ) => ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 )
  • AugustusSwapper.0b86a4c1( )
    • NewUniswapV2Router.swapOnUniswapV2Fork( tokenIn=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, amountIn=200000000000000000, amountOutMin=331897756654410132644, weth=0x0000000000000000000000000000000000000000, pools=[29143835337400447479337820817104211716110314198919430] )
      • TokenTransferProxy.transferFrom( token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, from=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, to=0x05767d9EF41dC40689678fFca0608878fb3dE906, amount=200000000000000000 )
        • WETH9.transferFrom( src=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, dst=0x05767d9EF41dC40689678fFca0608878fb3dE906, wad=200000000000000000 ) => ( True )
        • UniswapV2Pair.STATICCALL( )
        • UniswapV2Pair.swap( amount0Out=349366059636221192256, amount1Out=0, to=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, data=0x )
          • ConvexToken.transfer( recipient=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, amount=349366059636221192256 ) => ( True )
          • ConvexToken.balanceOf( account=0x05767d9EF41dC40689678fFca0608878fb3dE906 ) => ( 102239941031938598220498 )
          • WETH9.balanceOf( 0x05767d9EF41dC40689678fFca0608878fb3dE906 ) => ( 58553247773971608428 )
          • ConvexToken.balanceOf( account=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578 ) => ( 349366059636221192256 )
          • WarMinter.mint( vlToken=0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, amount=349366059636221192256 )
            • ConvexToken.transferFrom( sender=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, recipient=0x144a689A8261F1863c89954930ecae46Bd950341, amount=349366059636221192256 ) => ( True )
            • ConvexToken.allowance( owner=0x144a689A8261F1863c89954930ecae46Bd950341, spender=0x700d6d24A55512c6AEC08820B49da4e4193105B3 ) => ( 0 )
            • ConvexToken.allowance( owner=0x144a689A8261F1863c89954930ecae46Bd950341, spender=0x700d6d24A55512c6AEC08820B49da4e4193105B3 ) => ( 0 )
            • ConvexToken.approve( spender=0x700d6d24A55512c6AEC08820B49da4e4193105B3, amount=349366059636221192256 ) => ( True )
            • WarCvxLocker.lock( amount=349366059636221192256 )
              • ConvexToken.transferFrom( sender=0x144a689A8261F1863c89954930ecae46Bd950341, recipient=0x700d6d24A55512c6AEC08820B49da4e4193105B3, amount=349366059636221192256 ) => ( True )
              • ConvexToken.allowance( owner=0x700d6d24A55512c6AEC08820B49da4e4193105B3, spender=0x72a19342e8F1838460eBFCCEf09F6585e32db86E ) => ( 0 )
              • ConvexToken.allowance( owner=0x700d6d24A55512c6AEC08820B49da4e4193105B3, spender=0x72a19342e8F1838460eBFCCEf09F6585e32db86E ) => ( 0 )
              • ConvexToken.approve( spender=0x72a19342e8F1838460eBFCCEf09F6585e32db86E, amount=349366059636221192256 ) => ( True )
              • CvxLockerV2.lock( _account=0x700d6d24A55512c6AEC08820B49da4e4193105B3, _amount=349366059636221192256, _spendRatio=0 )
                • ConvexToken.transferFrom( sender=0x700d6d24A55512c6AEC08820B49da4e4193105B3, recipient=0x72a19342e8F1838460eBFCCEf09F6585e32db86E, amount=349366059636221192256 ) => ( True )
                • ConvexToken.balanceOf( account=0x72a19342e8F1838460eBFCCEf09F6585e32db86E ) => ( 58386633810103663299283092 )
                • CvxStakingProxyV2.STATICCALL( )
                  • cvxRewardPool.balanceOf( account=0xb5BBC863BAFE5006c68613B89130812a7b586A4e ) => ( 0 )
                  • WarRatiosV2.getMintAmount( token=0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B, amount=349366059636221192256 ) => ( mintAmount=705460560214976368453 )
                  • WarToken.mint( to=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, amount=705460560214976368453 )
                  • WarToken.balanceOf( 0x1Ec2b9a77A7226ACD457954820197F89B3E3a578 ) => ( 705460560214976368453 )
                  • Vault.deposit( assets=705460560214976368453, receiver=0xe563b9d0533Fec743E0fF867B7F3D1460f88798c ) => ( shares=670843963439359450714 )
                    • WarStaker.balanceOf( account=0x2fc1E74BC8A6D15fE768c10C2EDe7D6d95ec27e9 ) => ( 58126284090534772896415 )
                    • WarToken.transferFrom( from=0x1Ec2b9a77A7226ACD457954820197F89B3E3a578, to=0x2fc1E74BC8A6D15fE768c10C2EDe7D6d95ec27e9, amount=705460560214976368453 ) => ( True )
                    • WarStaker.stake( amount=705460560214976368453, receiver=0x2fc1E74BC8A6D15fE768c10C2EDe7D6d95ec27e9 ) => ( 705460560214976368453 )
                      • WarToken.transferFrom( from=0x2fc1E74BC8A6D15fE768c10C2EDe7D6d95ec27e9, to=0xA86c53AF3aadF20bE5d7a8136ACfdbC4B074758A, amount=705460560214976368453 ) => ( True )
                      • WarCvxCrvFarmer.STATICCALL( )
                      • WarCvxCrvFarmer.STATICCALL( )
                      • WarAuraBalFarmer.STATICCALL( )
                      • WarAuraBalFarmer.STATICCALL( )
                        File 1 of 18: Zapper
                        // SPDX-License-Identifier: GPL-3.0-or-later
                        pragma solidity 0.8.24;
                        import { Errors } from "./utils/Errors.sol";
                        import { ERC20 } from "solmate/tokens/ERC20.sol";
                        import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                        import { IMinter } from "warlord/interfaces/IMinter.sol";
                        import { WETH9 } from "./interfaces/external/WETH.sol";
                        import { Allowance } from "../utils/Allowance.sol";
                        import { ERC4626 } from "solady/tokens/ERC4626.sol";
                        import { Owned2Step } from "../utils/Owned2Step.sol";
                        /**
                         * @title Zapper contract
                         * @dev This contract enables users to seamlessly convert any token into tWAR tokens for the Warlord protocol by
                         * Paladin.vote. It uses a router such as paraswap to find the routing path for the swap.
                         * @author 0xtekgrinder
                         */
                        contract Zapper is Owned2Step {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice This event is emitted when a zap operation occurs.
                             * @param mintedAmount The amount of WAR tokens minted as a result.
                             * @param receiver The address of the recipient of the WAR tokens.
                             */
                            event Zapped(uint256 mintedAmount, address receiver);
                            /**
                             * @notice This event is emitted when the WarMinter address is changed.
                             * @param newMinter The new WarMinter address.
                             */
                            event SetWarMinter(address newMinter);
                            /**
                             * @notice This event is emitted when the WarStaker address is changed.
                             * @param newStaker The new WarStaker address.
                             */
                            event SetWarStaker(address newStaker);
                            /**
                             *  @notice Event emitted when the swap router is updated
                             */
                            event SwapRouterUpdated(address newSwapRouter);
                            /**
                             *  @notice Event emitted when the token proxy is updated
                             */
                            event TokenTransferAddressUpdated(address newTokenTransferAddress);
                            /**
                             *  @notice Event emitted when the vault is updated
                             */
                            event VaultUpdated(address newVault);
                            /*//////////////////////////////////////////////////////////////
                                                     CONSTANTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Address of the AURA token
                             */
                            address public constant AURA = 0xC0c293ce456fF0ED870ADd98a0828Dd4d2903DBF;
                            /**
                             * @notice Address of the Convex token
                             */
                            address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
                            /**
                             * @notice Address of the WETH token
                             */
                            address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                            /**
                             * @notice Address of the War token
                             */
                            address public constant WAR = 0xa8258deE2a677874a48F5320670A869D74f0cbC1;
                            /*//////////////////////////////////////////////////////////////
                                                  MUTABLE VARIABLES
                            //////////////////////////////////////////////////////////////*/
                            /**
                             *  @notice Dex/aggregaor router to call to perform swaps
                             */
                            address public swapRouter;
                            /**
                             * @notice Address to allow to swap tokens
                             */
                            address public tokenTransferAddress;
                            /**
                             * @notice Address of the WarMinter contract
                             */
                            address public warMinter;
                            /**
                             * @notice Address of the ERC4626 vault
                             */
                            address public vault;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                address initialOwner,
                                address initialSwapRouter,
                                address initialTokenTransferAddress,
                                address initialWarMinter,
                                address initialVault
                            ) Owned2Step(initialOwner) {
                                if (
                                    initialSwapRouter == address(0) || initialTokenTransferAddress == address(0)
                                        || initialWarMinter == address(0) || initialVault == address(0)
                                ) revert Errors.ZeroAddress();
                                swapRouter = initialSwapRouter;
                                tokenTransferAddress = initialTokenTransferAddress;
                                warMinter = initialWarMinter;
                                vault = initialVault;
                            }
                            /*////////////////////////////////////////////
                            /          Warlord allowance methods         /
                            ////////////////////////////////////////////*/
                            /// @dev Resets the allowances for Warlord-related interactions.
                            function resetWarlordAllowances() external onlyOwner {
                                SafeTransferLib.safeApprove(AURA, warMinter, type(uint256).max);
                                SafeTransferLib.safeApprove(CVX, warMinter, type(uint256).max);
                                SafeTransferLib.safeApprove(WAR, vault, type(uint256).max);
                            }
                            /// @dev Removes the allowances for Warlord-related interactions.
                            function removeWarlordAllowances() external onlyOwner {
                                SafeTransferLib.safeApprove(AURA, warMinter, 0);
                                SafeTransferLib.safeApprove(CVX, warMinter, 0);
                                SafeTransferLib.safeApprove(WAR, vault, 0);
                            }
                            function removeRouterAllowance(address token) external onlyOwner {
                                SafeTransferLib.safeApprove(token, swapRouter, 0);
                            }
                            /*////////////////////////////////////////////
                            /              Warlord setters               /
                            ////////////////////////////////////////////*/
                            /**
                             * @notice Set the WarMinter address
                             * @param newWarMinter address of the WarMinter
                             * @custom:requires owner
                             */
                            function setWarMinter(address newWarMinter) external onlyOwner {
                                if (newWarMinter == address(0)) revert Errors.ZeroAddress();
                                warMinter = newWarMinter;
                                emit SetWarMinter(newWarMinter);
                            }
                            /**
                             * @notice Set the dex/aggregator router to call to perform swaps
                             * @param newSwapRouter address of the router
                             * @custom:requires owner
                             */
                            function setSwapRouter(address newSwapRouter) external onlyOwner {
                                if (newSwapRouter == address(0)) revert Errors.ZeroAddress();
                                swapRouter = newSwapRouter;
                                emit SwapRouterUpdated(newSwapRouter);
                            }
                            /**
                             * @notice Set the token proxy address to allow to swap tokens
                             * @param newTokenTransferAddress address of the token proxy
                             * @custom:requires owner
                             */
                            function setTokenTransferAddress(address newTokenTransferAddress) external onlyOwner {
                                if (newTokenTransferAddress == address(0)) revert Errors.ZeroAddress();
                                tokenTransferAddress = newTokenTransferAddress;
                                emit TokenTransferAddressUpdated(newTokenTransferAddress);
                            }
                            /**
                             * @notice Set the vault address
                             * @param newVault address of the vault
                             * @custom:requires owner
                             */
                            function setVault(address newVault) external onlyOwner {
                                if (newVault == address(0)) revert Errors.ZeroAddress();
                                vault = newVault;
                                emit VaultUpdated(newVault);
                            }
                            /*////////////////////////////////////////////
                            /                Zap Functions               /
                            ////////////////////////////////////////////*/
                            /**
                             * @notice Perform the swap using the router/aggregator
                             * @param tokens array of tokens to swap
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function _swap(address[] memory tokens, bytes[] memory callDatas) internal {
                                uint256 length = tokens.length;
                                for (uint256 i; i < length;) {
                                    address token = tokens[i];
                                    Allowance._approveTokenIfNeeded(token, tokenTransferAddress);
                                    _performRouterSwap(callDatas[i]);
                                    unchecked {
                                        ++i;
                                    }
                                }
                            }
                            /**
                             * @notice Perform the swap using the router/aggregator
                             * @param callData bytes to call the router/aggregator
                             */
                            function _performRouterSwap(bytes memory callData) internal {
                                (bool success, bytes memory retData) = swapRouter.call(callData);
                                if (!success) {
                                    if (retData.length != 0) {
                                        assembly {
                                            revert(add(32, retData), mload(retData))
                                        }
                                    }
                                    revert Errors.SwapError();
                                }
                            }
                            /**
                             * @notice Mint a single vlToken
                             * @param receiver Address to stake for
                             * @param vlToken Token to mint WAR
                             * @param amount Amount of token to mint
                             */
                            function _mintSingleToken(address receiver, address vlToken, uint256 amount) internal {
                                IMinter(warMinter).mint(vlToken, amount);
                                uint256 stakedAmount = ERC20(WAR).balanceOf(address(this));
                                ERC4626(vault).deposit(stakedAmount, receiver);
                                emit Zapped(stakedAmount, receiver);
                            }
                            /**
                             * @notice Swap to a single vlToken and mint tWAR
                             * @param receiver Address to stake for
                             * @param token Token to swap
                             * @param vlToken Token to mint WAR
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function _swapAndMintSingleToken(address receiver, address token, address vlToken, bytes memory callDatas)
                                internal
                            {
                                address[] memory tokens = new address[](1);
                                tokens[0] = token;
                                bytes[] memory calldatas = new bytes[](1);
                                calldatas[0] = callDatas;
                                // Swap tokens and mint tWAR
                                _swap(tokens, calldatas);
                                uint256 amount = ERC20(vlToken).balanceOf(address(this));
                                _mintSingleToken(receiver, vlToken, amount);
                            }
                            /**
                             * @notice Mint multiple vlTokens
                             * @param receiver Address to stake for
                             * @param vlTokens Tokens to mint WAR
                             * @param amounts Amounts to mint
                             */
                            function _mintMultipleTokens(address receiver, address[] memory vlTokens, uint256[] memory amounts) internal {
                                uint256 length = vlTokens.length;
                                for (uint256 i; i < length;) {
                                    IMinter(warMinter).mint(vlTokens[i], amounts[i]);
                                    unchecked {
                                        ++i;
                                    }
                                }
                                uint256 stakedAmount = ERC20(WAR).balanceOf(address(this));
                                ERC4626(vault).deposit(stakedAmount, receiver);
                                emit Zapped(stakedAmount, receiver);
                            }
                            /**
                             * @notice Swap to multiple vlTokens and mint tWAR
                             * @param receiver Address to stake for
                             * @param token Token to swap
                             * @param vlTokens Tokens to mint WAR
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function _swapAndMintMultipleTokens(
                                address receiver,
                                address token,
                                address[] memory vlTokens,
                                bytes[] memory callDatas
                            ) internal {
                                // Create an array of the same token
                                uint256 length = callDatas.length;
                                address[] memory tokens = new address[](length);
                                for (uint256 i; i < length;) {
                                    tokens[i] = token;
                                    unchecked {
                                        ++i;
                                    }
                                }
                                // Swap tokens and mint tWAR
                                _swap(tokens, callDatas);
                                length = vlTokens.length;
                                uint256[] memory amounts = new uint256[](length);
                                for (uint256 i; i < length;) {
                                    amounts[i] = ERC20(vlTokens[i]).balanceOf(address(this));
                                    unchecked {
                                        ++i;
                                    }
                                }
                                _mintMultipleTokens(receiver, vlTokens, amounts);
                            }
                            /**
                             * @notice Zaps ether to a single vlToken
                             * @param receiver Address to stake for
                             * @param vlToken Token to mint WAR
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function zapEtherToSingleToken(address vlToken, address receiver, bytes calldata callDatas) external payable {
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                if (msg.value == 0) revert Errors.ZeroValue();
                                // Convert native eth to weth
                                WETH9(WETH).deposit{ value: msg.value }();
                                _swapAndMintSingleToken(receiver, WETH, vlToken, callDatas);
                            }
                            /**
                             * @notice Zaps an ERC20 token to a single vlToken
                             * @param token Token to swap
                             * @param vlToken Token to mint WAR
                             * @param amount Amount of token to swap
                             * @param receiver Address to stake for
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function zapERC20ToSingleToken(
                                address token,
                                address vlToken,
                                uint256 amount,
                                address receiver,
                                bytes calldata callDatas
                            ) external {
                                if (token == address(0)) revert Errors.ZeroAddress();
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                if (amount == 0) revert Errors.ZeroValue();
                                // Pull ERC20 from sender to this contract
                                SafeTransferLib.safeTransferFrom(token, msg.sender, address(this), amount);
                                _swapAndMintSingleToken(receiver, token, vlToken, callDatas);
                            }
                            /**
                             * @notice Zaps ether to multiple vlTokens
                             * @param receiver Address to stake for
                             * @param vlTokens List of token addresses to deposit
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function zapEtherToMultipleTokens(address[] calldata vlTokens, address receiver, bytes[] calldata callDatas)
                                external
                                payable
                            {
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                if (msg.value == 0) revert Errors.ZeroValue();
                                // Convert native eth to weth
                                WETH9(WETH).deposit{ value: msg.value }();
                                _swapAndMintMultipleTokens(receiver, WETH, vlTokens, callDatas);
                            }
                            /**
                             * @notice Zaps an ERC20 token to multiple vlTokens
                             * @param token Token to swap
                             * @param amount Amount of token to swap
                             * @param receiver Address to stake for
                             * @param vlTokens List of token addresses to deposit
                             * @param callDatas bytes to call the router/aggregator
                             */
                            function zapERC20ToMultipleTokens(
                                address token,
                                address[] calldata vlTokens,
                                uint256 amount,
                                address receiver,
                                bytes[] calldata callDatas
                            ) external {
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                if (amount == 0) revert Errors.ZeroValue();
                                // Pull ERC20 from sender to this contract
                                SafeTransferLib.safeTransferFrom(token, msg.sender, address(this), amount);
                                _swapAndMintMultipleTokens(receiver, token, vlTokens, callDatas);
                            }
                            /**
                             * @notice Zaps a vlToken to tWAR
                             * @param vlToken Token to mint WAR
                             * @param amount Amount of token to swap
                             * @param receiver Address to stake for
                             */
                            function zapVlToken(address vlToken, uint256 amount, address receiver) external {
                                if (vlToken == address(0)) revert Errors.ZeroAddress();
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                if (amount == 0) revert Errors.ZeroValue();
                                // Pull vl token from sender to this contract
                                SafeTransferLib.safeTransferFrom(vlToken, msg.sender, address(this), amount);
                                _mintSingleToken(receiver, vlToken, amount);
                            }
                            /**
                             * @notice Zaps multiple vlTokens to tWAR
                             * @param vlTokens List of token addresses to deposit
                             * @param amounts List of token amounts to deposit
                             * @param receiver Address to stake for
                             */
                            function zapVlTokens(address[] calldata vlTokens, uint256[] calldata amounts, address receiver) external {
                                if (receiver == address(0)) revert Errors.ZeroAddress();
                                // Pull vl tokens from sender to this contract
                                uint256 length = vlTokens.length;
                                for (uint256 i; i < length;) {
                                    if (amounts[i] == 0) revert Errors.ZeroValue();
                                    SafeTransferLib.safeTransferFrom(vlTokens[i], msg.sender, address(this), amounts[i]);
                                    unchecked {
                                        ++i;
                                    }
                                }
                                _mintMultipleTokens(receiver, vlTokens, amounts);
                            }
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.0;
                        library Errors {
                            // General errors
                            error ZeroValue();
                            error ZeroAddress();
                            error EmptyArray();
                            error DifferentSizeArrays(uint256 length1, uint256 length2);
                            // Fee errors
                            error InvalidFee();
                            // Swapper errors
                            error SwapError();
                            // Weighted tokens errors
                            error RatioOverflow();
                            error NoWeightedTokens();
                            // Operator errors
                            error NotOperator();
                            error NotOperatorOrOwner();
                            // Swapper errors
                            error NotVault();
                            error WithdrawMoreThanMax();
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                        /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                        abstract contract ERC20 {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                    METADATA STORAGE
                            //////////////////////////////////////////////////////////////*/
                            string public name;
                            string public symbol;
                            uint8 public immutable decimals;
                            /*//////////////////////////////////////////////////////////////
                                                      ERC20 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 public totalSupply;
                            mapping(address => uint256) public balanceOf;
                            mapping(address => mapping(address => uint256)) public allowance;
                            /*//////////////////////////////////////////////////////////////
                                                    EIP-2612 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 internal immutable INITIAL_CHAIN_ID;
                            bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                            mapping(address => uint256) public nonces;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                string memory _name,
                                string memory _symbol,
                                uint8 _decimals
                            ) {
                                name = _name;
                                symbol = _symbol;
                                decimals = _decimals;
                                INITIAL_CHAIN_ID = block.chainid;
                                INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                allowance[msg.sender][spender] = amount;
                                emit Approval(msg.sender, spender, amount);
                                return true;
                            }
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                balanceOf[msg.sender] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(msg.sender, to, amount);
                                return true;
                            }
                            function transferFrom(
                                address from,
                                address to,
                                uint256 amount
                            ) public virtual returns (bool) {
                                uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                balanceOf[from] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(from, to, amount);
                                return true;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     EIP-2612 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                // Unchecked because the only math done is incrementing
                                // the owner's nonce which cannot realistically overflow.
                                unchecked {
                                    address recoveredAddress = ecrecover(
                                        keccak256(
                                            abi.encodePacked(
                                                "\\x19\\x01",
                                                DOMAIN_SEPARATOR(),
                                                keccak256(
                                                    abi.encode(
                                                        keccak256(
                                                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                        ),
                                                        owner,
                                                        spender,
                                                        value,
                                                        nonces[owner]++,
                                                        deadline
                                                    )
                                                )
                                            )
                                        ),
                                        v,
                                        r,
                                        s
                                    );
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                    allowance[recoveredAddress][spender] = value;
                                }
                                emit Approval(owner, spender, value);
                            }
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                            }
                            function computeDomainSeparator() internal view virtual returns (bytes32) {
                                return
                                    keccak256(
                                        abi.encode(
                                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                            keccak256(bytes(name)),
                                            keccak256("1"),
                                            block.chainid,
                                            address(this)
                                        )
                                    );
                            }
                            /*//////////////////////////////////////////////////////////////
                                                INTERNAL MINT/BURN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function _mint(address to, uint256 amount) internal virtual {
                                totalSupply += amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(address(0), to, amount);
                            }
                            function _burn(address from, uint256 amount) internal virtual {
                                balanceOf[from] -= amount;
                                // Cannot underflow because a user's balance
                                // will never be larger than the total supply.
                                unchecked {
                                    totalSupply -= amount;
                                }
                                emit Transfer(from, address(0), amount);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                        /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
                        ///
                        /// @dev Note:
                        /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
                        /// - For ERC20s, this implementation won't check that a token has code,
                        ///   responsibility is delegated to the caller.
                        library SafeTransferLib {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The ETH transfer has failed.
                            error ETHTransferFailed();
                            /// @dev The ERC20 `transferFrom` has failed.
                            error TransferFromFailed();
                            /// @dev The ERC20 `transfer` has failed.
                            error TransferFailed();
                            /// @dev The ERC20 `approve` has failed.
                            error ApproveFailed();
                            /// @dev The Permit2 operation has failed.
                            error Permit2Failed();
                            /// @dev The Permit2 amount must be less than `2**160 - 1`.
                            error Permit2AmountOverflow();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
                            uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
                            /// @dev Suggested gas stipend for contract receiving ETH to perform a few
                            /// storage reads and writes, but low enough to prevent griefing.
                            uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
                            /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
                            bytes32 internal constant DAI_DOMAIN_SEPARATOR =
                                0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
                            /// @dev The address for the WETH9 contract on Ethereum mainnet.
                            address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                            /// @dev The canonical Permit2 address.
                            /// [Github](https://github.com/Uniswap/permit2)
                            /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
                            address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       ETH OPERATIONS                       */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
                            //
                            // The regular variants:
                            // - Forwards all remaining gas to the target.
                            // - Reverts if the target reverts.
                            // - Reverts if the current contract has insufficient balance.
                            //
                            // The force variants:
                            // - Forwards with an optional gas stipend
                            //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
                            // - If the target reverts, or if the gas stipend is exhausted,
                            //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
                            //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
                            // - Reverts if the current contract has insufficient balance.
                            //
                            // The try variants:
                            // - Forwards with a mandatory gas stipend.
                            // - Instead of reverting, returns whether the transfer succeeded.
                            /// @dev Sends `amount` (in wei) ETH to `to`.
                            function safeTransferETH(address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                            /// @dev Sends all the ETH in the current contract to `to`.
                            function safeTransferAllETH(address to) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Transfer all the ETH and check if it succeeded or not.
                                    if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                            /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                            function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if lt(selfbalance(), amount) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
                            function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
                            function forceSafeTransferETH(address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if lt(selfbalance(), amount) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
                            function forceSafeTransferAllETH(address to) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // forgefmt: disable-next-item
                                    if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                            function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
                                }
                            }
                            /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
                            function trySafeTransferAllETH(address to, uint256 gasStipend)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      ERC20 OPERATIONS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have at least `amount` approved for
                            /// the current contract to manage.
                            function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x60, amount) // Store the `amount` argument.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            ///
                            /// The `from` account must have at least `amount` approved for the current contract to manage.
                            function trySafeTransferFrom(address token, address from, address to, uint256 amount)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x60, amount) // Store the `amount` argument.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                    success :=
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends all of ERC20 `token` from `from` to `to`.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have their entire balance approved for the current contract to manage.
                            function safeTransferAllFrom(address token, address from, address to)
                                internal
                                returns (uint256 amount)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                    // Read the balance, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                                    amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
                            /// Reverts upon failure.
                            function safeTransfer(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sends all of ERC20 `token` from the current contract to `to`.
                            /// Reverts upon failure.
                            function safeTransferAll(address token, address to) internal returns (uint256 amount) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                                    mstore(0x20, address()) // Store the address of the current contract.
                                    // Read the balance, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x14, to) // Store the `to` argument.
                                    amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                                    mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                            /// Reverts upon failure.
                            function safeApprove(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                    // Perform the approval, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                            /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                            /// then retries the approval again (some tokens, e.g. USDT, requires this).
                            /// Reverts upon failure.
                            function safeApproveWithRetry(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                    // Perform the approval, retrying upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x34, 0) // Store 0 for the `amount`.
                                        mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                        pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                                        mstore(0x34, amount) // Store back the original `amount`.
                                        // Retry the approval, reverting upon failure.
                                        if iszero(
                                            and(
                                                or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                                call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                            )
                                        ) {
                                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Returns the amount of ERC20 `token` owned by `account`.
                            /// Returns zero if the `token` does not exist.
                            function balanceOf(address token, address account) internal view returns (uint256 amount) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, account) // Store the `account` argument.
                                    mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                    amount :=
                                        mul( // The arguments of `mul` are evaluated from right to left.
                                            mload(0x20),
                                            and( // The arguments of `and` are evaluated from right to left.
                                                gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                                staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                            )
                                        )
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            /// If the initial attempt fails, try to use Permit2 to transfer the token.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have at least `amount` approved for the current contract to manage.
                            function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
                                if (!trySafeTransferFrom(token, from, to, amount)) {
                                    permit2TransferFrom(token, from, to, amount);
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
                            /// Reverts upon failure.
                            function permit2TransferFrom(address token, address from, address to, uint256 amount)
                                internal
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40)
                                    mstore(add(m, 0x74), shr(96, shl(96, token)))
                                    mstore(add(m, 0x54), amount)
                                    mstore(add(m, 0x34), to)
                                    mstore(add(m, 0x20), shl(96, from))
                                    // `transferFrom(address,address,uint160,address)`.
                                    mstore(m, 0x36c78516000000000000000000000000)
                                    let p := mul(PERMIT2, iszero(shr(160, amount)))
                                    if iszero(mul(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), extcodesize(p)))
                                    {
                                        mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                                        revert(add(0x18, shl(2, iszero(p))), 0x04)
                                    }
                                }
                            }
                            /// @dev Permit a user to spend a given amount of
                            /// another user's tokens via native EIP-2612 permit if possible, falling
                            /// back to Permit2 if native permit fails or is not implemented on the token.
                            function permit2(
                                address token,
                                address owner,
                                address spender,
                                uint256 amount,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                bool success;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for {} shl(96, xor(token, WETH9)) {} {
                                        mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                                        if iszero(
                                            and( // The arguments of `and` are evaluated from right to left.
                                                lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                                                // Gas stipend to limit gas burn for tokens that don't refund gas when
                                                // an non-existing function is called. 5K should be enough for a SLOAD.
                                                staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                                            )
                                        ) { break }
                                        let m := mload(0x40)
                                        mstore(add(m, 0x34), spender)
                                        mstore(add(m, 0x20), shl(96, owner))
                                        mstore(add(m, 0x74), deadline)
                                        if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                                            mstore(0x14, owner)
                                            mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                                            mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                                            mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                                            // `nonces` is already at `add(m, 0x54)`.
                                            // `1` is already stored at `add(m, 0x94)`.
                                            mstore(add(m, 0xb4), and(0xff, v))
                                            mstore(add(m, 0xd4), r)
                                            mstore(add(m, 0xf4), s)
                                            success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                                            break
                                        }
                                        mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                                        mstore(add(m, 0x54), amount)
                                        mstore(add(m, 0x94), and(0xff, v))
                                        mstore(add(m, 0xb4), r)
                                        mstore(add(m, 0xd4), s)
                                        success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                                        break
                                    }
                                }
                                if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
                            }
                            /// @dev Simple permit on the Permit2 contract.
                            function simplePermit2(
                                address token,
                                address owner,
                                address spender,
                                uint256 amount,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40)
                                    mstore(m, 0x927da105) // `allowance(address,address,address)`.
                                    {
                                        let addressMask := shr(96, not(0))
                                        mstore(add(m, 0x20), and(addressMask, owner))
                                        mstore(add(m, 0x40), and(addressMask, token))
                                        mstore(add(m, 0x60), and(addressMask, spender))
                                        mstore(add(m, 0xc0), and(addressMask, spender))
                                    }
                                    let p := mul(PERMIT2, iszero(shr(160, amount)))
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                                            staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                                        )
                                    ) {
                                        mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                                        revert(add(0x18, shl(2, iszero(p))), 0x04)
                                    }
                                    mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                                    // `owner` is already `add(m, 0x20)`.
                                    // `token` is already at `add(m, 0x40)`.
                                    mstore(add(m, 0x60), amount)
                                    mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                                    // `nonce` is already at `add(m, 0xa0)`.
                                    // `spender` is already at `add(m, 0xc0)`.
                                    mstore(add(m, 0xe0), deadline)
                                    mstore(add(m, 0x100), 0x100) // `signature` offset.
                                    mstore(add(m, 0x120), 0x41) // `signature` length.
                                    mstore(add(m, 0x140), r)
                                    mstore(add(m, 0x160), s)
                                    mstore(add(m, 0x180), shl(248, v))
                                    if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
                                        mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity ^0.8.0;
                        interface IMinter {
                          function mint(address vlToken, uint256 amount) external;
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts) external;
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.0;
                        interface WETH9 {
                            event Approval(address indexed src, address indexed guy, uint256 wad);
                            event Deposit(address indexed dst, uint256 wad);
                            event Transfer(address indexed src, address indexed dst, uint256 wad);
                            event Withdrawal(address indexed src, uint256 wad);
                            function allowance(address, address) external view returns (uint256);
                            function approve(address guy, uint256 wad) external returns (bool);
                            function balanceOf(address) external view returns (uint256);
                            function decimals() external view returns (uint8);
                            function deposit() external payable;
                            function name() external view returns (string memory);
                            function symbol() external view returns (string memory);
                            function totalSupply() external view returns (uint256);
                            function transfer(address dst, uint256 wad) external returns (bool);
                            function transferFrom(address src, address dst, uint256 wad) external returns (bool);
                            function withdraw(uint256 wad) external;
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity 0.8.24;
                        import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                        import { ERC20 } from "solmate/tokens/ERC20.sol";
                        library Allowance {
                            /**
                             * @notice Approve the router/aggregator to spend the token if needed
                             * @param _token address of the token to approve
                             * @param _spender address of the router/aggregator
                             */
                            function _approveTokenIfNeeded(address _token, address _spender) internal {
                                if (ERC20(_token).allowance(address(this), _spender) == 0) {
                                    SafeTransferLib.safeApprove(_token, _spender, type(uint256).max);
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        import {ERC20} from "./ERC20.sol";
                        import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";
                        import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
                        /// @notice Simple ERC4626 tokenized Vault implementation.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC4626.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol)
                        abstract contract ERC4626 is ERC20 {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The default underlying decimals.
                            uint8 internal constant _DEFAULT_UNDERLYING_DECIMALS = 18;
                            /// @dev The default decimals offset.
                            uint8 internal constant _DEFAULT_DECIMALS_OFFSET = 0;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Cannot deposit more than the max limit.
                            error DepositMoreThanMax();
                            /// @dev Cannot mint more than the max limit.
                            error MintMoreThanMax();
                            /// @dev Cannot withdraw more than the max limit.
                            error WithdrawMoreThanMax();
                            /// @dev Cannot redeem more than the max limit.
                            error RedeemMoreThanMax();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           EVENTS                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Emitted during a mint call or deposit call.
                            event Deposit(address indexed by, address indexed owner, uint256 assets, uint256 shares);
                            /// @dev Emitted during a withdraw call or redeem call.
                            event Withdraw(
                                address indexed by,
                                address indexed to,
                                address indexed owner,
                                uint256 assets,
                                uint256 shares
                            );
                            /// @dev `keccak256(bytes("Deposit(address,address,uint256,uint256)"))`.
                            uint256 private constant _DEPOSIT_EVENT_SIGNATURE =
                                0xdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7;
                            /// @dev `keccak256(bytes("Withdraw(address,address,address,uint256,uint256)"))`.
                            uint256 private constant _WITHDRAW_EVENT_SIGNATURE =
                                0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     ERC4626 CONSTANTS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev To be overridden to return the address of the underlying asset.
                            ///
                            /// - MUST be an ERC20 token contract.
                            /// - MUST NOT revert.
                            function asset() public view virtual returns (address);
                            /// @dev To be overridden to return the number of decimals of the underlying asset.
                            /// Default: 18.
                            ///
                            /// - MUST NOT revert.
                            function _underlyingDecimals() internal view virtual returns (uint8) {
                                return _DEFAULT_UNDERLYING_DECIMALS;
                            }
                            /// @dev Override to return a non-zero value to make the inflation attack even more unfeasible.
                            /// Only used when {_useVirtualShares} returns true.
                            /// Default: 0.
                            ///
                            /// - MUST NOT revert.
                            function _decimalsOffset() internal view virtual returns (uint8) {
                                return _DEFAULT_DECIMALS_OFFSET;
                            }
                            /// @dev Returns whether virtual shares will be used to mitigate the inflation attack.
                            /// See: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/3706
                            /// Override to return true or false.
                            /// Default: true.
                            ///
                            /// - MUST NOT revert.
                            function _useVirtualShares() internal view virtual returns (bool) {
                                return true;
                            }
                            /// @dev Returns the decimals places of the token.
                            ///
                            /// - MUST NOT revert.
                            function decimals() public view virtual override(ERC20) returns (uint8) {
                                if (!_useVirtualShares()) return _underlyingDecimals();
                                return _underlyingDecimals() + _decimalsOffset();
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                ASSET DECIMALS GETTER HELPER                */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Helper function to get the decimals of the underlying asset.
                            /// Useful for setting the return value of `_underlyingDecimals` during initialization.
                            /// If the retrieval succeeds, `success` will be true, and `result` will hold the result.
                            /// Otherwise, `success` will be false, and `result` will be zero.
                            ///
                            /// Example usage:
                            /// ```
                            /// (bool success, uint8 result) = _tryGetAssetDecimals(underlying);
                            /// _decimals = success ? result : _DEFAULT_UNDERLYING_DECIMALS;
                            /// ```
                            function _tryGetAssetDecimals(address underlying)
                                internal
                                view
                                returns (bool success, uint8 result)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Store the function selector of `decimals()`.
                                    mstore(0x00, 0x313ce567)
                                    // Arguments are evaluated last to first.
                                    success :=
                                        and(
                                            // Returned value is less than 256, at left-padded to 32 bytes.
                                            and(lt(mload(0x00), 0x100), gt(returndatasize(), 0x1f)),
                                            // The staticcall succeeds.
                                            staticcall(gas(), underlying, 0x1c, 0x04, 0x00, 0x20)
                                        )
                                    result := mul(mload(0x00), success)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      ACCOUNTING LOGIC                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the total amount of the underlying asset managed by the Vault.
                            ///
                            /// - SHOULD include any compounding that occurs from the yield.
                            /// - MUST be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT revert.
                            function totalAssets() public view virtual returns (uint256 assets) {
                                assets = SafeTransferLib.balanceOf(asset(), address(this));
                            }
                            /// @dev Returns the amount of shares that the Vault will exchange for the amount of
                            /// assets provided, in an ideal scenario where all conditions are met.
                            ///
                            /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT show any variations depending on the caller.
                            /// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
                            /// - MUST NOT revert.
                            ///
                            /// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
                            /// should reflect the "average-user's" price-per-share, i.e. what the average user should
                            /// expect to see when exchanging to and from.
                            function convertToShares(uint256 assets) public view virtual returns (uint256 shares) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return _eitherIsZero(assets, supply)
                                        ? _initialConvertToShares(assets)
                                        : FixedPointMathLib.fullMulDiv(assets, supply, totalAssets());
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 1, _inc(totalAssets()));
                                }
                                return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
                            }
                            /// @dev Returns the amount of assets that the Vault will exchange for the amount of
                            /// shares provided, in an ideal scenario where all conditions are met.
                            ///
                            /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT show any variations depending on the caller.
                            /// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
                            /// - MUST NOT revert.
                            ///
                            /// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
                            /// should reflect the "average-user's" price-per-share, i.e. what the average user should
                            /// expect to see when exchanging to and from.
                            function convertToAssets(uint256 shares) public view virtual returns (uint256 assets) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return supply == 0
                                        ? _initialConvertToAssets(shares)
                                        : FixedPointMathLib.fullMulDiv(shares, totalAssets(), supply);
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, _inc(totalSupply()));
                                }
                                return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, totalSupply() + 10 ** o);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their deposit
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no more than the exact amount of Vault shares that
                            ///   will be minted in a deposit call in the same transaction, i.e. deposit should
                            ///   return the same or more shares as `previewDeposit` if call in the same transaction.
                            /// - MUST NOT account for deposit limits like those returned from `maxDeposit` and should
                            ///   always act as if the deposit will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of deposit fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToShares` and `previewDeposit` SHOULD
                            /// be considered slippage in share price or some other type of condition, meaning
                            /// the depositor will lose assets by depositing.
                            function previewDeposit(uint256 assets) public view virtual returns (uint256 shares) {
                                shares = convertToShares(assets);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their mint
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no fewer than the exact amount of assets that
                            ///   will be deposited in a mint call in the same transaction, i.e. mint should
                            ///   return the same or fewer assets as `previewMint` if called in the same transaction.
                            /// - MUST NOT account for mint limits like those returned from `maxMint` and should
                            ///   always act as if the mint will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of deposit fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToAssets` and `previewMint` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by minting.
                            function previewMint(uint256 shares) public view virtual returns (uint256 assets) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return supply == 0
                                        ? _initialConvertToAssets(shares)
                                        : FixedPointMathLib.fullMulDivUp(shares, totalAssets(), supply);
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, _inc(totalSupply()));
                                }
                                return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, totalSupply() + 10 ** o);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal
                            /// at the current block, given the current on-chain conditions.
                            ///
                            /// - MUST return as close to and no fewer than the exact amount of Vault shares that
                            ///   will be burned in a withdraw call in the same transaction, i.e. withdraw should
                            ///   return the same or fewer shares as `previewWithdraw` if call in the same transaction.
                            /// - MUST NOT account for withdrawal limits like those returned from `maxWithdraw` and should
                            ///   always act as if the withdrawal will be accepted, regardless of share balance, etc.
                            /// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToShares` and `previewWithdraw` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by depositing.
                            function previewWithdraw(uint256 assets) public view virtual returns (uint256 shares) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return _eitherIsZero(assets, supply)
                                        ? _initialConvertToShares(assets)
                                        : FixedPointMathLib.fullMulDivUp(assets, supply, totalAssets());
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 1, _inc(totalAssets()));
                                }
                                return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their redemption
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no more than the exact amount of assets that
                            ///   will be withdrawn in a redeem call in the same transaction, i.e. redeem should
                            ///   return the same or more assets as `previewRedeem` if called in the same transaction.
                            /// - MUST NOT account for redemption limits like those returned from `maxRedeem` and should
                            ///   always act as if the redemption will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
                            /// - MUST NOT revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToAssets` and `previewRedeem` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by depositing.
                            function previewRedeem(uint256 shares) public view virtual returns (uint256 assets) {
                                assets = convertToAssets(shares);
                            }
                            /// @dev Private helper to return if either value is zero.
                            function _eitherIsZero(uint256 a, uint256 b) private pure returns (bool result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    result := or(iszero(a), iszero(b))
                                }
                            }
                            /// @dev Private helper to return `x + 1` without the overflow check.
                            /// Used for computing the denominator input to `FixedPointMathLib.fullMulDiv(a, b, x + 1)`.
                            /// When `x == type(uint256).max`, we get `x + 1 == 0` (mod 2**256 - 1),
                            /// and `FixedPointMathLib.fullMulDiv` will revert as the denominator is zero.
                            function _inc(uint256 x) private pure returns (uint256) {
                                unchecked {
                                    return x + 1;
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*              DEPOSIT / WITHDRAWAL LIMIT LOGIC              */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the maximum amount of the underlying asset that can be deposited
                            /// into the Vault for `to`, via a deposit call.
                            ///
                            /// - MUST return a limited value if `to` is subject to some deposit limit.
                            /// - MUST return `2**256-1` if there is no maximum limit.
                            /// - MUST NOT revert.
                            function maxDeposit(address to) public view virtual returns (uint256 maxAssets) {
                                to = to; // Silence unused variable warning.
                                maxAssets = type(uint256).max;
                            }
                            /// @dev Returns the maximum amount of the Vault shares that can be minter for `to`,
                            /// via a mint call.
                            ///
                            /// - MUST return a limited value if `to` is subject to some mint limit.
                            /// - MUST return `2**256-1` if there is no maximum limit.
                            /// - MUST NOT revert.
                            function maxMint(address to) public view virtual returns (uint256 maxShares) {
                                to = to; // Silence unused variable warning.
                                maxShares = type(uint256).max;
                            }
                            /// @dev Returns the maximum amount of the underlying asset that can be withdrawn
                            /// from the `owner`'s balance in the Vault, via a withdraw call.
                            ///
                            /// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
                            /// - MUST NOT revert.
                            function maxWithdraw(address owner) public view virtual returns (uint256 maxAssets) {
                                maxAssets = convertToAssets(balanceOf(owner));
                            }
                            /// @dev Returns the maximum amount of Vault shares that can be redeemed
                            /// from the `owner`'s balance in the Vault, via a redeem call.
                            ///
                            /// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
                            /// - MUST return `balanceOf(owner)` otherwise.
                            /// - MUST NOT revert.
                            function maxRedeem(address owner) public view virtual returns (uint256 maxShares) {
                                maxShares = balanceOf(owner);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                 DEPOSIT / WITHDRAWAL LOGIC                 */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Mints `shares` Vault shares to `to` by depositing exactly `assets`
                            /// of underlying tokens.
                            ///
                            /// - MUST emit the {Deposit} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the deposit execution, and are accounted for during deposit.
                            /// - MUST revert if all of `assets` cannot be deposited, such as due to deposit limit,
                            ///   slippage, insufficient approval, etc.
                            ///
                            /// Note: Most implementations will require pre-approval of the Vault with the
                            /// Vault's underlying `asset` token.
                            function deposit(uint256 assets, address to) public virtual returns (uint256 shares) {
                                if (assets > maxDeposit(to)) _revert(0xb3c61a83); // `DepositMoreThanMax()`.
                                shares = previewDeposit(assets);
                                _deposit(msg.sender, to, assets, shares);
                            }
                            /// @dev Mints exactly `shares` Vault shares to `to` by depositing `assets`
                            /// of underlying tokens.
                            ///
                            /// - MUST emit the {Deposit} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the mint execution, and are accounted for during mint.
                            /// - MUST revert if all of `shares` cannot be deposited, such as due to deposit limit,
                            ///   slippage, insufficient approval, etc.
                            ///
                            /// Note: Most implementations will require pre-approval of the Vault with the
                            /// Vault's underlying `asset` token.
                            function mint(uint256 shares, address to) public virtual returns (uint256 assets) {
                                if (shares > maxMint(to)) _revert(0x6a695959); // `MintMoreThanMax()`.
                                assets = previewMint(shares);
                                _deposit(msg.sender, to, assets, shares);
                            }
                            /// @dev Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `to`.
                            ///
                            /// - MUST emit the {Withdraw} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the withdraw execution, and are accounted for during withdraw.
                            /// - MUST revert if all of `assets` cannot be withdrawn, such as due to withdrawal limit,
                            ///   slippage, insufficient balance, etc.
                            ///
                            /// Note: Some implementations will require pre-requesting to the Vault before a withdrawal
                            /// may be performed. Those methods should be performed separately.
                            function withdraw(uint256 assets, address to, address owner)
                                public
                                virtual
                                returns (uint256 shares)
                            {
                                if (assets > maxWithdraw(owner)) _revert(0x936941fc); // `WithdrawMoreThanMax()`.
                                shares = previewWithdraw(assets);
                                _withdraw(msg.sender, to, owner, assets, shares);
                            }
                            /// @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `to`.
                            ///
                            /// - MUST emit the {Withdraw} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the redeem execution, and are accounted for during redeem.
                            /// - MUST revert if all of shares cannot be redeemed, such as due to withdrawal limit,
                            ///   slippage, insufficient balance, etc.
                            ///
                            /// Note: Some implementations will require pre-requesting to the Vault before a redeem
                            /// may be performed. Those methods should be performed separately.
                            function redeem(uint256 shares, address to, address owner)
                                public
                                virtual
                                returns (uint256 assets)
                            {
                                if (shares > maxRedeem(owner)) _revert(0x4656425a); // `RedeemMoreThanMax()`.
                                assets = previewRedeem(shares);
                                _withdraw(msg.sender, to, owner, assets, shares);
                            }
                            /// @dev Internal helper for reverting efficiently.
                            function _revert(uint256 s) private pure {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x00, s)
                                    revert(0x1c, 0x04)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      INTERNAL HELPERS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev For deposits and mints.
                            ///
                            /// Emits a {Deposit} event.
                            function _deposit(address by, address to, uint256 assets, uint256 shares) internal virtual {
                                SafeTransferLib.safeTransferFrom(asset(), by, address(this), assets);
                                _mint(to, shares);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Emit the {Deposit} event.
                                    mstore(0x00, assets)
                                    mstore(0x20, shares)
                                    let m := shr(96, not(0))
                                    log3(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, and(m, by), and(m, to))
                                }
                                _afterDeposit(assets, shares);
                            }
                            /// @dev For withdrawals and redemptions.
                            ///
                            /// Emits a {Withdraw} event.
                            function _withdraw(address by, address to, address owner, uint256 assets, uint256 shares)
                                internal
                                virtual
                            {
                                if (by != owner) _spendAllowance(owner, by, shares);
                                _beforeWithdraw(assets, shares);
                                _burn(owner, shares);
                                SafeTransferLib.safeTransfer(asset(), to, assets);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Emit the {Withdraw} event.
                                    mstore(0x00, assets)
                                    mstore(0x20, shares)
                                    let m := shr(96, not(0))
                                    log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
                                }
                            }
                            /// @dev Internal conversion function (from assets to shares) to apply when the Vault is empty.
                            /// Only used when {_useVirtualShares} returns false.
                            ///
                            /// Note: Make sure to keep this function consistent with {_initialConvertToAssets}
                            /// when overriding it.
                            function _initialConvertToShares(uint256 assets)
                                internal
                                view
                                virtual
                                returns (uint256 shares)
                            {
                                shares = assets;
                            }
                            /// @dev Internal conversion function (from shares to assets) to apply when the Vault is empty.
                            /// Only used when {_useVirtualShares} returns false.
                            ///
                            /// Note: Make sure to keep this function consistent with {_initialConvertToShares}
                            /// when overriding it.
                            function _initialConvertToAssets(uint256 shares)
                                internal
                                view
                                virtual
                                returns (uint256 assets)
                            {
                                assets = shares;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     HOOKS TO OVERRIDE                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Hook that is called before any withdrawal or redemption.
                            function _beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
                            /// @dev Hook that is called after any deposit or mint.
                            function _afterDeposit(uint256 assets, uint256 shares) internal virtual {}
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.0;
                        import { Owned } from "solmate/auth/Owned.sol";
                        /// @author 0xtekgrinder
                        /// @title Owned2Step contract
                        /// @notice Simple single owner authorization mixin with 2 step transfer ownership
                        abstract contract Owned2Step is Owned {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event OwnershipTransferStarted(address indexed user, address indexed newOwner);
                            /*//////////////////////////////////////////////////////////////
                                                    OWNERSHIP STORAGE
                            //////////////////////////////////////////////////////////////*/
                            address public pendingOwner;
                            /*//////////////////////////////////////////////////////////////
                                                       MODIFIERS
                            //////////////////////////////////////////////////////////////*/
                            modifier onlyPendingOwner() {
                                require(pendingOwner == msg.sender, "UNAUTHORIZED");
                                _;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(address _owner) Owned(_owner) { }
                            /*//////////////////////////////////////////////////////////////
                                                     OWNERSHIP LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @dev Starts the ownership transfer of the contract to a new account.
                             * @dev Can only be called by the current owner.
                             */
                            function transferOwnership(address newOwner) public virtual override onlyOwner {
                                pendingOwner = newOwner;
                                emit OwnershipTransferStarted(owner, newOwner);
                            }
                            /**
                             * @dev The new owner accepts the ownership transfer.
                             */
                            function acceptOwnership() public virtual onlyPendingOwner {
                                delete pendingOwner;
                                super.transferOwnership(msg.sender);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Simple ERC20 + EIP-2612 implementation.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
                        ///
                        /// @dev Note:
                        /// - The ERC20 standard allows minting and transferring to and from the zero address,
                        ///   minting and transferring zero tokens, as well as self-approvals.
                        ///   For performance, this implementation WILL NOT revert for such actions.
                        ///   Please add any checks with overrides if desired.
                        /// - The `permit` function uses the ecrecover precompile (0x1).
                        ///
                        /// If you are overriding:
                        /// - NEVER violate the ERC20 invariant:
                        ///   the total sum of all balances must be equal to `totalSupply()`.
                        /// - Check that the overridden function is actually used in the function you want to
                        ///   change the behavior of. Much of the code has been manually inlined for performance.
                        abstract contract ERC20 {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The total supply has overflowed.
                            error TotalSupplyOverflow();
                            /// @dev The allowance has overflowed.
                            error AllowanceOverflow();
                            /// @dev The allowance has underflowed.
                            error AllowanceUnderflow();
                            /// @dev Insufficient balance.
                            error InsufficientBalance();
                            /// @dev Insufficient allowance.
                            error InsufficientAllowance();
                            /// @dev The permit is invalid.
                            error InvalidPermit();
                            /// @dev The permit has expired.
                            error PermitExpired();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           EVENTS                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
                            uint256 private constant _TRANSFER_EVENT_SIGNATURE =
                                0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
                            /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
                            uint256 private constant _APPROVAL_EVENT_SIGNATURE =
                                0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                          STORAGE                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The storage slot for the total supply.
                            uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
                            /// @dev The balance slot of `owner` is given by:
                            /// ```
                            ///     mstore(0x0c, _BALANCE_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let balanceSlot := keccak256(0x0c, 0x20)
                            /// ```
                            uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
                            /// @dev The allowance slot of (`owner`, `spender`) is given by:
                            /// ```
                            ///     mstore(0x20, spender)
                            ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let allowanceSlot := keccak256(0x0c, 0x34)
                            /// ```
                            uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
                            /// @dev The nonce slot of `owner` is given by:
                            /// ```
                            ///     mstore(0x0c, _NONCES_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let nonceSlot := keccak256(0x0c, 0x20)
                            /// ```
                            uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
                            uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
                            /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
                            bytes32 private constant _DOMAIN_TYPEHASH =
                                0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
                            /// @dev `keccak256("1")`.
                            bytes32 private constant _VERSION_HASH =
                                0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
                            /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
                            bytes32 private constant _PERMIT_TYPEHASH =
                                0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       ERC20 METADATA                       */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the name of the token.
                            function name() public view virtual returns (string memory);
                            /// @dev Returns the symbol of the token.
                            function symbol() public view virtual returns (string memory);
                            /// @dev Returns the decimals places of the token.
                            function decimals() public view virtual returns (uint8) {
                                return 18;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           ERC20                            */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the amount of tokens in existence.
                            function totalSupply() public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    result := sload(_TOTAL_SUPPLY_SLOT)
                                }
                            }
                            /// @dev Returns the amount of tokens owned by `owner`.
                            function balanceOf(address owner) public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x20))
                                }
                            }
                            /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
                            function allowance(address owner, address spender)
                                public
                                view
                                virtual
                                returns (uint256 result)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x34))
                                }
                            }
                            /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                            ///
                            /// Emits a {Approval} event.
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the allowance slot and store the amount.
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, caller())
                                    sstore(keccak256(0x0c, 0x34), amount)
                                    // Emit the {Approval} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
                                }
                                return true;
                            }
                            /// @dev Transfer `amount` tokens from the caller to `to`.
                            ///
                            /// Requirements:
                            /// - `from` must at least have `amount`.
                            ///
                            /// Emits a {Transfer} event.
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                _beforeTokenTransfer(msg.sender, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, caller())
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(msg.sender, to, amount);
                                return true;
                            }
                            /// @dev Transfers `amount` tokens from `from` to `to`.
                            ///
                            /// Note: Does not update the allowance if it is the maximum uint256 value.
                            ///
                            /// Requirements:
                            /// - `from` must at least have `amount`.
                            /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
                            ///
                            /// Emits a {Transfer} event.
                            function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
                                _beforeTokenTransfer(from, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let from_ := shl(96, from)
                                    // Compute the allowance slot and load its value.
                                    mstore(0x20, caller())
                                    mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                                    let allowanceSlot := keccak256(0x0c, 0x34)
                                    let allowance_ := sload(allowanceSlot)
                                    // If the allowance is not the maximum uint256 value.
                                    if add(allowance_, 1) {
                                        // Revert if the amount to be transferred exceeds the allowance.
                                        if gt(amount, allowance_) {
                                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                                            revert(0x1c, 0x04)
                                        }
                                        // Subtract and store the updated allowance.
                                        sstore(allowanceSlot, sub(allowance_, amount))
                                    }
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(from, to, amount);
                                return true;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                          EIP-2612                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev For more performance, override to return the constant value
                            /// of `keccak256(bytes(name()))` if `name()` will never change.
                            function _constantNameHash() internal view virtual returns (bytes32 result) {}
                            /// @dev Returns the current nonce for `owner`.
                            /// This value is used to compute the signature for EIP-2612 permit.
                            function nonces(address owner) public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the nonce slot and load its value.
                                    mstore(0x0c, _NONCES_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x20))
                                }
                            }
                            /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
                            /// authorized by a signed approval by `owner`.
                            ///
                            /// Emits a {Approval} event.
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                bytes32 nameHash = _constantNameHash();
                                //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
                                if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Revert if the block timestamp is greater than `deadline`.
                                    if gt(timestamp(), deadline) {
                                        mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
                                        revert(0x1c, 0x04)
                                    }
                                    let m := mload(0x40) // Grab the free memory pointer.
                                    // Clean the upper 96 bits.
                                    owner := shr(96, shl(96, owner))
                                    spender := shr(96, shl(96, spender))
                                    // Compute the nonce slot and load its value.
                                    mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
                                    mstore(0x00, owner)
                                    let nonceSlot := keccak256(0x0c, 0x20)
                                    let nonceValue := sload(nonceSlot)
                                    // Prepare the domain separator.
                                    mstore(m, _DOMAIN_TYPEHASH)
                                    mstore(add(m, 0x20), nameHash)
                                    mstore(add(m, 0x40), _VERSION_HASH)
                                    mstore(add(m, 0x60), chainid())
                                    mstore(add(m, 0x80), address())
                                    mstore(0x2e, keccak256(m, 0xa0))
                                    // Prepare the struct hash.
                                    mstore(m, _PERMIT_TYPEHASH)
                                    mstore(add(m, 0x20), owner)
                                    mstore(add(m, 0x40), spender)
                                    mstore(add(m, 0x60), value)
                                    mstore(add(m, 0x80), nonceValue)
                                    mstore(add(m, 0xa0), deadline)
                                    mstore(0x4e, keccak256(m, 0xc0))
                                    // Prepare the ecrecover calldata.
                                    mstore(0x00, keccak256(0x2c, 0x42))
                                    mstore(0x20, and(0xff, v))
                                    mstore(0x40, r)
                                    mstore(0x60, s)
                                    let t := staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)
                                    // If the ecrecover fails, the returndatasize will be 0x00,
                                    // `owner` will be checked if it equals the hash at 0x00,
                                    // which evaluates to false (i.e. 0), and we will revert.
                                    // If the ecrecover succeeds, the returndatasize will be 0x20,
                                    // `owner` will be compared against the returned address at 0x20.
                                    if iszero(eq(mload(returndatasize()), owner)) {
                                        mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Increment and store the updated nonce.
                                    sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
                                    // Compute the allowance slot and store the value.
                                    // The `owner` is already at slot 0x20.
                                    mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
                                    sstore(keccak256(0x2c, 0x34), value)
                                    // Emit the {Approval} event.
                                    log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
                                    mstore(0x40, m) // Restore the free memory pointer.
                                    mstore(0x60, 0) // Restore the zero pointer.
                                }
                            }
                            /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
                                bytes32 nameHash = _constantNameHash();
                                //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
                                if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Grab the free memory pointer.
                                    mstore(m, _DOMAIN_TYPEHASH)
                                    mstore(add(m, 0x20), nameHash)
                                    mstore(add(m, 0x40), _VERSION_HASH)
                                    mstore(add(m, 0x60), chainid())
                                    mstore(add(m, 0x80), address())
                                    result := keccak256(m, 0xa0)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  INTERNAL MINT FUNCTIONS                   */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Mints `amount` tokens to `to`, increasing the total supply.
                            ///
                            /// Emits a {Transfer} event.
                            function _mint(address to, uint256 amount) internal virtual {
                                _beforeTokenTransfer(address(0), to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
                                    let totalSupplyAfter := add(totalSupplyBefore, amount)
                                    // Revert if the total supply overflows.
                                    if lt(totalSupplyAfter, totalSupplyBefore) {
                                        mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Store the updated total supply.
                                    sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(address(0), to, amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  INTERNAL BURN FUNCTIONS                   */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Burns `amount` tokens from `from`, reducing the total supply.
                            ///
                            /// Emits a {Transfer} event.
                            function _burn(address from, uint256 amount) internal virtual {
                                _beforeTokenTransfer(from, address(0), amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, from)
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Subtract and store the updated total supply.
                                    sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
                                }
                                _afterTokenTransfer(from, address(0), amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                INTERNAL TRANSFER FUNCTIONS                 */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Moves `amount` of tokens from `from` to `to`.
                            function _transfer(address from, address to, uint256 amount) internal virtual {
                                _beforeTokenTransfer(from, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let from_ := shl(96, from)
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(from, to, amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                INTERNAL ALLOWANCE FUNCTIONS                */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
                            function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the allowance slot and load its value.
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    let allowanceSlot := keccak256(0x0c, 0x34)
                                    let allowance_ := sload(allowanceSlot)
                                    // If the allowance is not the maximum uint256 value.
                                    if add(allowance_, 1) {
                                        // Revert if the amount to be transferred exceeds the allowance.
                                        if gt(amount, allowance_) {
                                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                                            revert(0x1c, 0x04)
                                        }
                                        // Subtract and store the updated allowance.
                                        sstore(allowanceSlot, sub(allowance_, amount))
                                    }
                                }
                            }
                            /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
                            ///
                            /// Emits a {Approval} event.
                            function _approve(address owner, address spender, uint256 amount) internal virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let owner_ := shl(96, owner)
                                    // Compute the allowance slot and store the amount.
                                    mstore(0x20, spender)
                                    mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
                                    sstore(keccak256(0x0c, 0x34), amount)
                                    // Emit the {Approval} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     HOOKS TO OVERRIDE                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Hook that is called before any transfer of tokens.
                            /// This includes minting and burning.
                            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.
                            function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Arithmetic library with operations for fixed-point numbers.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
                        library FixedPointMathLib {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                            error ExpOverflow();
                            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                            error FactorialOverflow();
                            /// @dev The operation failed, due to an overflow.
                            error RPowOverflow();
                            /// @dev The mantissa is too big to fit.
                            error MantissaOverflow();
                            /// @dev The operation failed, due to an multiplication overflow.
                            error MulWadFailed();
                            /// @dev The operation failed, due to an multiplication overflow.
                            error SMulWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error DivWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error SDivWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error MulDivFailed();
                            /// @dev The division failed, as the denominator is zero.
                            error DivFailed();
                            /// @dev The full precision multiply-divide operation failed, either due
                            /// to the result being larger than 256 bits, or a division by a zero.
                            error FullMulDivFailed();
                            /// @dev The output is undefined, as the input is less-than-or-equal to zero.
                            error LnWadUndefined();
                            /// @dev The input outside the acceptable domain.
                            error OutOfDomain();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The scalar of ETH and most ERC20s.
                            uint256 internal constant WAD = 1e18;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*              SIMPLIFIED FIXED POINT OPERATIONS             */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Equivalent to `(x * y) / WAD` rounded down.
                            function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                    if mul(y, gt(x, div(not(0), y))) {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down.
                            function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(x, y)
                                    // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
                                    if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                                        mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := sdiv(z, WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                            function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                            function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded up.
                            function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                    if mul(y, gt(x, div(not(0), y))) {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
                            function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down.
                            function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down.
                            function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(x, WAD)
                                    // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
                                    if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                                        mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := sdiv(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                            function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                            function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded up.
                            function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
                            function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                                }
                            }
                            /// @dev Equivalent to `x` to the power of `y`.
                            /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
                            function powWad(int256 x, int256 y) internal pure returns (int256) {
                                // Using `ln(x)` means `x` must be greater than 0.
                                return expWad((lnWad(x) * y) / int256(WAD));
                            }
                            /// @dev Returns `exp(x)`, denominated in `WAD`.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                            function expWad(int256 x) internal pure returns (int256 r) {
                                unchecked {
                                    // When the result is less than 0.5 we return zero.
                                    // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
                                    if (x <= -41446531673892822313) return r;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                                        // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                                        if iszero(slt(x, 135305999368893231589)) {
                                            mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                    // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
                                    // for more intermediate precision and a binary basis. This base conversion
                                    // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                                    x = (x << 78) / 5 ** 18;
                                    // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                                    // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                                    // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                                    int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
                                    x = x - k * 54916777467707473351141471128;
                                    // `k` is in the range `[-61, 195]`.
                                    // Evaluate using a (6, 7)-term rational approximation.
                                    // `p` is made monic, we'll multiply by a scale factor later.
                                    int256 y = x + 1346386616545796478920950773328;
                                    y = ((y * x) >> 96) + 57155421227552351082224309758442;
                                    int256 p = y + x - 94201549194550492254356042504812;
                                    p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                                    p = p * x + (4385272521454847904659076985693276 << 96);
                                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                    int256 q = x - 2855989394907223263936484059900;
                                    q = ((q * x) >> 96) + 50020603652535783019961831881945;
                                    q = ((q * x) >> 96) - 533845033583426703283633433725380;
                                    q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                                    q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                                    q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Div in assembly because solidity adds a zero check despite the unchecked.
                                        // The q polynomial won't have zeros in the domain as all its roots are complex.
                                        // No scaling is necessary because p is already `2**96` too large.
                                        r := sdiv(p, q)
                                    }
                                    // r should be in the range `(0.09, 0.25) * 2**96`.
                                    // We now need to multiply r by:
                                    // - The scale factor `s ≈ 6.031367120`.
                                    // - The `2**k` factor from the range reduction.
                                    // - The `1e18 / 2**96` factor for base conversion.
                                    // We do this all at once, with an intermediate result in `2**213`
                                    // basis, so the final right shift is always by a positive amount.
                                    r = int256(
                                        (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
                                    );
                                }
                            }
                            /// @dev Returns `ln(x)`, denominated in `WAD`.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                            function lnWad(int256 x) internal pure returns (int256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
                                    // We do this by multiplying by `2**96 / 10**18`. But since
                                    // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
                                    // and add `ln(2**96 / 10**18)` at the end.
                                    // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    // We place the check here for more optimal stack operations.
                                    if iszero(sgt(x, 0)) {
                                        mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // forgefmt: disable-next-item
                                    r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                        0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
                                    // Reduce range of x to (1, 2) * 2**96
                                    // ln(2^k * x) = k * ln(2) + ln(x)
                                    x := shr(159, shl(r, x))
                                    // Evaluate using a (8, 8)-term rational approximation.
                                    // `p` is made monic, we will multiply by a scale factor later.
                                    // forgefmt: disable-next-item
                                    let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                                        sar(96, mul(add(43456485725739037958740375743393,
                                        sar(96, mul(add(24828157081833163892658089445524,
                                        sar(96, mul(add(3273285459638523848632254066296,
                                            x), x))), x))), x)), 11111509109440967052023855526967)
                                    p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
                                    p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
                                    p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
                                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                    // `q` is monic by convention.
                                    let q := add(5573035233440673466300451813936, x)
                                    q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
                                    q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
                                    q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
                                    q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
                                    q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
                                    q := add(909429971244387300277376558375, sar(96, mul(x, q)))
                                    // `p / q` is in the range `(0, 0.125) * 2**96`.
                                    // Finalization, we need to:
                                    // - Multiply by the scale factor `s = 5.549…`.
                                    // - Add `ln(2**96 / 10**18)`.
                                    // - Add `k * ln(2)`.
                                    // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
                                    // The q polynomial is known not to have zeros in the domain.
                                    // No scaling required because p is already `2**96` too large.
                                    p := sdiv(p, q)
                                    // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
                                    p := mul(1677202110996718588342820967067443963516166, p)
                                    // Add `ln(2) * k * 5**18 * 2**192`.
                                    // forgefmt: disable-next-item
                                    p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
                                    // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
                                    p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
                                    // Base conversion: mul `2**18 / 2**192`.
                                    r := sar(174, p)
                                }
                            }
                            /// @dev Returns `W_0(x)`, denominated in `WAD`.
                            /// See: https://en.wikipedia.org/wiki/Lambert_W_function
                            /// a.k.a. Product log function. This is an approximation of the principal branch.
                            function lambertW0Wad(int256 x) internal pure returns (int256 w) {
                                // forgefmt: disable-next-item
                                unchecked {
                                    if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
                                    int256 wad = int256(WAD);
                                    int256 p = x;
                                    uint256 c; // Whether we need to avoid catastrophic cancellation.
                                    uint256 i = 4; // Number of iterations.
                                    if (w <= 0x1ffffffffffff) {
                                        if (-0x4000000000000 <= w) {
                                            i = 1; // Inputs near zero only take one step to converge.
                                        } else if (w <= -0x3ffffffffffffff) {
                                            i = 32; // Inputs near `-1/e` take very long to converge.
                                        }
                                    } else if (w >> 63 == 0) {
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            // Inline log2 for more performance, since the range is small.
                                            let v := shr(49, w)
                                            let l := shl(3, lt(0xff, v))
                                            l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                                                0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                                            w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                                            c := gt(l, 60)
                                            i := add(2, add(gt(l, 53), c))
                                        }
                                    } else {
                                        int256 ll = lnWad(w = lnWad(w));
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                                            w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                                            i := add(3, iszero(shr(68, x)))
                                            c := iszero(shr(143, x))
                                        }
                                        if (c == 0) {
                                            do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                                                int256 e = expWad(w);
                                                /// @solidity memory-safe-assembly
                                                assembly {
                                                    let t := mul(w, div(e, wad))
                                                    w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                                                }
                                                if (p <= w) break;
                                                p = w;
                                            } while (--i != 0);
                                            /// @solidity memory-safe-assembly
                                            assembly {
                                                w := sub(w, sgt(w, 2))
                                            }
                                            return w;
                                        }
                                    }
                                    do { // Otherwise, use Halley's for faster convergence.
                                        int256 e = expWad(w);
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            let t := add(w, wad)
                                            let s := sub(mul(w, e), mul(x, wad))
                                            w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                                        }
                                        if (p <= w) break;
                                        p = w;
                                    } while (--i != c);
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        w := sub(w, sgt(w, 2))
                                    }
                                    // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
                                    // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
                                    if (c != 0) {
                                        int256 t = w | 1;
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            x := sdiv(mul(x, wad), t)
                                        }
                                        x = (t * (wad + lnWad(x)));
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            w := sdiv(x, add(wad, t))
                                        }
                                    }
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  GENERAL NUMBER UTILITIES                  */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Calculates `floor(x * y / d)` with full precision.
                            /// Throws if result overflows a uint256 or when `d` is zero.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
                            function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for {} 1 {} {
                                        // 512-bit multiply `[p1 p0] = x * y`.
                                        // Compute the product mod `2**256` and mod `2**256 - 1`
                                        // then use the Chinese Remainder Theorem to reconstruct
                                        // the 512 bit result. The result is stored in two 256
                                        // variables such that `product = p1 * 2**256 + p0`.
                                        // Least significant 256 bits of the product.
                                        result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                                        let mm := mulmod(x, y, not(0))
                                        // Most significant 256 bits of the product.
                                        let p1 := sub(mm, add(result, lt(mm, result)))
                                        // Handle non-overflow cases, 256 by 256 division.
                                        if iszero(p1) {
                                            if iszero(d) {
                                                mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                                revert(0x1c, 0x04)
                                            }
                                            result := div(result, d)
                                            break
                                        }
                                        // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                                        if iszero(gt(d, p1)) {
                                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                        /*------------------- 512 by 256 division --------------------*/
                                        // Make division exact by subtracting the remainder from `[p1 p0]`.
                                        // Compute remainder using mulmod.
                                        let r := mulmod(x, y, d)
                                        // `t` is the least significant bit of `d`.
                                        // Always greater or equal to 1.
                                        let t := and(d, sub(0, d))
                                        // Divide `d` by `t`, which is a power of two.
                                        d := div(d, t)
                                        // Invert `d mod 2**256`
                                        // Now that `d` is an odd number, it has an inverse
                                        // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                                        // Compute the inverse by starting with a seed that is correct
                                        // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                                        let inv := xor(2, mul(3, d))
                                        // Now use Newton-Raphson iteration to improve the precision.
                                        // Thanks to Hensel's lifting lemma, this also works in modular
                                        // arithmetic, doubling the correct bits in each step.
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                                        result :=
                                            mul(
                                                // Divide [p1 p0] by the factors of two.
                                                // Shift in bits from `p1` into `p0`. For this we need
                                                // to flip `t` such that it is `2**256 / t`.
                                                or(
                                                    mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                                                    div(sub(result, r), t)
                                                ),
                                                // inverse mod 2**256
                                                mul(inv, sub(2, mul(d, inv)))
                                            )
                                        break
                                    }
                                }
                            }
                            /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
                            /// Throws if result overflows a uint256 or when `d` is zero.
                            /// Credit to Uniswap-v3-core under MIT license:
                            /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
                            function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                                result = fullMulDiv(x, y, d);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if mulmod(x, y, d) {
                                        result := add(result, 1)
                                        if iszero(result) {
                                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                }
                            }
                            /// @dev Returns `floor(x * y / d)`.
                            /// Reverts if `x * y` overflows, or `d` is zero.
                            function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, y), d)
                                }
                            }
                            /// @dev Returns `ceil(x * y / d)`.
                            /// Reverts if `x * y` overflows, or `d` is zero.
                            function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
                                }
                            }
                            /// @dev Returns `ceil(x / d)`.
                            /// Reverts if `d` is zero.
                            function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(d) {
                                        mstore(0x00, 0x65244e4e) // `DivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(x, d))), div(x, d))
                                }
                            }
                            /// @dev Returns `max(0, x - y)`.
                            function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(gt(x, y), sub(x, y))
                                }
                            }
                            /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
                            /// Reverts if the computation overflows.
                            function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
                                    if x {
                                        z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                                        let half := shr(1, b) // Divide `b` by 2.
                                        // Divide `y` by 2 every iteration.
                                        for { y := shr(1, y) } y { y := shr(1, y) } {
                                            let xx := mul(x, x) // Store x squared.
                                            let xxRound := add(xx, half) // Round to the nearest number.
                                            // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                                            if or(lt(xxRound, xx), shr(128, x)) {
                                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                                revert(0x1c, 0x04)
                                            }
                                            x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                                            // If `y` is odd:
                                            if and(y, 1) {
                                                let zx := mul(z, x) // Compute `z * x`.
                                                let zxRound := add(zx, half) // Round to the nearest number.
                                                // If `z * x` overflowed or `zx + half` overflowed:
                                                if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                                                    // Revert if `x` is non-zero.
                                                    if iszero(iszero(x)) {
                                                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                                        revert(0x1c, 0x04)
                                                    }
                                                }
                                                z := div(zxRound, b) // Return properly scaled `zxRound`.
                                            }
                                        }
                                    }
                                }
                            }
                            /// @dev Returns the square root of `x`.
                            function sqrt(uint256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
                                    z := 181 // The "correct" value is 1, but this saves a multiplication later.
                                    // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                                    // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                                    // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
                                    // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
                                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffffff, shr(r, x))))
                                    z := shl(shr(1, r), z)
                                    // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
                                    // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
                                    // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
                                    // That's not possible if `x < 256` but we can just verify those cases exhaustively.
                                    // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
                                    // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
                                    // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
                                    // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
                                    // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
                                    // with largest error when `s = 1` and when `s = 256` or `1/256`.
                                    // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
                                    // Then we can estimate `sqrt(y)` using
                                    // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
                                    // There is no overflow risk here since `y < 2**136` after the first branch above.
                                    z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
                                    // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    // If `x+1` is a perfect square, the Babylonian method cycles between
                                    // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
                                    // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                                    z := sub(z, lt(div(x, z), z))
                                }
                            }
                            /// @dev Returns the cube root of `x`.
                            /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
                            /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
                            function cbrt(uint256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := sub(z, lt(div(x, mul(z, z)), z))
                                }
                            }
                            /// @dev Returns the square root of `x`, denominated in `WAD`.
                            function sqrtWad(uint256 x) internal pure returns (uint256 z) {
                                unchecked {
                                    z = 10 ** 9;
                                    if (x <= type(uint256).max / 10 ** 36 - 1) {
                                        x *= 10 ** 18;
                                        z = 1;
                                    }
                                    z *= sqrt(x);
                                }
                            }
                            /// @dev Returns the cube root of `x`, denominated in `WAD`.
                            function cbrtWad(uint256 x) internal pure returns (uint256 z) {
                                unchecked {
                                    z = 10 ** 12;
                                    if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                                        if (x >= type(uint256).max / 10 ** 36) {
                                            x *= 10 ** 18;
                                            z = 10 ** 6;
                                        } else {
                                            x *= 10 ** 36;
                                            z = 1;
                                        }
                                    }
                                    z *= cbrt(x);
                                }
                            }
                            /// @dev Returns the factorial of `x`.
                            function factorial(uint256 x) internal pure returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(lt(x, 58)) {
                                        mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
                                }
                            }
                            /// @dev Returns the log2 of `x`.
                            /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
                            /// Returns 0 if `x` is zero.
                            function log2(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    // forgefmt: disable-next-item
                                    r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                        0x0706060506020504060203020504030106050205030304010505030400000000))
                                }
                            }
                            /// @dev Returns the log2 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log2Up(uint256 x) internal pure returns (uint256 r) {
                                r = log2(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(shl(r, 1), x))
                                }
                            }
                            /// @dev Returns the log10 of `x`.
                            /// Returns 0 if `x` is zero.
                            function log10(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(lt(x, 100000000000000000000000000000000000000)) {
                                        x := div(x, 100000000000000000000000000000000000000)
                                        r := 38
                                    }
                                    if iszero(lt(x, 100000000000000000000)) {
                                        x := div(x, 100000000000000000000)
                                        r := add(r, 20)
                                    }
                                    if iszero(lt(x, 10000000000)) {
                                        x := div(x, 10000000000)
                                        r := add(r, 10)
                                    }
                                    if iszero(lt(x, 100000)) {
                                        x := div(x, 100000)
                                        r := add(r, 5)
                                    }
                                    r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
                                }
                            }
                            /// @dev Returns the log10 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log10Up(uint256 x) internal pure returns (uint256 r) {
                                r = log10(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(exp(10, r), x))
                                }
                            }
                            /// @dev Returns the log256 of `x`.
                            /// Returns 0 if `x` is zero.
                            function log256(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(shr(3, r), lt(0xff, shr(r, x)))
                                }
                            }
                            /// @dev Returns the log256 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log256Up(uint256 x) internal pure returns (uint256 r) {
                                r = log256(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(shl(shl(3, r), 1), x))
                                }
                            }
                            /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
                            /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
                            function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mantissa := x
                                    if mantissa {
                                        if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                                            mantissa := div(mantissa, 1000000000000000000000000000000000)
                                            exponent := 33
                                        }
                                        if iszero(mod(mantissa, 10000000000000000000)) {
                                            mantissa := div(mantissa, 10000000000000000000)
                                            exponent := add(exponent, 19)
                                        }
                                        if iszero(mod(mantissa, 1000000000000)) {
                                            mantissa := div(mantissa, 1000000000000)
                                            exponent := add(exponent, 12)
                                        }
                                        if iszero(mod(mantissa, 1000000)) {
                                            mantissa := div(mantissa, 1000000)
                                            exponent := add(exponent, 6)
                                        }
                                        if iszero(mod(mantissa, 10000)) {
                                            mantissa := div(mantissa, 10000)
                                            exponent := add(exponent, 4)
                                        }
                                        if iszero(mod(mantissa, 100)) {
                                            mantissa := div(mantissa, 100)
                                            exponent := add(exponent, 2)
                                        }
                                        if iszero(mod(mantissa, 10)) {
                                            mantissa := div(mantissa, 10)
                                            exponent := add(exponent, 1)
                                        }
                                    }
                                }
                            }
                            /// @dev Convenience function for packing `x` into a smaller number using `sci`.
                            /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
                            /// The `exponent` will be in bits [0..6] (the lower 7 bits).
                            /// Use `SafeCastLib` to safely ensure that the `packed` number is small
                            /// enough to fit in the desired unsigned integer type:
                            /// ```
                            ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
                            /// ```
                            function packSci(uint256 x) internal pure returns (uint256 packed) {
                                (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if shr(249, x) {
                                        mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    packed := or(shl(7, x), packed)
                                }
                            }
                            /// @dev Convenience function for unpacking a packed number from `packSci`.
                            function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
                                unchecked {
                                    unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
                                }
                            }
                            /// @dev Returns the average of `x` and `y`.
                            function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = (x & y) + ((x ^ y) >> 1);
                                }
                            }
                            /// @dev Returns the average of `x` and `y`.
                            function avg(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = (x >> 1) + (y >> 1) + (x & y & 1);
                                }
                            }
                            /// @dev Returns the absolute value of `x`.
                            function abs(int256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
                                }
                            }
                            /// @dev Returns the absolute distance between `x` and `y`.
                            function dist(int256 x, int256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
                                }
                            }
                            /// @dev Returns the minimum of `x` and `y`.
                            function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), lt(y, x)))
                                }
                            }
                            /// @dev Returns the minimum of `x` and `y`.
                            function min(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), slt(y, x)))
                                }
                            }
                            /// @dev Returns the maximum of `x` and `y`.
                            function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), gt(y, x)))
                                }
                            }
                            /// @dev Returns the maximum of `x` and `y`.
                            function max(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), sgt(y, x)))
                                }
                            }
                            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                            function clamp(uint256 x, uint256 minValue, uint256 maxValue)
                                internal
                                pure
                                returns (uint256 z)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
                                    z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
                                }
                            }
                            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                            function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
                                    z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
                                }
                            }
                            /// @dev Returns greatest common divisor of `x` and `y`.
                            function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for { z := x } y {} {
                                        let t := y
                                        y := mod(z, y)
                                        z := t
                                    }
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                   RAW NUMBER OPERATIONS                    */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns `x + y`, without checking for overflow.
                            function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x + y;
                                }
                            }
                            /// @dev Returns `x + y`, without checking for overflow.
                            function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x + y;
                                }
                            }
                            /// @dev Returns `x - y`, without checking for underflow.
                            function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x - y;
                                }
                            }
                            /// @dev Returns `x - y`, without checking for underflow.
                            function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x - y;
                                }
                            }
                            /// @dev Returns `x * y`, without checking for overflow.
                            function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x * y;
                                }
                            }
                            /// @dev Returns `x * y`, without checking for overflow.
                            function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x * y;
                                }
                            }
                            /// @dev Returns `x / y`, returning 0 if `y` is zero.
                            function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(x, y)
                                }
                            }
                            /// @dev Returns `x / y`, returning 0 if `y` is zero.
                            function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(x, y)
                                }
                            }
                            /// @dev Returns `x % y`, returning 0 if `y` is zero.
                            function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mod(x, y)
                                }
                            }
                            /// @dev Returns `x % y`, returning 0 if `y` is zero.
                            function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := smod(x, y)
                                }
                            }
                            /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
                            function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := addmod(x, y, d)
                                }
                            }
                            /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
                            function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mulmod(x, y, d)
                                }
                            }
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Simple single owner authorization mixin.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
                        abstract contract Owned {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event OwnershipTransferred(address indexed user, address indexed newOwner);
                            /*//////////////////////////////////////////////////////////////
                                                    OWNERSHIP STORAGE
                            //////////////////////////////////////////////////////////////*/
                            address public owner;
                            modifier onlyOwner() virtual {
                                require(msg.sender == owner, "UNAUTHORIZED");
                                _;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(address _owner) {
                                owner = _owner;
                                emit OwnershipTransferred(address(0), _owner);
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     OWNERSHIP LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function transferOwnership(address newOwner) public virtual onlyOwner {
                                owner = newOwner;
                                emit OwnershipTransferred(msg.sender, newOwner);
                            }
                        }
                        

                        File 2 of 18: WETH9
                        // Copyright (C) 2015, 2016, 2017 Dapphub
                        
                        // This program is free software: you can redistribute it and/or modify
                        // it under the terms of the GNU General Public License as published by
                        // the Free Software Foundation, either version 3 of the License, or
                        // (at your option) any later version.
                        
                        // This program is distributed in the hope that it will be useful,
                        // but WITHOUT ANY WARRANTY; without even the implied warranty of
                        // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                        // GNU General Public License for more details.
                        
                        // You should have received a copy of the GNU General Public License
                        // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                        
                        pragma solidity ^0.4.18;
                        
                        contract WETH9 {
                            string public name     = "Wrapped Ether";
                            string public symbol   = "WETH";
                            uint8  public decimals = 18;
                        
                            event  Approval(address indexed src, address indexed guy, uint wad);
                            event  Transfer(address indexed src, address indexed dst, uint wad);
                            event  Deposit(address indexed dst, uint wad);
                            event  Withdrawal(address indexed src, uint wad);
                        
                            mapping (address => uint)                       public  balanceOf;
                            mapping (address => mapping (address => uint))  public  allowance;
                        
                            function() public payable {
                                deposit();
                            }
                            function deposit() public payable {
                                balanceOf[msg.sender] += msg.value;
                                Deposit(msg.sender, msg.value);
                            }
                            function withdraw(uint wad) public {
                                require(balanceOf[msg.sender] >= wad);
                                balanceOf[msg.sender] -= wad;
                                msg.sender.transfer(wad);
                                Withdrawal(msg.sender, wad);
                            }
                        
                            function totalSupply() public view returns (uint) {
                                return this.balance;
                            }
                        
                            function approve(address guy, uint wad) public returns (bool) {
                                allowance[msg.sender][guy] = wad;
                                Approval(msg.sender, guy, wad);
                                return true;
                            }
                        
                            function transfer(address dst, uint wad) public returns (bool) {
                                return transferFrom(msg.sender, dst, wad);
                            }
                        
                            function transferFrom(address src, address dst, uint wad)
                                public
                                returns (bool)
                            {
                                require(balanceOf[src] >= wad);
                        
                                if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                                    require(allowance[src][msg.sender] >= wad);
                                    allowance[src][msg.sender] -= wad;
                                }
                        
                                balanceOf[src] -= wad;
                                balanceOf[dst] += wad;
                        
                                Transfer(src, dst, wad);
                        
                                return true;
                            }
                        }
                        
                        
                        /*
                                            GNU GENERAL PUBLIC LICENSE
                                               Version 3, 29 June 2007
                        
                         Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
                         Everyone is permitted to copy and distribute verbatim copies
                         of this license document, but changing it is not allowed.
                        
                                                    Preamble
                        
                          The GNU General Public License is a free, copyleft license for
                        software and other kinds of works.
                        
                          The licenses for most software and other practical works are designed
                        to take away your freedom to share and change the works.  By contrast,
                        the GNU General Public License is intended to guarantee your freedom to
                        share and change all versions of a program--to make sure it remains free
                        software for all its users.  We, the Free Software Foundation, use the
                        GNU General Public License for most of our software; it applies also to
                        any other work released this way by its authors.  You can apply it to
                        your programs, too.
                        
                          When we speak of free software, we are referring to freedom, not
                        price.  Our General Public Licenses are designed to make sure that you
                        have the freedom to distribute copies of free software (and charge for
                        them if you wish), that you receive source code or can get it if you
                        want it, that you can change the software or use pieces of it in new
                        free programs, and that you know you can do these things.
                        
                          To protect your rights, we need to prevent others from denying you
                        these rights or asking you to surrender the rights.  Therefore, you have
                        certain responsibilities if you distribute copies of the software, or if
                        you modify it: responsibilities to respect the freedom of others.
                        
                          For example, if you distribute copies of such a program, whether
                        gratis or for a fee, you must pass on to the recipients the same
                        freedoms that you received.  You must make sure that they, too, receive
                        or can get the source code.  And you must show them these terms so they
                        know their rights.
                        
                          Developers that use the GNU GPL protect your rights with two steps:
                        (1) assert copyright on the software, and (2) offer you this License
                        giving you legal permission to copy, distribute and/or modify it.
                        
                          For the developers' and authors' protection, the GPL clearly explains
                        that there is no warranty for this free software.  For both users' and
                        authors' sake, the GPL requires that modified versions be marked as
                        changed, so that their problems will not be attributed erroneously to
                        authors of previous versions.
                        
                          Some devices are designed to deny users access to install or run
                        modified versions of the software inside them, although the manufacturer
                        can do so.  This is fundamentally incompatible with the aim of
                        protecting users' freedom to change the software.  The systematic
                        pattern of such abuse occurs in the area of products for individuals to
                        use, which is precisely where it is most unacceptable.  Therefore, we
                        have designed this version of the GPL to prohibit the practice for those
                        products.  If such problems arise substantially in other domains, we
                        stand ready to extend this provision to those domains in future versions
                        of the GPL, as needed to protect the freedom of users.
                        
                          Finally, every program is threatened constantly by software patents.
                        States should not allow patents to restrict development and use of
                        software on general-purpose computers, but in those that do, we wish to
                        avoid the special danger that patents applied to a free program could
                        make it effectively proprietary.  To prevent this, the GPL assures that
                        patents cannot be used to render the program non-free.
                        
                          The precise terms and conditions for copying, distribution and
                        modification follow.
                        
                                               TERMS AND CONDITIONS
                        
                          0. Definitions.
                        
                          "This License" refers to version 3 of the GNU General Public License.
                        
                          "Copyright" also means copyright-like laws that apply to other kinds of
                        works, such as semiconductor masks.
                        
                          "The Program" refers to any copyrightable work licensed under this
                        License.  Each licensee is addressed as "you".  "Licensees" and
                        "recipients" may be individuals or organizations.
                        
                          To "modify" a work means to copy from or adapt all or part of the work
                        in a fashion requiring copyright permission, other than the making of an
                        exact copy.  The resulting work is called a "modified version" of the
                        earlier work or a work "based on" the earlier work.
                        
                          A "covered work" means either the unmodified Program or a work based
                        on the Program.
                        
                          To "propagate" a work means to do anything with it that, without
                        permission, would make you directly or secondarily liable for
                        infringement under applicable copyright law, except executing it on a
                        computer or modifying a private copy.  Propagation includes copying,
                        distribution (with or without modification), making available to the
                        public, and in some countries other activities as well.
                        
                          To "convey" a work means any kind of propagation that enables other
                        parties to make or receive copies.  Mere interaction with a user through
                        a computer network, with no transfer of a copy, is not conveying.
                        
                          An interactive user interface displays "Appropriate Legal Notices"
                        to the extent that it includes a convenient and prominently visible
                        feature that (1) displays an appropriate copyright notice, and (2)
                        tells the user that there is no warranty for the work (except to the
                        extent that warranties are provided), that licensees may convey the
                        work under this License, and how to view a copy of this License.  If
                        the interface presents a list of user commands or options, such as a
                        menu, a prominent item in the list meets this criterion.
                        
                          1. Source Code.
                        
                          The "source code" for a work means the preferred form of the work
                        for making modifications to it.  "Object code" means any non-source
                        form of a work.
                        
                          A "Standard Interface" means an interface that either is an official
                        standard defined by a recognized standards body, or, in the case of
                        interfaces specified for a particular programming language, one that
                        is widely used among developers working in that language.
                        
                          The "System Libraries" of an executable work include anything, other
                        than the work as a whole, that (a) is included in the normal form of
                        packaging a Major Component, but which is not part of that Major
                        Component, and (b) serves only to enable use of the work with that
                        Major Component, or to implement a Standard Interface for which an
                        implementation is available to the public in source code form.  A
                        "Major Component", in this context, means a major essential component
                        (kernel, window system, and so on) of the specific operating system
                        (if any) on which the executable work runs, or a compiler used to
                        produce the work, or an object code interpreter used to run it.
                        
                          The "Corresponding Source" for a work in object code form means all
                        the source code needed to generate, install, and (for an executable
                        work) run the object code and to modify the work, including scripts to
                        control those activities.  However, it does not include the work's
                        System Libraries, or general-purpose tools or generally available free
                        programs which are used unmodified in performing those activities but
                        which are not part of the work.  For example, Corresponding Source
                        includes interface definition files associated with source files for
                        the work, and the source code for shared libraries and dynamically
                        linked subprograms that the work is specifically designed to require,
                        such as by intimate data communication or control flow between those
                        subprograms and other parts of the work.
                        
                          The Corresponding Source need not include anything that users
                        can regenerate automatically from other parts of the Corresponding
                        Source.
                        
                          The Corresponding Source for a work in source code form is that
                        same work.
                        
                          2. Basic Permissions.
                        
                          All rights granted under this License are granted for the term of
                        copyright on the Program, and are irrevocable provided the stated
                        conditions are met.  This License explicitly affirms your unlimited
                        permission to run the unmodified Program.  The output from running a
                        covered work is covered by this License only if the output, given its
                        content, constitutes a covered work.  This License acknowledges your
                        rights of fair use or other equivalent, as provided by copyright law.
                        
                          You may make, run and propagate covered works that you do not
                        convey, without conditions so long as your license otherwise remains
                        in force.  You may convey covered works to others for the sole purpose
                        of having them make modifications exclusively for you, or provide you
                        with facilities for running those works, provided that you comply with
                        the terms of this License in conveying all material for which you do
                        not control copyright.  Those thus making or running the covered works
                        for you must do so exclusively on your behalf, under your direction
                        and control, on terms that prohibit them from making any copies of
                        your copyrighted material outside their relationship with you.
                        
                          Conveying under any other circumstances is permitted solely under
                        the conditions stated below.  Sublicensing is not allowed; section 10
                        makes it unnecessary.
                        
                          3. Protecting Users' Legal Rights From Anti-Circumvention Law.
                        
                          No covered work shall be deemed part of an effective technological
                        measure under any applicable law fulfilling obligations under article
                        11 of the WIPO copyright treaty adopted on 20 December 1996, or
                        similar laws prohibiting or restricting circumvention of such
                        measures.
                        
                          When you convey a covered work, you waive any legal power to forbid
                        circumvention of technological measures to the extent such circumvention
                        is effected by exercising rights under this License with respect to
                        the covered work, and you disclaim any intention to limit operation or
                        modification of the work as a means of enforcing, against the work's
                        users, your or third parties' legal rights to forbid circumvention of
                        technological measures.
                        
                          4. Conveying Verbatim Copies.
                        
                          You may convey verbatim copies of the Program's source code as you
                        receive it, in any medium, provided that you conspicuously and
                        appropriately publish on each copy an appropriate copyright notice;
                        keep intact all notices stating that this License and any
                        non-permissive terms added in accord with section 7 apply to the code;
                        keep intact all notices of the absence of any warranty; and give all
                        recipients a copy of this License along with the Program.
                        
                          You may charge any price or no price for each copy that you convey,
                        and you may offer support or warranty protection for a fee.
                        
                          5. Conveying Modified Source Versions.
                        
                          You may convey a work based on the Program, or the modifications to
                        produce it from the Program, in the form of source code under the
                        terms of section 4, provided that you also meet all of these conditions:
                        
                            a) The work must carry prominent notices stating that you modified
                            it, and giving a relevant date.
                        
                            b) The work must carry prominent notices stating that it is
                            released under this License and any conditions added under section
                            7.  This requirement modifies the requirement in section 4 to
                            "keep intact all notices".
                        
                            c) You must license the entire work, as a whole, under this
                            License to anyone who comes into possession of a copy.  This
                            License will therefore apply, along with any applicable section 7
                            additional terms, to the whole of the work, and all its parts,
                            regardless of how they are packaged.  This License gives no
                            permission to license the work in any other way, but it does not
                            invalidate such permission if you have separately received it.
                        
                            d) If the work has interactive user interfaces, each must display
                            Appropriate Legal Notices; however, if the Program has interactive
                            interfaces that do not display Appropriate Legal Notices, your
                            work need not make them do so.
                        
                          A compilation of a covered work with other separate and independent
                        works, which are not by their nature extensions of the covered work,
                        and which are not combined with it such as to form a larger program,
                        in or on a volume of a storage or distribution medium, is called an
                        "aggregate" if the compilation and its resulting copyright are not
                        used to limit the access or legal rights of the compilation's users
                        beyond what the individual works permit.  Inclusion of a covered work
                        in an aggregate does not cause this License to apply to the other
                        parts of the aggregate.
                        
                          6. Conveying Non-Source Forms.
                        
                          You may convey a covered work in object code form under the terms
                        of sections 4 and 5, provided that you also convey the
                        machine-readable Corresponding Source under the terms of this License,
                        in one of these ways:
                        
                            a) Convey the object code in, or embodied in, a physical product
                            (including a physical distribution medium), accompanied by the
                            Corresponding Source fixed on a durable physical medium
                            customarily used for software interchange.
                        
                            b) Convey the object code in, or embodied in, a physical product
                            (including a physical distribution medium), accompanied by a
                            written offer, valid for at least three years and valid for as
                            long as you offer spare parts or customer support for that product
                            model, to give anyone who possesses the object code either (1) a
                            copy of the Corresponding Source for all the software in the
                            product that is covered by this License, on a durable physical
                            medium customarily used for software interchange, for a price no
                            more than your reasonable cost of physically performing this
                            conveying of source, or (2) access to copy the
                            Corresponding Source from a network server at no charge.
                        
                            c) Convey individual copies of the object code with a copy of the
                            written offer to provide the Corresponding Source.  This
                            alternative is allowed only occasionally and noncommercially, and
                            only if you received the object code with such an offer, in accord
                            with subsection 6b.
                        
                            d) Convey the object code by offering access from a designated
                            place (gratis or for a charge), and offer equivalent access to the
                            Corresponding Source in the same way through the same place at no
                            further charge.  You need not require recipients to copy the
                            Corresponding Source along with the object code.  If the place to
                            copy the object code is a network server, the Corresponding Source
                            may be on a different server (operated by you or a third party)
                            that supports equivalent copying facilities, provided you maintain
                            clear directions next to the object code saying where to find the
                            Corresponding Source.  Regardless of what server hosts the
                            Corresponding Source, you remain obligated to ensure that it is
                            available for as long as needed to satisfy these requirements.
                        
                            e) Convey the object code using peer-to-peer transmission, provided
                            you inform other peers where the object code and Corresponding
                            Source of the work are being offered to the general public at no
                            charge under subsection 6d.
                        
                          A separable portion of the object code, whose source code is excluded
                        from the Corresponding Source as a System Library, need not be
                        included in conveying the object code work.
                        
                          A "User Product" is either (1) a "consumer product", which means any
                        tangible personal property which is normally used for personal, family,
                        or household purposes, or (2) anything designed or sold for incorporation
                        into a dwelling.  In determining whether a product is a consumer product,
                        doubtful cases shall be resolved in favor of coverage.  For a particular
                        product received by a particular user, "normally used" refers to a
                        typical or common use of that class of product, regardless of the status
                        of the particular user or of the way in which the particular user
                        actually uses, or expects or is expected to use, the product.  A product
                        is a consumer product regardless of whether the product has substantial
                        commercial, industrial or non-consumer uses, unless such uses represent
                        the only significant mode of use of the product.
                        
                          "Installation Information" for a User Product means any methods,
                        procedures, authorization keys, or other information required to install
                        and execute modified versions of a covered work in that User Product from
                        a modified version of its Corresponding Source.  The information must
                        suffice to ensure that the continued functioning of the modified object
                        code is in no case prevented or interfered with solely because
                        modification has been made.
                        
                          If you convey an object code work under this section in, or with, or
                        specifically for use in, a User Product, and the conveying occurs as
                        part of a transaction in which the right of possession and use of the
                        User Product is transferred to the recipient in perpetuity or for a
                        fixed term (regardless of how the transaction is characterized), the
                        Corresponding Source conveyed under this section must be accompanied
                        by the Installation Information.  But this requirement does not apply
                        if neither you nor any third party retains the ability to install
                        modified object code on the User Product (for example, the work has
                        been installed in ROM).
                        
                          The requirement to provide Installation Information does not include a
                        requirement to continue to provide support service, warranty, or updates
                        for a work that has been modified or installed by the recipient, or for
                        the User Product in which it has been modified or installed.  Access to a
                        network may be denied when the modification itself materially and
                        adversely affects the operation of the network or violates the rules and
                        protocols for communication across the network.
                        
                          Corresponding Source conveyed, and Installation Information provided,
                        in accord with this section must be in a format that is publicly
                        documented (and with an implementation available to the public in
                        source code form), and must require no special password or key for
                        unpacking, reading or copying.
                        
                          7. Additional Terms.
                        
                          "Additional permissions" are terms that supplement the terms of this
                        License by making exceptions from one or more of its conditions.
                        Additional permissions that are applicable to the entire Program shall
                        be treated as though they were included in this License, to the extent
                        that they are valid under applicable law.  If additional permissions
                        apply only to part of the Program, that part may be used separately
                        under those permissions, but the entire Program remains governed by
                        this License without regard to the additional permissions.
                        
                          When you convey a copy of a covered work, you may at your option
                        remove any additional permissions from that copy, or from any part of
                        it.  (Additional permissions may be written to require their own
                        removal in certain cases when you modify the work.)  You may place
                        additional permissions on material, added by you to a covered work,
                        for which you have or can give appropriate copyright permission.
                        
                          Notwithstanding any other provision of this License, for material you
                        add to a covered work, you may (if authorized by the copyright holders of
                        that material) supplement the terms of this License with terms:
                        
                            a) Disclaiming warranty or limiting liability differently from the
                            terms of sections 15 and 16 of this License; or
                        
                            b) Requiring preservation of specified reasonable legal notices or
                            author attributions in that material or in the Appropriate Legal
                            Notices displayed by works containing it; or
                        
                            c) Prohibiting misrepresentation of the origin of that material, or
                            requiring that modified versions of such material be marked in
                            reasonable ways as different from the original version; or
                        
                            d) Limiting the use for publicity purposes of names of licensors or
                            authors of the material; or
                        
                            e) Declining to grant rights under trademark law for use of some
                            trade names, trademarks, or service marks; or
                        
                            f) Requiring indemnification of licensors and authors of that
                            material by anyone who conveys the material (or modified versions of
                            it) with contractual assumptions of liability to the recipient, for
                            any liability that these contractual assumptions directly impose on
                            those licensors and authors.
                        
                          All other non-permissive additional terms are considered "further
                        restrictions" within the meaning of section 10.  If the Program as you
                        received it, or any part of it, contains a notice stating that it is
                        governed by this License along with a term that is a further
                        restriction, you may remove that term.  If a license document contains
                        a further restriction but permits relicensing or conveying under this
                        License, you may add to a covered work material governed by the terms
                        of that license document, provided that the further restriction does
                        not survive such relicensing or conveying.
                        
                          If you add terms to a covered work in accord with this section, you
                        must place, in the relevant source files, a statement of the
                        additional terms that apply to those files, or a notice indicating
                        where to find the applicable terms.
                        
                          Additional terms, permissive or non-permissive, may be stated in the
                        form of a separately written license, or stated as exceptions;
                        the above requirements apply either way.
                        
                          8. Termination.
                        
                          You may not propagate or modify a covered work except as expressly
                        provided under this License.  Any attempt otherwise to propagate or
                        modify it is void, and will automatically terminate your rights under
                        this License (including any patent licenses granted under the third
                        paragraph of section 11).
                        
                          However, if you cease all violation of this License, then your
                        license from a particular copyright holder is reinstated (a)
                        provisionally, unless and until the copyright holder explicitly and
                        finally terminates your license, and (b) permanently, if the copyright
                        holder fails to notify you of the violation by some reasonable means
                        prior to 60 days after the cessation.
                        
                          Moreover, your license from a particular copyright holder is
                        reinstated permanently if the copyright holder notifies you of the
                        violation by some reasonable means, this is the first time you have
                        received notice of violation of this License (for any work) from that
                        copyright holder, and you cure the violation prior to 30 days after
                        your receipt of the notice.
                        
                          Termination of your rights under this section does not terminate the
                        licenses of parties who have received copies or rights from you under
                        this License.  If your rights have been terminated and not permanently
                        reinstated, you do not qualify to receive new licenses for the same
                        material under section 10.
                        
                          9. Acceptance Not Required for Having Copies.
                        
                          You are not required to accept this License in order to receive or
                        run a copy of the Program.  Ancillary propagation of a covered work
                        occurring solely as a consequence of using peer-to-peer transmission
                        to receive a copy likewise does not require acceptance.  However,
                        nothing other than this License grants you permission to propagate or
                        modify any covered work.  These actions infringe copyright if you do
                        not accept this License.  Therefore, by modifying or propagating a
                        covered work, you indicate your acceptance of this License to do so.
                        
                          10. Automatic Licensing of Downstream Recipients.
                        
                          Each time you convey a covered work, the recipient automatically
                        receives a license from the original licensors, to run, modify and
                        propagate that work, subject to this License.  You are not responsible
                        for enforcing compliance by third parties with this License.
                        
                          An "entity transaction" is a transaction transferring control of an
                        organization, or substantially all assets of one, or subdividing an
                        organization, or merging organizations.  If propagation of a covered
                        work results from an entity transaction, each party to that
                        transaction who receives a copy of the work also receives whatever
                        licenses to the work the party's predecessor in interest had or could
                        give under the previous paragraph, plus a right to possession of the
                        Corresponding Source of the work from the predecessor in interest, if
                        the predecessor has it or can get it with reasonable efforts.
                        
                          You may not impose any further restrictions on the exercise of the
                        rights granted or affirmed under this License.  For example, you may
                        not impose a license fee, royalty, or other charge for exercise of
                        rights granted under this License, and you may not initiate litigation
                        (including a cross-claim or counterclaim in a lawsuit) alleging that
                        any patent claim is infringed by making, using, selling, offering for
                        sale, or importing the Program or any portion of it.
                        
                          11. Patents.
                        
                          A "contributor" is a copyright holder who authorizes use under this
                        License of the Program or a work on which the Program is based.  The
                        work thus licensed is called the contributor's "contributor version".
                        
                          A contributor's "essential patent claims" are all patent claims
                        owned or controlled by the contributor, whether already acquired or
                        hereafter acquired, that would be infringed by some manner, permitted
                        by this License, of making, using, or selling its contributor version,
                        but do not include claims that would be infringed only as a
                        consequence of further modification of the contributor version.  For
                        purposes of this definition, "control" includes the right to grant
                        patent sublicenses in a manner consistent with the requirements of
                        this License.
                        
                          Each contributor grants you a non-exclusive, worldwide, royalty-free
                        patent license under the contributor's essential patent claims, to
                        make, use, sell, offer for sale, import and otherwise run, modify and
                        propagate the contents of its contributor version.
                        
                          In the following three paragraphs, a "patent license" is any express
                        agreement or commitment, however denominated, not to enforce a patent
                        (such as an express permission to practice a patent or covenant not to
                        sue for patent infringement).  To "grant" such a patent license to a
                        party means to make such an agreement or commitment not to enforce a
                        patent against the party.
                        
                          If you convey a covered work, knowingly relying on a patent license,
                        and the Corresponding Source of the work is not available for anyone
                        to copy, free of charge and under the terms of this License, through a
                        publicly available network server or other readily accessible means,
                        then you must either (1) cause the Corresponding Source to be so
                        available, or (2) arrange to deprive yourself of the benefit of the
                        patent license for this particular work, or (3) arrange, in a manner
                        consistent with the requirements of this License, to extend the patent
                        license to downstream recipients.  "Knowingly relying" means you have
                        actual knowledge that, but for the patent license, your conveying the
                        covered work in a country, or your recipient's use of the covered work
                        in a country, would infringe one or more identifiable patents in that
                        country that you have reason to believe are valid.
                        
                          If, pursuant to or in connection with a single transaction or
                        arrangement, you convey, or propagate by procuring conveyance of, a
                        covered work, and grant a patent license to some of the parties
                        receiving the covered work authorizing them to use, propagate, modify
                        or convey a specific copy of the covered work, then the patent license
                        you grant is automatically extended to all recipients of the covered
                        work and works based on it.
                        
                          A patent license is "discriminatory" if it does not include within
                        the scope of its coverage, prohibits the exercise of, or is
                        conditioned on the non-exercise of one or more of the rights that are
                        specifically granted under this License.  You may not convey a covered
                        work if you are a party to an arrangement with a third party that is
                        in the business of distributing software, under which you make payment
                        to the third party based on the extent of your activity of conveying
                        the work, and under which the third party grants, to any of the
                        parties who would receive the covered work from you, a discriminatory
                        patent license (a) in connection with copies of the covered work
                        conveyed by you (or copies made from those copies), or (b) primarily
                        for and in connection with specific products or compilations that
                        contain the covered work, unless you entered into that arrangement,
                        or that patent license was granted, prior to 28 March 2007.
                        
                          Nothing in this License shall be construed as excluding or limiting
                        any implied license or other defenses to infringement that may
                        otherwise be available to you under applicable patent law.
                        
                          12. No Surrender of Others' Freedom.
                        
                          If conditions are imposed on you (whether by court order, agreement or
                        otherwise) that contradict the conditions of this License, they do not
                        excuse you from the conditions of this License.  If you cannot convey a
                        covered work so as to satisfy simultaneously your obligations under this
                        License and any other pertinent obligations, then as a consequence you may
                        not convey it at all.  For example, if you agree to terms that obligate you
                        to collect a royalty for further conveying from those to whom you convey
                        the Program, the only way you could satisfy both those terms and this
                        License would be to refrain entirely from conveying the Program.
                        
                          13. Use with the GNU Affero General Public License.
                        
                          Notwithstanding any other provision of this License, you have
                        permission to link or combine any covered work with a work licensed
                        under version 3 of the GNU Affero General Public License into a single
                        combined work, and to convey the resulting work.  The terms of this
                        License will continue to apply to the part which is the covered work,
                        but the special requirements of the GNU Affero General Public License,
                        section 13, concerning interaction through a network will apply to the
                        combination as such.
                        
                          14. Revised Versions of this License.
                        
                          The Free Software Foundation may publish revised and/or new versions of
                        the GNU General Public License from time to time.  Such new versions will
                        be similar in spirit to the present version, but may differ in detail to
                        address new problems or concerns.
                        
                          Each version is given a distinguishing version number.  If the
                        Program specifies that a certain numbered version of the GNU General
                        Public License "or any later version" applies to it, you have the
                        option of following the terms and conditions either of that numbered
                        version or of any later version published by the Free Software
                        Foundation.  If the Program does not specify a version number of the
                        GNU General Public License, you may choose any version ever published
                        by the Free Software Foundation.
                        
                          If the Program specifies that a proxy can decide which future
                        versions of the GNU General Public License can be used, that proxy's
                        public statement of acceptance of a version permanently authorizes you
                        to choose that version for the Program.
                        
                          Later license versions may give you additional or different
                        permissions.  However, no additional obligations are imposed on any
                        author or copyright holder as a result of your choosing to follow a
                        later version.
                        
                          15. Disclaimer of Warranty.
                        
                          THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
                        APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
                        HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
                        OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
                        THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                        PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
                        IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
                        ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
                        
                          16. Limitation of Liability.
                        
                          IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                        WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
                        THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
                        GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
                        USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
                        DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
                        PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
                        EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
                        SUCH DAMAGES.
                        
                          17. Interpretation of Sections 15 and 16.
                        
                          If the disclaimer of warranty and limitation of liability provided
                        above cannot be given local legal effect according to their terms,
                        reviewing courts shall apply local law that most closely approximates
                        an absolute waiver of all civil liability in connection with the
                        Program, unless a warranty or assumption of liability accompanies a
                        copy of the Program in return for a fee.
                        
                                             END OF TERMS AND CONDITIONS
                        
                                    How to Apply These Terms to Your New Programs
                        
                          If you develop a new program, and you want it to be of the greatest
                        possible use to the public, the best way to achieve this is to make it
                        free software which everyone can redistribute and change under these terms.
                        
                          To do so, attach the following notices to the program.  It is safest
                        to attach them to the start of each source file to most effectively
                        state the exclusion of warranty; and each file should have at least
                        the "copyright" line and a pointer to where the full notice is found.
                        
                            <one line to give the program's name and a brief idea of what it does.>
                            Copyright (C) <year>  <name of author>
                        
                            This program is free software: you can redistribute it and/or modify
                            it under the terms of the GNU General Public License as published by
                            the Free Software Foundation, either version 3 of the License, or
                            (at your option) any later version.
                        
                            This program is distributed in the hope that it will be useful,
                            but WITHOUT ANY WARRANTY; without even the implied warranty of
                            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                            GNU General Public License for more details.
                        
                            You should have received a copy of the GNU General Public License
                            along with this program.  If not, see <http://www.gnu.org/licenses/>.
                        
                        Also add information on how to contact you by electronic and paper mail.
                        
                          If the program does terminal interaction, make it output a short
                        notice like this when it starts in an interactive mode:
                        
                            <program>  Copyright (C) <year>  <name of author>
                            This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                            This is free software, and you are welcome to redistribute it
                            under certain conditions; type `show c' for details.
                        
                        The hypothetical commands `show w' and `show c' should show the appropriate
                        parts of the General Public License.  Of course, your program's commands
                        might be different; for a GUI interface, you would use an "about box".
                        
                          You should also get your employer (if you work as a programmer) or school,
                        if any, to sign a "copyright disclaimer" for the program, if necessary.
                        For more information on this, and how to apply and follow the GNU GPL, see
                        <http://www.gnu.org/licenses/>.
                        
                          The GNU General Public License does not permit incorporating your program
                        into proprietary programs.  If your program is a subroutine library, you
                        may consider it more useful to permit linking proprietary applications with
                        the library.  If this is what you want to do, use the GNU Lesser General
                        Public License instead of this License.  But first, please read
                        <http://www.gnu.org/philosophy/why-not-lgpl.html>.
                        
                        */

                        File 3 of 18: UniswapV2Pair
                        // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
                        
                        pragma solidity >=0.5.0;
                        
                        interface IUniswapV2Factory {
                            event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                        
                            function feeTo() external view returns (address);
                            function feeToSetter() external view returns (address);
                            function migrator() external view returns (address);
                        
                            function getPair(address tokenA, address tokenB) external view returns (address pair);
                            function allPairs(uint) external view returns (address pair);
                            function allPairsLength() external view returns (uint);
                        
                            function createPair(address tokenA, address tokenB) external returns (address pair);
                        
                            function setFeeTo(address) external;
                            function setFeeToSetter(address) external;
                            function setMigrator(address) external;
                        }
                        
                        // File: contracts/uniswapv2/libraries/SafeMath.sol
                        
                        pragma solidity =0.6.12;
                        
                        // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                        
                        library SafeMathUniswap {
                            function add(uint x, uint y) internal pure returns (uint z) {
                                require((z = x + y) >= x, 'ds-math-add-overflow');
                            }
                        
                            function sub(uint x, uint y) internal pure returns (uint z) {
                                require((z = x - y) <= x, 'ds-math-sub-underflow');
                            }
                        
                            function mul(uint x, uint y) internal pure returns (uint z) {
                                require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                            }
                        }
                        
                        // File: contracts/uniswapv2/UniswapV2ERC20.sol
                        
                        pragma solidity =0.6.12;
                        
                        
                        contract UniswapV2ERC20 {
                            using SafeMathUniswap for uint;
                        
                            string public constant name = 'SushiSwap LP Token';
                            string public constant symbol = 'SLP';
                            uint8 public constant decimals = 18;
                            uint  public totalSupply;
                            mapping(address => uint) public balanceOf;
                            mapping(address => mapping(address => uint)) public allowance;
                        
                            bytes32 public DOMAIN_SEPARATOR;
                            // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                            bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                            mapping(address => uint) public nonces;
                        
                            event Approval(address indexed owner, address indexed spender, uint value);
                            event Transfer(address indexed from, address indexed to, uint value);
                        
                            constructor() public {
                                uint chainId;
                                assembly {
                                    chainId := chainid()
                                }
                                DOMAIN_SEPARATOR = keccak256(
                                    abi.encode(
                                        keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                        keccak256(bytes(name)),
                                        keccak256(bytes('1')),
                                        chainId,
                                        address(this)
                                    )
                                );
                            }
                        
                            function _mint(address to, uint value) internal {
                                totalSupply = totalSupply.add(value);
                                balanceOf[to] = balanceOf[to].add(value);
                                emit Transfer(address(0), to, value);
                            }
                        
                            function _burn(address from, uint value) internal {
                                balanceOf[from] = balanceOf[from].sub(value);
                                totalSupply = totalSupply.sub(value);
                                emit Transfer(from, address(0), value);
                            }
                        
                            function _approve(address owner, address spender, uint value) private {
                                allowance[owner][spender] = value;
                                emit Approval(owner, spender, value);
                            }
                        
                            function _transfer(address from, address to, uint value) private {
                                balanceOf[from] = balanceOf[from].sub(value);
                                balanceOf[to] = balanceOf[to].add(value);
                                emit Transfer(from, to, value);
                            }
                        
                            function approve(address spender, uint value) external returns (bool) {
                                _approve(msg.sender, spender, value);
                                return true;
                            }
                        
                            function transfer(address to, uint value) external returns (bool) {
                                _transfer(msg.sender, to, value);
                                return true;
                            }
                        
                            function transferFrom(address from, address to, uint value) external returns (bool) {
                                if (allowance[from][msg.sender] != uint(-1)) {
                                    allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                }
                                _transfer(from, to, value);
                                return true;
                            }
                        
                            function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                                require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                                bytes32 digest = keccak256(
                                    abi.encodePacked(
                                        '\x19\x01',
                                        DOMAIN_SEPARATOR,
                                        keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                    )
                                );
                                address recoveredAddress = ecrecover(digest, v, r, s);
                                require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                                _approve(owner, spender, value);
                            }
                        }
                        
                        // File: contracts/uniswapv2/libraries/Math.sol
                        
                        pragma solidity =0.6.12;
                        
                        // a library for performing various math operations
                        
                        library Math {
                            function min(uint x, uint y) internal pure returns (uint z) {
                                z = x < y ? x : y;
                            }
                        
                            // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                            function sqrt(uint y) internal pure returns (uint z) {
                                if (y > 3) {
                                    z = y;
                                    uint x = y / 2 + 1;
                                    while (x < z) {
                                        z = x;
                                        x = (y / x + x) / 2;
                                    }
                                } else if (y != 0) {
                                    z = 1;
                                }
                            }
                        }
                        
                        // File: contracts/uniswapv2/libraries/UQ112x112.sol
                        
                        pragma solidity =0.6.12;
                        
                        // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                        
                        // range: [0, 2**112 - 1]
                        // resolution: 1 / 2**112
                        
                        library UQ112x112 {
                            uint224 constant Q112 = 2**112;
                        
                            // encode a uint112 as a UQ112x112
                            function encode(uint112 y) internal pure returns (uint224 z) {
                                z = uint224(y) * Q112; // never overflows
                            }
                        
                            // divide a UQ112x112 by a uint112, returning a UQ112x112
                            function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                                z = x / uint224(y);
                            }
                        }
                        
                        // File: contracts/uniswapv2/interfaces/IERC20.sol
                        
                        pragma solidity >=0.5.0;
                        
                        interface IERC20Uniswap {
                            event Approval(address indexed owner, address indexed spender, uint value);
                            event Transfer(address indexed from, address indexed to, uint value);
                        
                            function name() external view returns (string memory);
                            function symbol() external view returns (string memory);
                            function decimals() external view returns (uint8);
                            function totalSupply() external view returns (uint);
                            function balanceOf(address owner) external view returns (uint);
                            function allowance(address owner, address spender) external view returns (uint);
                        
                            function approve(address spender, uint value) external returns (bool);
                            function transfer(address to, uint value) external returns (bool);
                            function transferFrom(address from, address to, uint value) external returns (bool);
                        }
                        
                        // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol
                        
                        pragma solidity >=0.5.0;
                        
                        interface IUniswapV2Callee {
                            function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                        }
                        
                        // File: contracts/uniswapv2/UniswapV2Pair.sol
                        
                        pragma solidity =0.6.12;
                        
                        
                        
                        
                        
                        
                        
                        
                        interface IMigrator {
                            // Return the desired amount of liquidity token that the migrator wants.
                            function desiredLiquidity() external view returns (uint256);
                        }
                        
                        contract UniswapV2Pair is UniswapV2ERC20 {
                            using SafeMathUniswap  for uint;
                            using UQ112x112 for uint224;
                        
                            uint public constant MINIMUM_LIQUIDITY = 10**3;
                            bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                        
                            address public factory;
                            address public token0;
                            address public token1;
                        
                            uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                            uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                            uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                        
                            uint public price0CumulativeLast;
                            uint public price1CumulativeLast;
                            uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                        
                            uint private unlocked = 1;
                            modifier lock() {
                                require(unlocked == 1, 'UniswapV2: LOCKED');
                                unlocked = 0;
                                _;
                                unlocked = 1;
                            }
                        
                            function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                                _reserve0 = reserve0;
                                _reserve1 = reserve1;
                                _blockTimestampLast = blockTimestampLast;
                            }
                        
                            function _safeTransfer(address token, address to, uint value) private {
                                (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                                require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                            }
                        
                            event Mint(address indexed sender, uint amount0, uint amount1);
                            event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                            event Swap(
                                address indexed sender,
                                uint amount0In,
                                uint amount1In,
                                uint amount0Out,
                                uint amount1Out,
                                address indexed to
                            );
                            event Sync(uint112 reserve0, uint112 reserve1);
                        
                            constructor() public {
                                factory = msg.sender;
                            }
                        
                            // called once by the factory at time of deployment
                            function initialize(address _token0, address _token1) external {
                                require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                                token0 = _token0;
                                token1 = _token1;
                            }
                        
                            // update reserves and, on the first call per block, price accumulators
                            function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                                require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                                uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                                uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                                if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                    // * never overflows, and + overflow is desired
                                    price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                    price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                }
                                reserve0 = uint112(balance0);
                                reserve1 = uint112(balance1);
                                blockTimestampLast = blockTimestamp;
                                emit Sync(reserve0, reserve1);
                            }
                        
                            // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                            function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                                address feeTo = IUniswapV2Factory(factory).feeTo();
                                feeOn = feeTo != address(0);
                                uint _kLast = kLast; // gas savings
                                if (feeOn) {
                                    if (_kLast != 0) {
                                        uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                        uint rootKLast = Math.sqrt(_kLast);
                                        if (rootK > rootKLast) {
                                            uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                            uint denominator = rootK.mul(5).add(rootKLast);
                                            uint liquidity = numerator / denominator;
                                            if (liquidity > 0) _mint(feeTo, liquidity);
                                        }
                                    }
                                } else if (_kLast != 0) {
                                    kLast = 0;
                                }
                            }
                        
                            // this low-level function should be called from a contract which performs important safety checks
                            function mint(address to) external lock returns (uint liquidity) {
                                (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
                                uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
                                uint amount0 = balance0.sub(_reserve0);
                                uint amount1 = balance1.sub(_reserve1);
                        
                                bool feeOn = _mintFee(_reserve0, _reserve1);
                                uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                if (_totalSupply == 0) {
                                    address migrator = IUniswapV2Factory(factory).migrator();
                                    if (msg.sender == migrator) {
                                        liquidity = IMigrator(migrator).desiredLiquidity();
                                        require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
                                    } else {
                                        require(migrator == address(0), "Must not have migrator");
                                        liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                                        _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                                    }
                                } else {
                                    liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                                }
                                require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                                _mint(to, liquidity);
                        
                                _update(balance0, balance1, _reserve0, _reserve1);
                                if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                emit Mint(msg.sender, amount0, amount1);
                            }
                        
                            // this low-level function should be called from a contract which performs important safety checks
                            function burn(address to) external lock returns (uint amount0, uint amount1) {
                                (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                address _token0 = token0;                                // gas savings
                                address _token1 = token1;                                // gas savings
                                uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                                uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                                uint liquidity = balanceOf[address(this)];
                        
                                bool feeOn = _mintFee(_reserve0, _reserve1);
                                uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                                amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                                amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                                require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                                _burn(address(this), liquidity);
                                _safeTransfer(_token0, to, amount0);
                                _safeTransfer(_token1, to, amount1);
                                balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                                balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                        
                                _update(balance0, balance1, _reserve0, _reserve1);
                                if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                                emit Burn(msg.sender, amount0, amount1, to);
                            }
                        
                            // this low-level function should be called from a contract which performs important safety checks
                            function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                                require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                                (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                                require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                        
                                uint balance0;
                                uint balance1;
                                { // scope for _token{0,1}, avoids stack too deep errors
                                address _token0 = token0;
                                address _token1 = token1;
                                require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                                if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                                balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                                }
                                uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                                uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                                require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                                { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                                uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                                require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                                }
                        
                                _update(balance0, balance1, _reserve0, _reserve1);
                                emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                            }
                        
                            // force balances to match reserves
                            function skim(address to) external lock {
                                address _token0 = token0; // gas savings
                                address _token1 = token1; // gas savings
                                _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
                                _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
                            }
                        
                            // force reserves to match balances
                            function sync() external lock {
                                _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
                            }
                        }

                        File 4 of 18: ConvexToken
                        // SPDX-License-Identifier: MIT
                        
                        
                        // File: contracts\Interfaces.sol
                        pragma solidity 0.6.12;
                        
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library MathUtil {
                            /**
                             * @dev Returns the smallest of two numbers.
                             */
                            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                return a < b ? a : b;
                            }
                        }
                        
                        contract ReentrancyGuard {
                            uint256 private _guardCounter;
                        
                            constructor () internal {
                                _guardCounter = 1;
                            }
                        
                            modifier nonReentrant() {
                                _guardCounter += 1;
                                uint256 localCounter = _guardCounter;
                                _;
                                require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
                            }
                        }
                        
                        interface ICurveGauge {
                            function deposit(uint256) external;
                            function balanceOf(address) external view returns (uint256);
                            function withdraw(uint256) external;
                            function claim_rewards() external;
                            function reward_tokens(uint256) external view returns(address);//v2
                            function rewarded_token() external view returns(address);//v1
                        }
                        
                        interface ICurveVoteEscrow {
                            function create_lock(uint256, uint256) external;
                            function increase_amount(uint256) external;
                            function increase_unlock_time(uint256) external;
                            function withdraw() external;
                            function smart_wallet_checker() external view returns (address);
                        }
                        
                        interface IWalletChecker {
                            function check(address) external view returns (bool);
                        }
                        
                        interface IVoting{
                            function vote(uint256, bool, bool) external; //voteId, support, executeIfDecided
                            function getVote(uint256) external view returns(bool,bool,uint64,uint64,uint64,uint64,uint256,uint256,uint256,bytes memory); 
                            function vote_for_gauge_weights(address,uint256) external;
                        }
                        
                        interface IMinter{
                            function mint(address) external;
                        }
                        
                        interface IRegistry{
                            function get_registry() external view returns(address);
                            function get_address(uint256 _id) external view returns(address);
                            function gauge_controller() external view returns(address);
                            function get_lp_token(address) external view returns(address);
                            function get_gauges(address) external view returns(address[10] memory,uint128[10] memory);
                        }
                        
                        interface IStaker{
                            function deposit(address, address) external;
                            function withdraw(address) external;
                            function withdraw(address, address, uint256) external;
                            function withdrawAll(address, address) external;
                            function createLock(uint256, uint256) external;
                            function increaseAmount(uint256) external;
                            function increaseTime(uint256) external;
                            function release() external;
                            function claimCrv(address) external returns (uint256);
                            function claimRewards(address) external;
                            function claimFees(address,address) external;
                            function setStashAccess(address, bool) external;
                            function vote(uint256,address,bool) external;
                            function voteGaugeWeight(address,uint256) external;
                            function balanceOfPool(address) external view returns (uint256);
                            function operator() external view returns (address);
                            function execute(address _to, uint256 _value, bytes calldata _data) external returns (bool, bytes memory);
                        }
                        
                        interface IRewards{
                            function stake(address, uint256) external;
                            function stakeFor(address, uint256) external;
                            function withdraw(address, uint256) external;
                            function exit(address) external;
                            function getReward(address) external;
                            function queueNewRewards(uint256) external;
                            function notifyRewardAmount(uint256) external;
                            function addExtraReward(address) external;
                            function stakingToken() external returns (address);
                        }
                        
                        interface IStash{
                            function stashRewards() external returns (bool);
                            function processStash() external returns (bool);
                            function claimRewards() external returns (bool);
                        }
                        
                        interface IFeeDistro{
                            function claim() external;
                            function token() external view returns(address);
                        }
                        
                        interface ITokenMinter{
                            function mint(address,uint256) external;
                            function burn(address,uint256) external;
                        }
                        
                        interface IDeposit{
                            function isShutdown() external view returns(bool);
                            function balanceOf(address _account) external view returns(uint256);
                            function totalSupply() external view returns(uint256);
                            function poolInfo(uint256) external view returns(address,address,address,address,address, bool);
                            function rewardClaimed(uint256,address,uint256) external;
                            function withdrawTo(uint256,uint256,address) external;
                            function claimRewards(uint256,address) external returns(bool);
                            function rewardArbitrator() external returns(address);
                        }
                        
                        interface ICrvDeposit{
                            function deposit(uint256, bool) external;
                            function lockIncentive() external view returns(uint256);
                        }
                        
                        interface IRewardFactory{
                            function setAccess(address,bool) external;
                            function CreateCrvRewards(uint256,address) external returns(address);
                            function CreateTokenRewards(address,address,address) external returns(address);
                            function activeRewardCount(address) external view returns(uint256);
                            function addActiveReward(address,uint256) external returns(bool);
                            function removeActiveReward(address,uint256) external returns(bool);
                        }
                        
                        interface IStashFactory{
                            function CreateStash(uint256,address,address,uint256) external returns(address);
                        }
                        
                        interface ITokenFactory{
                            function CreateDepositToken(address) external returns(address);
                        }
                        
                        interface IPools{
                            function addPool(address _lptoken, address _gauge, uint256 _stashVersion) external returns(bool);
                            function shutdownPool(uint256 _pid) external returns(bool);
                            function poolInfo(uint256) external view returns(address,address,address,address,address,bool);
                            function poolLength() external view returns (uint256);
                            function gaugeMap(address) external view returns(bool);
                            function setPoolManager(address _poolM) external;
                        }
                        
                        interface IVestedEscrow{
                            function fund(address[] calldata _recipient, uint256[] calldata _amount) external returns(bool);
                        }
                        
                        // File: @openzeppelin\contracts\math\SafeMath.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                uint256 c = a + b;
                                if (c < a) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b > a) return (false, 0);
                                return (true, a - b);
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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-contracts/pull/522
                                if (a == 0) return (true, 0);
                                uint256 c = a * b;
                                if (c / a != b) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the division of two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a / b);
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a % b);
                            }
                        
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b <= a, "SafeMath: subtraction overflow");
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot overflow.
                             */
                            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                if (a == 0) return 0;
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: division by zero");
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: modulo by zero");
                                return a % b;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {trySub}.
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryDiv}.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting with custom message when dividing by zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryMod}.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a % b;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\IERC20.sol
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                        
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                        
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                        
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                        
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        
                        // File: @openzeppelin\contracts\utils\Address.sol
                        
                        pragma solidity >=0.6.2 <0.8.0;
                        
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                        
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                        
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                        
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                        
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                require(isContract(target), "Address: delegate call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                        
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                        
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                        
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                        
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                        
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                        
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        
                        // File: node_modules\@openzeppelin\contracts\utils\Context.sol
                        
                        pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                return msg.sender;
                            }
                        
                            function _msgData() internal view virtual returns (bytes memory) {
                                this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                return msg.data;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\ERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        /**
                         * @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
                         * to implement supply mechanisms].
                         *
                         * We have followed general OpenZeppelin guidelines: functions revert instead
                         * of 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 {
                            using SafeMath for uint256;
                        
                            mapping (address => uint256) private _balances;
                        
                            mapping (address => mapping (address => uint256)) private _allowances;
                        
                            uint256 private _totalSupply;
                        
                            string private _name;
                            string private _symbol;
                            uint8 private _decimals;
                        
                            /**
                             * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
                             * a default value of 18.
                             *
                             * To select a different value for {decimals}, use {_setupDecimals}.
                             *
                             * All three of these values are immutable: they can only be set once during
                             * construction.
                             */
                            constructor (string memory name_, string memory symbol_) public {
                                _name = name_;
                                _symbol = symbol_;
                                _decimals = 18;
                            }
                        
                            /**
                             * @dev Returns the name of the token.
                             */
                            function name() public view virtual returns (string memory) {
                                return _name;
                            }
                        
                            /**
                             * @dev Returns the symbol of the token, usually a shorter version of the
                             * name.
                             */
                            function symbol() public view virtual 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 value {ERC20} uses, unless {_setupDecimals} is
                             * called.
                             *
                             * 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 returns (uint8) {
                                return _decimals;
                            }
                        
                            /**
                             * @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:
                             *
                             * - `recipient` cannot be the zero address.
                             * - the caller must have a balance of at least `amount`.
                             */
                            function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                                _transfer(_msgSender(), recipient, 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}.
                             *
                             * Requirements:
                             *
                             * - `spender` cannot be the zero address.
                             */
                            function approve(address spender, uint256 amount) public virtual override returns (bool) {
                                _approve(_msgSender(), 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}.
                             *
                             * Requirements:
                             *
                             * - `sender` and `recipient` cannot be the zero address.
                             * - `sender` must have a balance of at least `amount`.
                             * - the caller must have allowance for ``sender``'s tokens of at least
                             * `amount`.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
                                _transfer(sender, recipient, amount);
                                _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
                                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) {
                                _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
                                _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                return true;
                            }
                        
                            /**
                             * @dev Moves tokens `amount` from `sender` to `recipient`.
                             *
                             * This is 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:
                             *
                             * - `sender` cannot be the zero address.
                             * - `recipient` cannot be the zero address.
                             * - `sender` must have a balance of at least `amount`.
                             */
                            function _transfer(address sender, address recipient, uint256 amount) internal virtual {
                                require(sender != address(0), "ERC20: transfer from the zero address");
                                require(recipient != address(0), "ERC20: transfer to the zero address");
                        
                                _beforeTokenTransfer(sender, recipient, amount);
                        
                                _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                                _balances[recipient] = _balances[recipient].add(amount);
                                emit Transfer(sender, recipient, 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:
                             *
                             * - `to` 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 = _totalSupply.add(amount);
                                _balances[account] = _balances[account].add(amount);
                                emit Transfer(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);
                        
                                _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                                _totalSupply = _totalSupply.sub(amount);
                                emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
                             *
                             * WARNING: This function should only be called from the constructor. Most
                             * applications that interact with token contracts will not expect
                             * {decimals} to ever change, and may work incorrectly if it does.
                             */
                            function _setupDecimals(uint8 decimals_) internal virtual {
                                _decimals = decimals_;
                            }
                        
                            /**
                             * @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 to 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 { }
                        }
                        
                        // File: contracts\Cvx.sol
                        
                        pragma solidity 0.6.12;
                        
                        
                        contract ConvexToken is ERC20{
                            using SafeERC20 for IERC20;
                            using Address for address;
                            using SafeMath for uint256;
                        
                            address public operator;
                            address public vecrvProxy;
                        
                            uint256 public maxSupply = 100 * 1000000 * 1e18; //100mil
                            uint256 public totalCliffs = 1000;
                            uint256 public reductionPerCliff;
                        
                            constructor(address _proxy)
                                public
                                ERC20(
                                    "Convex Token",
                                    "CVX"
                                )
                            {
                                operator = msg.sender;
                                vecrvProxy = _proxy;
                                reductionPerCliff = maxSupply.div(totalCliffs);
                            }
                        
                            //get current operator off proxy incase there was a change
                            function updateOperator() public {
                                operator = IStaker(vecrvProxy).operator();
                            }
                            
                            function mint(address _to, uint256 _amount) external {
                                if(msg.sender != operator){
                                    //dont error just return. if a shutdown happens, rewards on old system
                                    //can still be claimed, just wont mint cvx
                                    return;
                                }
                        
                                uint256 supply = totalSupply();
                                if(supply == 0){
                                    //premine, one time only
                                    _mint(_to,_amount);
                                    //automatically switch operators
                                    updateOperator();
                                    return;
                                }
                                
                                //use current supply to gauge cliff
                                //this will cause a bit of overflow into the next cliff range
                                //but should be within reasonable levels.
                                //requires a max supply check though
                                uint256 cliff = supply.div(reductionPerCliff);
                                //mint if below total cliffs
                                if(cliff < totalCliffs){
                                    //for reduction% take inverse of current cliff
                                    uint256 reduction = totalCliffs.sub(cliff);
                                    //reduce
                                    _amount = _amount.mul(reduction).div(totalCliffs);
                        
                                    //supply cap check
                                    uint256 amtTillMax = maxSupply.sub(supply);
                                    if(_amount > amtTillMax){
                                        _amount = amtTillMax;
                                    }
                        
                                    //mint
                                    _mint(_to, _amount);
                                }
                            }
                        
                        }

                        File 5 of 18: WarMinter
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {WarToken} from "./Token.sol";
                        import {IWarLocker} from "interfaces/IWarLocker.sol";
                        import {IRatios} from "interfaces/IRatios.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {ReentrancyGuard} from "openzeppelin/security/ReentrancyGuard.sol";
                        /**
                         * @title Warlord Minter contract
                         * @author Paladin
                         * @notice Receives vlToken to deposit in Lockers and mints WAR
                         */
                        contract WarMinter is Owner, ReentrancyGuard {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice WAR token contract
                           */
                          WarToken public immutable war;
                          /**
                           * @notice Address of the contract calculating the mint amounts
                           */
                          IRatios public ratios;
                          /**
                           * @notice Address of the Locker set for each token
                           */
                          mapping(address => address) public lockers;
                          /**
                           * @notice Event emitted when the Ratio contract is updated
                           */
                          event MintRatioUpdated(address oldMintRatio, address newMintRatio);
                          // Constructor
                          constructor(address _war, address _ratios) {
                            if (_war == address(0) || _ratios == address(0)) revert Errors.ZeroAddress();
                            war = WarToken(_war);
                            ratios = IRatios(_ratios);
                          }
                          /**
                           * @notice Sets a new Locker for a given token
                           * @param vlToken Address of the token
                           * @param warLocker Address of the Locker
                           */
                          function setLocker(address vlToken, address warLocker) external onlyOwner {
                            if (vlToken == address(0) || warLocker == address(0)) revert Errors.ZeroAddress();
                            address expectedToken = IWarLocker(warLocker).token();
                            if (expectedToken != vlToken) revert Errors.MismatchingLocker(expectedToken, vlToken);
                            lockers[vlToken] = warLocker;
                          }
                          /**
                           * @notice Mints WAR token based of the amount of token deposited
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           */
                          function mint(address vlToken, uint256 amount) external nonReentrant {
                            _mint(vlToken, amount, msg.sender);
                          }
                          /**
                           * @notice Mints WAR token based of the amount of token deposited, mints for the given receiver
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function mint(address vlToken, uint256 amount, address receiver) external nonReentrant {
                            _mint(vlToken, amount, receiver);
                          }
                          /**
                           * @dev Pulls tokens to deposit in the associated Locker & mints WAR based on the deposited amount
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function _mint(address vlToken, uint256 amount, address receiver) internal {
                            if (amount == 0) revert Errors.ZeroValue();
                            if (vlToken == address(0) || receiver == address(0)) revert Errors.ZeroAddress();
                            if (lockers[vlToken] == address(0)) revert Errors.NoWarLocker();
                            // Load the correct Locker contract
                            IWarLocker locker = IWarLocker(lockers[vlToken]);
                            // Pull the tokens, and deposit them in the Locker
                            IERC20(vlToken).safeTransferFrom(msg.sender, address(this), amount);
                            if (IERC20(vlToken).allowance(address(this), address(locker)) != 0) IERC20(vlToken).safeApprove(address(locker), 0);
                            IERC20(vlToken).safeIncreaseAllowance(address(locker), amount);
                            locker.lock(amount);
                            // Get the amount of WAR to mint for the deposited amount
                            uint256 mintAmount = ratios.getMintAmount(vlToken, amount);
                            if (mintAmount == 0) revert Errors.ZeroMintAmount();
                            // Mint the WAR to the receiver
                            war.mint(receiver, mintAmount);
                          }
                          /**
                           * @dev Pulls multiple tokens to deposit in the associated Locker & mints WAR based on the deposited amounts
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function _mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts, address receiver) internal {
                            if (vlTokens.length != amounts.length) revert Errors.DifferentSizeArrays(vlTokens.length, amounts.length);
                            if (vlTokens.length == 0) revert Errors.EmptyArray();
                            uint256 length = vlTokens.length;
                            for (uint256 i; i < length;) {
                              _mint(vlTokens[i], amounts[i], receiver);
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          /**
                           * @notice Mints WAR token based of the amounts of tokens deposited
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts, address receiver)
                            external
                            nonReentrant
                          {
                            _mintMultiple(vlTokens, amounts, receiver);
                          }
                          /**
                           * @notice Mints WAR token based of the amounts of tokens deposited
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           */
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts) external nonReentrant {
                            _mintMultiple(vlTokens, amounts, msg.sender);
                          }
                          /**
                           * @notice Sets the Ratio contract address
                           * @param newRatios Address of the new Ratio contract
                           */
                          function setRatios(address newRatios) external onlyOwner {
                            if (newRatios == address(0)) revert Errors.ZeroAddress();
                            address oldRatios = address(ratios);
                            ratios = IRatios(newRatios);
                            emit MintRatioUpdated(oldRatios, newRatios);
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.6.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.8.0) (token/ERC20/utils/SafeERC20.sol)
                        pragma solidity ^0.8.0;
                        import "../IERC20.sol";
                        import "../extensions/draft-IERC20Permit.sol";
                        import "../../../utils/Address.sol";
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using Address for address;
                            function safeTransfer(
                                IERC20 token,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(
                                IERC20 token,
                                address from,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                require(
                                    (value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                uint256 newAllowance = token.allowance(address(this), spender) + value;
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                unchecked {
                                    uint256 oldAllowance = token.allowance(address(this), spender);
                                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                    uint256 newAllowance = oldAllowance - value;
                                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                }
                            }
                            function safePermit(
                                IERC20Permit token,
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                uint256 nonceBefore = token.nonces(owner);
                                token.permit(owner, spender, value, deadline, v, r, s);
                                uint256 nonceAfter = token.nonces(owner);
                                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) {
                                    // Return data is optional
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {ERC20} from "solmate/tokens/ERC20.sol";
                        import {AccessControl} from "openzeppelin/access/AccessControl.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Warlord Token contract
                         * @author Paladin
                         * @notice ERC20 token minted by deposit in Warlord
                         */
                        contract WarToken is ERC20, AccessControl {
                          /**
                           * @notice Event emitted when a new pending owner is set
                           */
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          /**
                           * @notice Address of the current pending owner
                           */
                          address public pendingOwner;
                          /**
                           * @notice Address of the current owner
                           */
                          address public owner;
                          /**
                           * @notice Minter role
                           */
                          bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
                          /**
                           * @notice Burner role
                           */
                          bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
                          // Constructor
                          constructor() ERC20("Warlord token", "WAR", 18) {
                            owner = msg.sender;
                            _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
                            _setRoleAdmin(DEFAULT_ADMIN_ROLE, keccak256("NO_ROLE"));
                          }
                          /**
                           * @notice Set the given address as the new pending owner
                           * @param newOwner Address to set as pending owner
                           */
                          function transferOwnership(address newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
                            if (newOwner == address(0)) revert Errors.ZeroAddress();
                            if (newOwner == owner) revert Errors.CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          /**
                           * @notice Accept the ownership transfer (only callable by the current pending owner)
                           */
                          function acceptOwnership() external {
                            if (msg.sender != pendingOwner) revert Errors.CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            // Revoke the previous owner ADMIN role and set it for the new owner
                            _revokeRole(DEFAULT_ADMIN_ROLE, owner);
                            _grantRole(DEFAULT_ADMIN_ROLE, newOwner);
                            owner = newOwner;
                            // Reset the pending owner
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                          /**
                           * @notice Mints the given amount of tokens to the given address
                           * @param to Address to mint token to
                           * @param amount Amount of token to mint
                           */
                          function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
                            _mint(to, amount);
                          }
                          /**
                           * @notice Burns the given amount of tokens from the given address
                           * @param from Address to burn token from
                           * @param amount Amount of token to burn
                           */
                          function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
                            _burn(from, amount);
                          }
                          /**
                           * @dev Atomically increases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param addedValue Amount of token to increase the allowance
                           */
                          function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
                            uint256 newAllowance = allowance[msg.sender][spender] + addedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                          /**
                           * @dev Atomically decreases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param subtractedValue Amount of token to increase the allowance
                           */
                          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
                            uint256 currentAllowance = allowance[msg.sender][spender];
                            if (subtractedValue > currentAllowance) revert Errors.AllowanceUnderflow();
                            uint256 newAllowance = currentAllowance - subtractedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        import {IHarvestable} from "./IHarvestable.sol";
                        interface IWarLocker is IHarvestable {
                          function lock(uint256 amount) external;
                          function token() external view returns (address);
                          function getCurrentLockedTokens() external view returns (uint256);
                          function processUnlock() external;
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IRatios {
                          function getTokenRatio(address token) external view returns (uint256);
                          function addToken(address token, uint256 maxSupply) external;
                          function getMintAmount(address token, uint256 amount) external view returns (uint256 mintAmount);
                          function getBurnAmount(address token, uint256 amount) external view returns (uint256 burnAmount);
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.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;
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @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 IERC20Permit {
                            /**
                             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                             * given ``owner``'s signed approval.
                             *
                             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                             * ordering also apply here.
                             *
                             * 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}).
                             *
                             * For more information on the signature format, see the
                             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                             * section].
                             */
                            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);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
                        pragma solidity ^0.8.1;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             *
                             * [IMPORTANT]
                             * ====
                             * You shouldn't rely on `isContract` to protect against flash loan attacks!
                             *
                             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                             * constructor.
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize/address.code.length, which returns 0
                                // for contracts in construction, since the code is only stored at the end
                                // of the constructor execution.
                                return account.code.length > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                (bool success, ) = recipient.call{value: amount}("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain `call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                (bool success, bytes memory returndata) = target.call{value: value}(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                             *
                             * _Available since v4.8._
                             */
                            function verifyCallResultFromTarget(
                                address target,
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                if (success) {
                                    if (returndata.length == 0) {
                                        // only check isContract if the call was successful and the return data is empty
                                        // otherwise we already know that it was a contract
                                        require(isContract(target), "Address: call to non-contract");
                                    }
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            /**
                             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                             * revert reason or using the provided one.
                             *
                             * _Available since v4.3._
                             */
                            function verifyCallResult(
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal pure returns (bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                        /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                        abstract contract ERC20 {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                    METADATA STORAGE
                            //////////////////////////////////////////////////////////////*/
                            string public name;
                            string public symbol;
                            uint8 public immutable decimals;
                            /*//////////////////////////////////////////////////////////////
                                                      ERC20 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 public totalSupply;
                            mapping(address => uint256) public balanceOf;
                            mapping(address => mapping(address => uint256)) public allowance;
                            /*//////////////////////////////////////////////////////////////
                                                    EIP-2612 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 internal immutable INITIAL_CHAIN_ID;
                            bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                            mapping(address => uint256) public nonces;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                string memory _name,
                                string memory _symbol,
                                uint8 _decimals
                            ) {
                                name = _name;
                                symbol = _symbol;
                                decimals = _decimals;
                                INITIAL_CHAIN_ID = block.chainid;
                                INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                allowance[msg.sender][spender] = amount;
                                emit Approval(msg.sender, spender, amount);
                                return true;
                            }
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                balanceOf[msg.sender] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(msg.sender, to, amount);
                                return true;
                            }
                            function transferFrom(
                                address from,
                                address to,
                                uint256 amount
                            ) public virtual returns (bool) {
                                uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                balanceOf[from] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(from, to, amount);
                                return true;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     EIP-2612 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                // Unchecked because the only math done is incrementing
                                // the owner's nonce which cannot realistically overflow.
                                unchecked {
                                    address recoveredAddress = ecrecover(
                                        keccak256(
                                            abi.encodePacked(
                                                "\\x19\\x01",
                                                DOMAIN_SEPARATOR(),
                                                keccak256(
                                                    abi.encode(
                                                        keccak256(
                                                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                        ),
                                                        owner,
                                                        spender,
                                                        value,
                                                        nonces[owner]++,
                                                        deadline
                                                    )
                                                )
                                            )
                                        ),
                                        v,
                                        r,
                                        s
                                    );
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                    allowance[recoveredAddress][spender] = value;
                                }
                                emit Approval(owner, spender, value);
                            }
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                            }
                            function computeDomainSeparator() internal view virtual returns (bytes32) {
                                return
                                    keccak256(
                                        abi.encode(
                                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                            keccak256(bytes(name)),
                                            keccak256("1"),
                                            block.chainid,
                                            address(this)
                                        )
                                    );
                            }
                            /*//////////////////////////////////////////////////////////////
                                                INTERNAL MINT/BURN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function _mint(address to, uint256 amount) internal virtual {
                                totalSupply += amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(address(0), to, amount);
                            }
                            function _burn(address from, uint256 amount) internal virtual {
                                balanceOf[from] -= amount;
                                // Cannot underflow because a user's balance
                                // will never be larger than the total supply.
                                unchecked {
                                    totalSupply -= amount;
                                }
                                emit Transfer(from, address(0), amount);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
                        pragma solidity ^0.8.0;
                        import "./IAccessControl.sol";
                        import "../utils/Context.sol";
                        import "../utils/Strings.sol";
                        import "../utils/introspection/ERC165.sol";
                        /**
                         * @dev Contract module that allows children to implement role-based access
                         * control mechanisms. This is a lightweight version that doesn't allow enumerating role
                         * members except through off-chain means by accessing the contract event logs. Some
                         * applications may benefit from on-chain enumerability, for those cases see
                         * {AccessControlEnumerable}.
                         *
                         * Roles are referred to by their `bytes32` identifier. These should be exposed
                         * in the external API and be unique. The best way to achieve this is by
                         * using `public constant` hash digests:
                         *
                         * ```
                         * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                         * ```
                         *
                         * Roles can be used to represent a set of permissions. To restrict access to a
                         * function call, use {hasRole}:
                         *
                         * ```
                         * function foo() public {
                         *     require(hasRole(MY_ROLE, msg.sender));
                         *     ...
                         * }
                         * ```
                         *
                         * Roles can be granted and revoked dynamically via the {grantRole} and
                         * {revokeRole} functions. Each role has an associated admin role, and only
                         * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                         *
                         * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                         * that only accounts with this role will be able to grant or revoke other
                         * roles. More complex role relationships can be created by using
                         * {_setRoleAdmin}.
                         *
                         * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                         * grant and revoke this role. Extra precautions should be taken to secure
                         * accounts that have been granted it.
                         */
                        abstract contract AccessControl is Context, IAccessControl, ERC165 {
                            struct RoleData {
                                mapping(address => bool) members;
                                bytes32 adminRole;
                            }
                            mapping(bytes32 => RoleData) private _roles;
                            bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                            /**
                             * @dev Modifier that checks that an account has a specific role. Reverts
                             * with a standardized message including the required role.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             *
                             * _Available since v4.1._
                             */
                            modifier onlyRole(bytes32 role) {
                                _checkRole(role);
                                _;
                            }
                            /**
                             * @dev See {IERC165-supportsInterface}.
                             */
                            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                                return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
                            }
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                                return _roles[role].members[account];
                            }
                            /**
                             * @dev Revert with a standard message if `_msgSender()` is missing `role`.
                             * Overriding this function changes the behavior of the {onlyRole} modifier.
                             *
                             * Format of the revert message is described in {_checkRole}.
                             *
                             * _Available since v4.6._
                             */
                            function _checkRole(bytes32 role) internal view virtual {
                                _checkRole(role, _msgSender());
                            }
                            /**
                             * @dev Revert with a standard message if `account` is missing `role`.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             */
                            function _checkRole(bytes32 role, address account) internal view virtual {
                                if (!hasRole(role, account)) {
                                    revert(
                                        string(
                                            abi.encodePacked(
                                                "AccessControl: account ",
                                                Strings.toHexString(account),
                                                " is missing role ",
                                                Strings.toHexString(uint256(role), 32)
                                            )
                                        )
                                    );
                                }
                            }
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                                return _roles[role].adminRole;
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been revoked `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function renounceRole(bytes32 role, address account) public virtual override {
                                require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event. Note that unlike {grantRole}, this function doesn't perform any
                             * checks on the calling account.
                             *
                             * May emit a {RoleGranted} event.
                             *
                             * [WARNING]
                             * ====
                             * This function should only be called from the constructor when setting
                             * up the initial roles for the system.
                             *
                             * Using this function in any other way is effectively circumventing the admin
                             * system imposed by {AccessControl}.
                             * ====
                             *
                             * NOTE: This function is deprecated in favor of {_grantRole}.
                             */
                            function _setupRole(bytes32 role, address account) internal virtual {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Sets `adminRole` as ``role``'s admin role.
                             *
                             * Emits a {RoleAdminChanged} event.
                             */
                            function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                bytes32 previousAdminRole = getRoleAdmin(role);
                                _roles[role].adminRole = adminRole;
                                emit RoleAdminChanged(role, previousAdminRole, adminRole);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function _grantRole(bytes32 role, address account) internal virtual {
                                if (!hasRole(role, account)) {
                                    _roles[role].members[account] = true;
                                    emit RoleGranted(role, account, _msgSender());
                                }
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function _revokeRole(bytes32 role, address account) internal virtual {
                                if (hasRole(role, account)) {
                                    _roles[role].members[account] = false;
                                    emit RoleRevoked(role, account, _msgSender());
                                }
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IHarvestable {
                          function harvest() external;
                          function rewardTokens() external view returns (address[] memory);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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
                        // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev External interface of AccessControl declared to support ERC165 detection.
                         */
                        interface IAccessControl {
                            /**
                             * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                             *
                             * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                             * {RoleAdminChanged} not being emitted signaling this.
                             *
                             * _Available since v3.1._
                             */
                            event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                            /**
                             * @dev Emitted when `account` is granted `role`.
                             *
                             * `sender` is the account that originated the contract call, an admin role
                             * bearer except when using {AccessControl-_setupRole}.
                             */
                            event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Emitted when `account` is revoked `role`.
                             *
                             * `sender` is the account that originated the contract call:
                             *   - if using `revokeRole`, it is the admin role bearer
                             *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                             */
                            event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) external view returns (bool);
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {AccessControl-_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) external view returns (bytes32);
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function grantRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function revokeRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been granted `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             */
                            function renounceRole(bytes32 role, address account) external;
                        }
                        // 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 (last updated v4.8.0) (utils/Strings.sol)
                        pragma solidity ^0.8.0;
                        import "./math/Math.sol";
                        /**
                         * @dev String operations.
                         */
                        library Strings {
                            bytes16 private constant _SYMBOLS = "0123456789abcdef";
                            uint8 private constant _ADDRESS_LENGTH = 20;
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                             */
                            function toString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    uint256 length = Math.log10(value) + 1;
                                    string memory buffer = new string(length);
                                    uint256 ptr;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        ptr := add(buffer, add(32, length))
                                    }
                                    while (true) {
                                        ptr--;
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                                        }
                                        value /= 10;
                                        if (value == 0) break;
                                    }
                                    return buffer;
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                             */
                            function toHexString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    return toHexString(value, Math.log256(value) + 1);
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                             */
                            function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                                bytes memory buffer = new bytes(2 * length + 2);
                                buffer[0] = "0";
                                buffer[1] = "x";
                                for (uint256 i = 2 * length + 1; i > 1; --i) {
                                    buffer[i] = _SYMBOLS[value & 0xf];
                                    value >>= 4;
                                }
                                require(value == 0, "Strings: hex length insufficient");
                                return string(buffer);
                            }
                            /**
                             * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                             */
                            function toHexString(address addr) internal pure returns (string memory) {
                                return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                            }
                        }
                        // 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 (last updated v4.8.0) (utils/math/Math.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library Math {
                            enum Rounding {
                                Down, // Toward negative infinity
                                Up, // Toward infinity
                                Zero // Toward zero
                            }
                            /**
                             * @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 average of two numbers. The result is rounded towards
                             * zero.
                             */
                            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                // (a + b) / 2 can overflow.
                                return (a & b) + (a ^ b) / 2;
                            }
                            /**
                             * @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;
                            }
                            /**
                             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                             * with further edits by Uniswap Labs also under MIT license.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator
                            ) internal pure returns (uint256 result) {
                                unchecked {
                                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                    // variables such that product = prod1 * 2^256 + prod0.
                                    uint256 prod0; // Least significant 256 bits of the product
                                    uint256 prod1; // Most significant 256 bits of the product
                                    assembly {
                                        let mm := mulmod(x, y, not(0))
                                        prod0 := mul(x, y)
                                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                    }
                                    // Handle non-overflow cases, 256 by 256 division.
                                    if (prod1 == 0) {
                                        return prod0 / denominator;
                                    }
                                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                    require(denominator > prod1);
                                    ///////////////////////////////////////////////
                                    // 512 by 256 division.
                                    ///////////////////////////////////////////////
                                    // Make division exact by subtracting the remainder from [prod1 prod0].
                                    uint256 remainder;
                                    assembly {
                                        // Compute remainder using mulmod.
                                        remainder := mulmod(x, y, denominator)
                                        // Subtract 256 bit number from 512 bit number.
                                        prod1 := sub(prod1, gt(remainder, prod0))
                                        prod0 := sub(prod0, remainder)
                                    }
                                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                    // See https://cs.stackexchange.com/q/138556/92363.
                                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                                    uint256 twos = denominator & (~denominator + 1);
                                    assembly {
                                        // Divide denominator by twos.
                                        denominator := div(denominator, twos)
                                        // Divide [prod1 prod0] by twos.
                                        prod0 := div(prod0, twos)
                                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                        twos := add(div(sub(0, twos), twos), 1)
                                    }
                                    // Shift in bits from prod1 into prod0.
                                    prod0 |= prod1 * twos;
                                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                    // four bits. That is, denominator * inv = 1 mod 2^4.
                                    uint256 inverse = (3 * denominator) ^ 2;
                                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                    // in modular arithmetic, doubling the correct bits in each step.
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                    // is no longer required.
                                    result = prod0 * inverse;
                                    return result;
                                }
                            }
                            /**
                             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator,
                                Rounding rounding
                            ) internal pure returns (uint256) {
                                uint256 result = mulDiv(x, y, denominator);
                                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                    result += 1;
                                }
                                return result;
                            }
                            /**
                             * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                             *
                             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                             */
                            function sqrt(uint256 a) internal pure returns (uint256) {
                                if (a == 0) {
                                    return 0;
                                }
                                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                //
                                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                //
                                // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                //
                                // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                uint256 result = 1 << (log2(a) >> 1);
                                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                // into the expected uint128 result.
                                unchecked {
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    return min(result, a / result);
                                }
                            }
                            /**
                             * @notice Calculates sqrt(a), following the selected rounding direction.
                             */
                            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = sqrt(a);
                                    return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 2, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 128;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 64;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 32;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 16;
                                    }
                                    if (value >> 8 > 0) {
                                        value >>= 8;
                                        result += 8;
                                    }
                                    if (value >> 4 > 0) {
                                        value >>= 4;
                                        result += 4;
                                    }
                                    if (value >> 2 > 0) {
                                        value >>= 2;
                                        result += 2;
                                    }
                                    if (value >> 1 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log2(value);
                                    return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 10, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >= 10**64) {
                                        value /= 10**64;
                                        result += 64;
                                    }
                                    if (value >= 10**32) {
                                        value /= 10**32;
                                        result += 32;
                                    }
                                    if (value >= 10**16) {
                                        value /= 10**16;
                                        result += 16;
                                    }
                                    if (value >= 10**8) {
                                        value /= 10**8;
                                        result += 8;
                                    }
                                    if (value >= 10**4) {
                                        value /= 10**4;
                                        result += 4;
                                    }
                                    if (value >= 10**2) {
                                        value /= 10**2;
                                        result += 2;
                                    }
                                    if (value >= 10**1) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log10(value);
                                    return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 256, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             *
                             * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                             */
                            function log256(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 16;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 8;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 4;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 2;
                                    }
                                    if (value >> 8 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log256(value);
                                    return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                                }
                            }
                        }
                        // 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);
                        }
                        

                        File 6 of 18: WarCvxLocker
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import "./IncentivizedLocker.sol";
                        import {IDelegateRegistry} from "interfaces/external/IDelegateRegistry.sol";
                        import {CvxLockerV2} from "interfaces/external/convex/vlCvx.sol";
                        import {Math} from "openzeppelin/utils/math/Math.sol";
                        /**
                         * @title Warlord CVX Locker contract
                         * @author Paladin
                         * @notice Contract locking CVX into vlCVX, claiming rewards and delegating voting power
                         */
                        contract WarCvxLocker is IncentivizedLocker {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice Address of the vlCVX contract
                           */
                          CvxLockerV2 private constant vlCvx = CvxLockerV2(0x72a19342e8F1838460eBFCCEf09F6585e32db86E);
                          /**
                           * @notice Address of the CVX token
                           */
                          IERC20 private constant cvx = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
                          /**
                           * @notice Address of the DelegateRegistry contract
                           */
                          IDelegateRegistry private constant registry = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
                          // Constructor
                          constructor(address _controller, address _redeemModule, address _warMinter, address _delegatee)
                            WarBaseLocker(_controller, _redeemModule, _warMinter, _delegatee)
                          {
                            registry.setDelegate("cvx.eth", _delegatee);
                          }
                          /**
                           * @notice Returns the address of the token being locked
                           * @return address : token
                           */
                          function token() external pure returns (address) {
                            return address(cvx);
                          }
                          /**
                           * @notice Returns the current total amount of locked tokens for this Locker
                           */
                          function getCurrentLockedTokens() external view override returns (uint256) {
                            (uint256 totalBalance,,,) = vlCvx.lockedBalances(address(this));
                            return totalBalance;
                          }
                          /**
                           * @dev Locks the tokens in the vlToken contract
                           * @param amount Amount to lock
                           */
                          function _lock(uint256 amount) internal override {
                            cvx.safeTransferFrom(msg.sender, address(this), amount);
                            if (cvx.allowance(address(this), address(vlCvx)) != 0) cvx.safeApprove(address(vlCvx), 0);
                            cvx.safeIncreaseAllowance(address(vlCvx), amount);
                            vlCvx.lock(address(this), amount, 0);
                          }
                          /**
                           * @dev Harvest rewards & send them to the Controller
                           */
                          function _harvest() internal override {
                            CvxLockerV2.EarnedData[] memory rewards = vlCvx.claimableRewards(address(this));
                            uint256 rewardsLength = rewards.length;
                            vlCvx.getReward(address(this), false);
                            for (uint256 i; i < rewardsLength;) {
                              IERC20 rewardToken = IERC20(rewards[i].token);
                              uint256 rewardBalance = rewardToken.balanceOf(address(this));
                              rewardToken.safeTransfer(controller, rewardBalance);
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          /**
                           * @dev Updates the Delegatee & delegates the voting power
                           * @param _delegatee Address of the delegatee
                           */
                          function _setDelegate(address _delegatee) internal override {
                            registry.setDelegate("cvx.eth", _delegatee);
                          }
                          /**
                           * @dev Processes the unlock of tokens
                           */
                          function _processUnlock() internal override {
                            // Harvest the rewards before processing unlocks
                            _harvest();
                            // Get the amount being unlocked
                            (, uint256 unlockableBalance,,) = vlCvx.lockedBalances(address(this));
                            if (unlockableBalance == 0) return;
                            // Get the amount needed in the Redeem Module
                            uint256 withdrawalAmount = IWarRedeemModule(redeemModule).queuedForWithdrawal(address(cvx));
                            // If unlock == 0 relock everything
                            if (withdrawalAmount == 0) {
                              vlCvx.processExpiredLocks(true);
                            } else {
                              // otherwise withdraw everything and lock only what's left
                              vlCvx.processExpiredLocks(false);
                              withdrawalAmount = Math.min(unlockableBalance, withdrawalAmount);
                              cvx.safeTransfer(address(redeemModule), withdrawalAmount);
                              IWarRedeemModule(redeemModule).notifyUnlock(address(cvx), withdrawalAmount);
                              uint256 relock = unlockableBalance - withdrawalAmount;
                              if (relock > 0) {
                                if (cvx.allowance(address(this), address(vlCvx)) != 0) cvx.safeApprove(address(vlCvx), 0);
                                cvx.safeIncreaseAllowance(address(vlCvx), relock);
                                vlCvx.lock(address(this), relock, 0);
                              }
                            }
                          }
                          /**
                           * @dev Migrates the tokens hold by this contract to another address (& unlocks everything that can be unlocked)
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal override {
                            // withdraws unlockable balance to receiver
                            vlCvx.withdrawExpiredLocksTo(receiver);
                            // withdraws rewards to controller
                            _harvest();
                          }
                          /**
                           * @notice Recover ERC2O tokens in the contract
                           * @dev Recover ERC2O tokens in the contract
                           * @param _token Address of the ERC2O token
                           * @return bool: success
                           */
                          function recoverERC20(address _token) external onlyOwner returns (bool) {
                            if (_token == address(cvx)) revert Errors.RecoverForbidden();
                            if (_token == address(0)) revert Errors.ZeroAddress();
                            uint256 amount = IERC20(_token).balanceOf(address(this));
                            if (amount == 0) revert Errors.ZeroValue();
                            IERC20(_token).safeTransfer(owner(), amount);
                            return true;
                          }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import "./BaseLocker.sol";
                        import "interfaces/IIncentivizedLocker.sol";
                        import {
                          IQuestDistributor,
                          IDelegationDistributor,
                          IVotiumDistributor,
                          IHiddenHandDistributor
                        } from "interfaces/external/incentives/IIncentivesDistributors.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Incentivized Locker contract
                         * @author Paladin
                         * @notice Locker contract capable of claiming vote rewards from different sources
                         */
                        abstract contract IncentivizedLocker is WarBaseLocker, IIncentivizedLocker {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice Checks that the caller is the controller
                           */
                          modifier onlyController() {
                            if (msg.sender != controller) revert Errors.CallerNotAllowed();
                            _;
                          }
                          /**
                           * @notice Claims voting rewards from Quest
                           * @param distributor Address of the contract distributing the rewards
                           * @param questID ID of the Quest to claim rewards from
                           * @param period Timestamp of the Quest period to claim
                           * @param index Index in the Merkle Tree
                           * @param account Address claiming the rewards
                           * @param amount Amount to claim
                           * @param merkleProof Merkle Proofs for the claim
                           */
                          function claimQuestRewards(
                            address distributor,
                            uint256 questID,
                            uint256 period,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external nonReentrant onlyController {
                            IQuestDistributor _distributor = IQuestDistributor(distributor);
                            IERC20 _token = IERC20(_distributor.questRewardToken(questID));
                            _distributor.claim(questID, period, index, account, amount, merkleProof);
                            _token.safeTransfer(controller, amount);
                          }
                          /**
                           * @notice Claims voting rewards from the Paladin Delegation address
                           * @param distributor Address of the contract distributing the rewards
                           * @param token Address of the reward token to claim
                           * @param index Index in the Merkle Tree
                           * @param account Address claiming the rewards
                           * @param amount Amount to claim
                           * @param merkleProof Merkle Proofs for the claim
                           */
                          function claimDelegationRewards(
                            address distributor,
                            address token,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external nonReentrant onlyController {
                            IDelegationDistributor(distributor).claim(token, index, account, amount, merkleProof);
                            IERC20(token).safeTransfer(controller, amount);
                          }
                          /**
                           * @notice Claims voting rewards from Votium
                           * @param distributor Address of the contract distributing the rewards
                           * @param token Address of the reward token to claim
                           * @param index Index in the Merkle Tree
                           * @param account Address claiming the rewards
                           * @param amount Amount to claim
                           * @param merkleProof Merkle Proofs for the claim
                           */
                          function claimVotiumRewards(
                            address distributor,
                            address token,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external nonReentrant onlyController {
                            IVotiumDistributor(distributor).claim(token, index, account, amount, merkleProof);
                            IERC20(token).safeTransfer(controller, amount);
                          }
                          /**
                           * @notice Claims voting rewards from HiddenHand
                           * @param distributor Address of the contract distributing the rewards
                           * @param claimParams Parameters for claims
                           */
                          function claimHiddenHandRewards(address distributor, IHiddenHandDistributor.Claim[] calldata claimParams)
                            external
                            nonReentrant
                            onlyController
                          {
                            require(claimParams.length == 1);
                            IHiddenHandDistributor _distributor = IHiddenHandDistributor(distributor);
                            address token = _distributor.rewards(claimParams[0].identifier).token;
                            uint256 initialBalance = IERC20(token).balanceOf(address(this));
                            _distributor.claim(claimParams);
                            uint256 claimedAmount = IERC20(token).balanceOf(address(this)) - initialBalance;
                            IERC20(token).safeTransfer(controller, claimedAmount);
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IDelegateRegistry {
                          function delegation(address delegator, bytes32 id) external view returns (address);
                          function setDelegate(bytes32 id, address delegate) external;
                          function clearDelegate(bytes32 id) external;
                        }
                        pragma solidity 0.8.16;
                        interface CvxLockerV2 {
                          event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                          event Recovered(address _token, uint256 _amount);
                          event RewardAdded(address indexed _token, uint256 _reward);
                          event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
                          event Staked(
                            address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount
                          );
                          event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
                          struct EarnedData {
                            address token;
                            uint256 amount;
                          }
                          struct LockedBalance {
                            uint112 amount;
                            uint112 boosted;
                            uint32 unlockTime;
                          }
                          function addReward(address _rewardsToken, address _distributor, bool _useBoost) external;
                          function approveRewardDistributor(address _rewardsToken, address _distributor, bool _approved) external;
                          function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);
                          function balanceOf(address _user) external view returns (uint256 amount);
                          function balances(address) external view returns (uint112 locked, uint112 boosted, uint32 nextUnlockIndex);
                          function boostPayment() external view returns (address);
                          function boostRate() external view returns (uint256);
                          function boostedSupply() external view returns (uint256);
                          function checkpointEpoch() external;
                          function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards);
                          function cvxCrv() external view returns (address);
                          function cvxcrvStaking() external view returns (address);
                          function decimals() external view returns (uint8);
                          function denominator() external view returns (uint256);
                          function epochCount() external view returns (uint256);
                          function epochs(uint256) external view returns (uint224 supply, uint32 date);
                          function findEpochId(uint256 _time) external view returns (uint256 epoch);
                          function getReward(address _account, bool _stake) external;
                          function getReward(address _account) external;
                          function getRewardForDuration(address _rewardsToken) external view returns (uint256);
                          function isShutdown() external view returns (bool);
                          function kickExpiredLocks(address _account) external;
                          function kickRewardEpochDelay() external view returns (uint256);
                          function kickRewardPerEpoch() external view returns (uint256);
                          function lastTimeRewardApplicable(address _rewardsToken) external view returns (uint256);
                          function lock(address _account, uint256 _amount, uint256 _spendRatio) external;
                          function lockDuration() external view returns (uint256);
                          function lockedBalanceOf(address _user) external view returns (uint256 amount);
                          function lockedBalances(address _user)
                            external
                            view
                            returns (uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData);
                          function lockedSupply() external view returns (uint256);
                          function maximumBoostPayment() external view returns (uint256);
                          function maximumStake() external view returns (uint256);
                          function minimumStake() external view returns (uint256);
                          function name() external view returns (string memory);
                          function nextBoostRate() external view returns (uint256);
                          function nextMaximumBoostPayment() external view returns (uint256);
                          function notifyRewardAmount(address _rewardsToken, uint256 _reward) external;
                          function owner() external view returns (address);
                          function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);
                          function pendingLockOf(address _user) external view returns (uint256 amount);
                          function processExpiredLocks(bool _relock) external;
                          function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external;
                          function renounceOwnership() external;
                          function rewardData(address)
                            external
                            view
                            returns (
                              bool useBoost,
                              uint40 periodFinish,
                              uint208 rewardRate,
                              uint40 lastUpdateTime,
                              uint208 rewardPerTokenStored
                            );
                          function rewardDistributors(address, address) external view returns (bool);
                          function rewardPerToken(address _rewardsToken) external view returns (uint256);
                          function rewardTokens(uint256) external view returns (address);
                          function rewardWeightOf(address _user) external view returns (uint256 amount);
                          function rewards(address, address) external view returns (uint256);
                          function rewardsDuration() external view returns (uint256);
                          function setApprovals() external;
                          function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external;
                          function setKickIncentive(uint256 _rate, uint256 _delay) external;
                          function setStakeLimits(uint256 _minimum, uint256 _maximum) external;
                          function setStakingContract(address _staking) external;
                          function shutdown() external;
                          function stakeOffsetOnLock() external view returns (uint256);
                          function stakingProxy() external view returns (address);
                          function stakingToken() external view returns (address);
                          function symbol() external view returns (string memory);
                          function totalSupply() external view returns (uint256 supply);
                          function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply);
                          function transferOwnership(address newOwner) external;
                          function userLocks(address, uint256) external view returns (uint112 amount, uint112 boosted, uint32 unlockTime);
                          function userRewardPerTokenPaid(address, address) external view returns (uint256);
                          function version() external view returns (uint256);
                          function withdrawExpiredLocksTo(address _withdrawTo) external;
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library Math {
                            enum Rounding {
                                Down, // Toward negative infinity
                                Up, // Toward infinity
                                Zero // Toward zero
                            }
                            /**
                             * @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 average of two numbers. The result is rounded towards
                             * zero.
                             */
                            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                // (a + b) / 2 can overflow.
                                return (a & b) + (a ^ b) / 2;
                            }
                            /**
                             * @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;
                            }
                            /**
                             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                             * with further edits by Uniswap Labs also under MIT license.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator
                            ) internal pure returns (uint256 result) {
                                unchecked {
                                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                    // variables such that product = prod1 * 2^256 + prod0.
                                    uint256 prod0; // Least significant 256 bits of the product
                                    uint256 prod1; // Most significant 256 bits of the product
                                    assembly {
                                        let mm := mulmod(x, y, not(0))
                                        prod0 := mul(x, y)
                                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                    }
                                    // Handle non-overflow cases, 256 by 256 division.
                                    if (prod1 == 0) {
                                        return prod0 / denominator;
                                    }
                                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                    require(denominator > prod1);
                                    ///////////////////////////////////////////////
                                    // 512 by 256 division.
                                    ///////////////////////////////////////////////
                                    // Make division exact by subtracting the remainder from [prod1 prod0].
                                    uint256 remainder;
                                    assembly {
                                        // Compute remainder using mulmod.
                                        remainder := mulmod(x, y, denominator)
                                        // Subtract 256 bit number from 512 bit number.
                                        prod1 := sub(prod1, gt(remainder, prod0))
                                        prod0 := sub(prod0, remainder)
                                    }
                                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                    // See https://cs.stackexchange.com/q/138556/92363.
                                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                                    uint256 twos = denominator & (~denominator + 1);
                                    assembly {
                                        // Divide denominator by twos.
                                        denominator := div(denominator, twos)
                                        // Divide [prod1 prod0] by twos.
                                        prod0 := div(prod0, twos)
                                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                        twos := add(div(sub(0, twos), twos), 1)
                                    }
                                    // Shift in bits from prod1 into prod0.
                                    prod0 |= prod1 * twos;
                                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                    // four bits. That is, denominator * inv = 1 mod 2^4.
                                    uint256 inverse = (3 * denominator) ^ 2;
                                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                    // in modular arithmetic, doubling the correct bits in each step.
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                    // is no longer required.
                                    result = prod0 * inverse;
                                    return result;
                                }
                            }
                            /**
                             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator,
                                Rounding rounding
                            ) internal pure returns (uint256) {
                                uint256 result = mulDiv(x, y, denominator);
                                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                    result += 1;
                                }
                                return result;
                            }
                            /**
                             * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                             *
                             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                             */
                            function sqrt(uint256 a) internal pure returns (uint256) {
                                if (a == 0) {
                                    return 0;
                                }
                                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                //
                                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                //
                                // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                //
                                // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                uint256 result = 1 << (log2(a) >> 1);
                                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                // into the expected uint128 result.
                                unchecked {
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    return min(result, a / result);
                                }
                            }
                            /**
                             * @notice Calculates sqrt(a), following the selected rounding direction.
                             */
                            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = sqrt(a);
                                    return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 2, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 128;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 64;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 32;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 16;
                                    }
                                    if (value >> 8 > 0) {
                                        value >>= 8;
                                        result += 8;
                                    }
                                    if (value >> 4 > 0) {
                                        value >>= 4;
                                        result += 4;
                                    }
                                    if (value >> 2 > 0) {
                                        value >>= 2;
                                        result += 2;
                                    }
                                    if (value >> 1 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log2(value);
                                    return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 10, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >= 10**64) {
                                        value /= 10**64;
                                        result += 64;
                                    }
                                    if (value >= 10**32) {
                                        value /= 10**32;
                                        result += 32;
                                    }
                                    if (value >= 10**16) {
                                        value /= 10**16;
                                        result += 16;
                                    }
                                    if (value >= 10**8) {
                                        value /= 10**8;
                                        result += 8;
                                    }
                                    if (value >= 10**4) {
                                        value /= 10**4;
                                        result += 4;
                                    }
                                    if (value >= 10**2) {
                                        value /= 10**2;
                                        result += 2;
                                    }
                                    if (value >= 10**1) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log10(value);
                                    return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 256, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             *
                             * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                             */
                            function log256(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 16;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 8;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 4;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 2;
                                    }
                                    if (value >> 8 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log256(value);
                                    return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                                }
                            }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {Harvestable} from "./Harvestable.sol";
                        import {IWarLocker} from "interfaces/IWarLocker.sol";
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {Pausable} from "openzeppelin/security/Pausable.sol";
                        import {ReentrancyGuard} from "openzeppelin/security/ReentrancyGuard.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {IWarRedeemModule} from "interfaces/IWarRedeemModule.sol";
                        import {WarMinter} from "src/Minter.sol";
                        /**
                         * @title Warlord Base Locker contract
                         * @author Paladin
                         * @notice Base implementation for Locker contracts
                         */
                        abstract contract WarBaseLocker is IWarLocker, Pausable, Owner, ReentrancyGuard, Harvestable {
                          /**
                           * @notice Address of the voting power delegate
                           */
                          address public delegate;
                          /**
                           * @notice Address of the Redeem Module contract
                           */
                          address public redeemModule;
                          /**
                           * @notice Address of the Controller contract
                           */
                          address public controller;
                          /**
                           * @notice Address of the Minter contract
                           */
                          address public warMinter;
                          /**
                           * @notice Is the contract shutdown
                           */
                          bool public isShutdown;
                          /**
                           * @notice Event emitted when the Controller is set
                           */
                          event SetController(address newController);
                          /**
                           * @notice Event emitted when the Redeem Module is set
                           */
                          event SetRedeemModule(address newRedeemModule);
                          /**
                           * @notice Event emitted when the delegate is updated
                           */
                          event SetDelegate(address newDelegatee);
                          /**
                           * @notice Event emitted when the Locker is shutdown
                           */
                          event Shutdown();
                          // Constructor
                          constructor(address _controller, address _redeemModule, address _warMinter, address _delegatee) {
                            if (_controller == address(0) || _redeemModule == address(0) || _warMinter == address(0)) {
                              revert Errors.ZeroAddress();
                            }
                            warMinter = _warMinter;
                            controller = _controller;
                            redeemModule = _redeemModule;
                            delegate = _delegatee;
                          }
                          /**
                           * @notice Returns the current total amount of locked tokens for this Locker
                           */
                          function getCurrentLockedTokens() external view virtual returns (uint256);
                          /**
                           * @notice Updates the Controller contract
                           * @param _controller Address of the Controller contract
                           */
                          function setController(address _controller) external onlyOwner {
                            if (_controller == address(0)) revert Errors.ZeroAddress();
                            if (_controller == controller) revert Errors.AlreadySet();
                            controller = _controller;
                            emit SetController(_controller);
                          }
                          /**
                           * @notice Updates the Redeem Module contract
                           * @param _redeemModule Address of the Redeem Module contract
                           */
                          function setRedeemModule(address _redeemModule) external onlyOwner {
                            if (_redeemModule == address(0)) revert Errors.ZeroAddress();
                            if (_redeemModule == address(redeemModule)) revert Errors.AlreadySet();
                            redeemModule = _redeemModule;
                            emit SetRedeemModule(_redeemModule);
                          }
                          /**
                           * @dev Updates the Delegatee & delegates the voting power
                           * @param _delegatee Address of the delegatee
                           */
                          function _setDelegate(address _delegatee) internal virtual;
                          /**
                           * @notice Updates the Delegatee & delegates the voting power
                           * @param _delegatee Address of the delegatee
                           */
                          function setDelegate(address _delegatee) external onlyOwner {
                            delegate = _delegatee;
                            _setDelegate(_delegatee);
                            emit SetDelegate(_delegatee);
                          }
                          /**
                           * @dev Locks the tokens in the vlToken contract
                           * @param amount Amount to lock
                           */
                          function _lock(uint256 amount) internal virtual;
                          /**
                           * @notice Locks the tokens in the vlToken contract
                           * @param amount Amount to lock
                           */
                          function lock(uint256 amount) external nonReentrant whenNotPaused {
                            if (warMinter != msg.sender) revert Errors.CallerNotAllowed();
                            if (amount == 0) revert Errors.ZeroValue();
                            _lock(amount);
                          }
                          /**
                           * @dev Processes the unlock of tokens
                           */
                          function _processUnlock() internal virtual;
                          /**
                           * @notice Processes the unlock of tokens
                           */
                          function processUnlock() external nonReentrant whenNotPaused {
                            _processUnlock();
                          }
                          /**
                           * @dev Harvest rewards & send them to the Controller
                           */
                          function _harvest() internal virtual;
                          /**
                           * @notice Harvest rewards
                           */
                          function harvest() external whenNotPaused {
                            _harvest();
                          }
                          /**
                           * @dev Migrates the tokens hold by this contract to another address (& unlocks everything that can be unlocked)
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal virtual;
                          /**
                           * @notice Migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function migrate(address receiver) external nonReentrant onlyOwner whenPaused {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            _migrate(receiver);
                          }
                          /**
                           * @notice Pause the contract
                           */
                          function pause() external onlyOwner {
                            _pause();
                          }
                          /**
                           * @notice Unpause the contract
                           */
                          function unpause() external onlyOwner {
                            if (isShutdown) revert Errors.LockerShutdown();
                            _unpause();
                          }
                          /**
                           * @notice Shutdowns the contract
                           */
                          function shutdown() external onlyOwner whenPaused {
                            isShutdown = true;
                            emit Shutdown();
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        import {IHiddenHandDistributor} from "interfaces/external/incentives/IIncentivesDistributors.sol";
                        interface IIncentivizedLocker {
                          function claimQuestRewards(
                            address distributor,
                            uint256 questID,
                            uint256 period,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external;
                          function claimDelegationRewards(
                            address distributor,
                            address token,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external;
                          function claimVotiumRewards(
                            address distributor,
                            address token,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external;
                          function claimHiddenHandRewards(address distributor, IHiddenHandDistributor.Claim[] calldata claimParams) external;
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IQuestDistributor {
                          function questRewardToken(uint256 questID) external view returns (address);
                          //Struct ClaimParams
                          struct ClaimParams {
                            uint256 questID;
                            uint256 period;
                            uint256 index;
                            uint256 amount;
                            bytes32[] merkleProof;
                          }
                          function claim(
                            uint256 questID,
                            uint256 period,
                            uint256 index,
                            address account,
                            uint256 amount,
                            bytes32[] calldata merkleProof
                          ) external;
                        }
                        interface IDelegationDistributor {
                          //Struct ClaimParams
                          struct ClaimParams {
                            address token;
                            uint256 index;
                            uint256 amount;
                            bytes32[] merkleProof;
                          }
                          function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof)
                            external;
                        }
                        interface IVotiumDistributor {
                          struct claimParam {
                            address token;
                            uint256 index;
                            uint256 amount;
                            bytes32[] merkleProof;
                          }
                          function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof)
                            external;
                        }
                        interface IHiddenHandDistributor {
                          struct Reward {
                            address token;
                            bytes32 merkleRoot;
                            bytes32 proof;
                            uint256 updateCount;
                          }
                          function rewards(bytes32 indentifier) external view returns (Reward memory);
                          struct Claim {
                            bytes32 identifier;
                            address account;
                            uint256 amount;
                            bytes32[] merkleProof;
                          }
                          function claim(Claim[] calldata _claims) external;
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IHarvestable} from "interfaces/IHarvestable.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Harvestable contract
                         * @author Paladin
                         * @notice Contract harvesting reward tokens to send to the Controller
                         */
                        abstract contract Harvestable is IHarvestable, Owner {
                          /**
                           * @notice List of harvestable reward tokens
                           */
                          address[] private _rewardTokens;
                          /**
                           * @notice Set to true when a reward token is listed
                           */
                          mapping(address => bool) private _rewardAssigned;
                          /**
                           * @notice Returns the list of rewards token that can be harvested for this contract
                           * @return address[] : List of tokens
                           */
                          function rewardTokens() external view returns (address[] memory) {
                            return _rewardTokens;
                          }
                          /**
                           * @notice Adds a token to the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function addReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (_rewardAssigned[reward]) revert Errors.AlreadySet();
                            _rewardTokens.push(reward);
                            _rewardAssigned[reward] = true;
                          }
                          /**
                           * @notice Removes a token from the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function removeReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (!_rewardAssigned[reward]) revert Errors.NotRewardToken();
                            // remove the reward without leaving holes in the array
                            address[] memory rewardTokens_ = _rewardTokens;
                            uint256 length = rewardTokens_.length;
                            uint256 lastIndex = length - 1;
                            for (uint256 i; i < length;) {
                              if (rewardTokens_[i] == reward) {
                                if (i != lastIndex) {
                                  _rewardTokens[i] = rewardTokens_[lastIndex];
                                }
                                _rewardTokens.pop();
                                break;
                              }
                              unchecked {
                                ++i;
                              }
                            }
                            // rewardToken is no longer part of the list
                            _rewardAssigned[reward] = false;
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        import {IHarvestable} from "./IHarvestable.sol";
                        interface IWarLocker is IHarvestable {
                          function lock(uint256 amount) external;
                          function token() external view returns (address);
                          function getCurrentLockedTokens() external view returns (uint256);
                          function processUnlock() external;
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.6.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.7.0) (security/Pausable.sol)
                        pragma solidity ^0.8.0;
                        import "../utils/Context.sol";
                        /**
                         * @dev Contract module which allows children to implement an emergency stop
                         * mechanism that can be triggered by an authorized account.
                         *
                         * This module is used through inheritance. It will make available the
                         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                         * the functions of your contract. Note that they will not be pausable by
                         * simply including this module, only once the modifiers are put in place.
                         */
                        abstract contract Pausable is Context {
                            /**
                             * @dev Emitted when the pause is triggered by `account`.
                             */
                            event Paused(address account);
                            /**
                             * @dev Emitted when the pause is lifted by `account`.
                             */
                            event Unpaused(address account);
                            bool private _paused;
                            /**
                             * @dev Initializes the contract in unpaused state.
                             */
                            constructor() {
                                _paused = false;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is not paused.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            modifier whenNotPaused() {
                                _requireNotPaused();
                                _;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is paused.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            modifier whenPaused() {
                                _requirePaused();
                                _;
                            }
                            /**
                             * @dev Returns true if the contract is paused, and false otherwise.
                             */
                            function paused() public view virtual returns (bool) {
                                return _paused;
                            }
                            /**
                             * @dev Throws if the contract is paused.
                             */
                            function _requireNotPaused() internal view virtual {
                                require(!paused(), "Pausable: paused");
                            }
                            /**
                             * @dev Throws if the contract is not paused.
                             */
                            function _requirePaused() internal view virtual {
                                require(paused(), "Pausable: not paused");
                            }
                            /**
                             * @dev Triggers stopped state.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            function _pause() internal virtual whenNotPaused {
                                _paused = true;
                                emit Paused(_msgSender());
                            }
                            /**
                             * @dev Returns to normal state.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            function _unpause() internal virtual whenPaused {
                                _paused = false;
                                emit Unpaused(_msgSender());
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.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;
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
                        pragma solidity ^0.8.0;
                        import "../IERC20.sol";
                        import "../extensions/draft-IERC20Permit.sol";
                        import "../../../utils/Address.sol";
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using Address for address;
                            function safeTransfer(
                                IERC20 token,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(
                                IERC20 token,
                                address from,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                require(
                                    (value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                uint256 newAllowance = token.allowance(address(this), spender) + value;
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                unchecked {
                                    uint256 oldAllowance = token.allowance(address(this), spender);
                                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                    uint256 newAllowance = oldAllowance - value;
                                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                }
                            }
                            function safePermit(
                                IERC20Permit token,
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                uint256 nonceBefore = token.nonces(owner);
                                token.permit(owner, spender, value, deadline, v, r, s);
                                uint256 nonceAfter = token.nonces(owner);
                                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) {
                                    // Return data is optional
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IWarRedeemModule {
                          function queuedForWithdrawal(address token) external returns (uint256);
                          function notifyUnlock(address token, uint256 amount) external;
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {WarToken} from "./Token.sol";
                        import {IWarLocker} from "interfaces/IWarLocker.sol";
                        import {IRatios} from "interfaces/IRatios.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {ReentrancyGuard} from "openzeppelin/security/ReentrancyGuard.sol";
                        /**
                         * @title Warlord Minter contract
                         * @author Paladin
                         * @notice Receives vlToken to deposit in Lockers and mints WAR
                         */
                        contract WarMinter is Owner, ReentrancyGuard {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice WAR token contract
                           */
                          WarToken public immutable war;
                          /**
                           * @notice Address of the contract calculating the mint amounts
                           */
                          IRatios public ratios;
                          /**
                           * @notice Address of the Locker set for each token
                           */
                          mapping(address => address) public lockers;
                          /**
                           * @notice Event emitted when the Ratio contract is updated
                           */
                          event MintRatioUpdated(address oldMintRatio, address newMintRatio);
                          // Constructor
                          constructor(address _war, address _ratios) {
                            if (_war == address(0) || _ratios == address(0)) revert Errors.ZeroAddress();
                            war = WarToken(_war);
                            ratios = IRatios(_ratios);
                          }
                          /**
                           * @notice Sets a new Locker for a given token
                           * @param vlToken Address of the token
                           * @param warLocker Address of the Locker
                           */
                          function setLocker(address vlToken, address warLocker) external onlyOwner {
                            if (vlToken == address(0) || warLocker == address(0)) revert Errors.ZeroAddress();
                            address expectedToken = IWarLocker(warLocker).token();
                            if (expectedToken != vlToken) revert Errors.MismatchingLocker(expectedToken, vlToken);
                            lockers[vlToken] = warLocker;
                          }
                          /**
                           * @notice Mints WAR token based of the amount of token deposited
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           */
                          function mint(address vlToken, uint256 amount) external nonReentrant {
                            _mint(vlToken, amount, msg.sender);
                          }
                          /**
                           * @notice Mints WAR token based of the amount of token deposited, mints for the given receiver
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function mint(address vlToken, uint256 amount, address receiver) external nonReentrant {
                            _mint(vlToken, amount, receiver);
                          }
                          /**
                           * @dev Pulls tokens to deposit in the associated Locker & mints WAR based on the deposited amount
                           * @param vlToken Address of the token to deposit
                           * @param amount Amount to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function _mint(address vlToken, uint256 amount, address receiver) internal {
                            if (amount == 0) revert Errors.ZeroValue();
                            if (vlToken == address(0) || receiver == address(0)) revert Errors.ZeroAddress();
                            if (lockers[vlToken] == address(0)) revert Errors.NoWarLocker();
                            // Load the correct Locker contract
                            IWarLocker locker = IWarLocker(lockers[vlToken]);
                            // Pull the tokens, and deposit them in the Locker
                            IERC20(vlToken).safeTransferFrom(msg.sender, address(this), amount);
                            if (IERC20(vlToken).allowance(address(this), address(locker)) != 0) IERC20(vlToken).safeApprove(address(locker), 0);
                            IERC20(vlToken).safeIncreaseAllowance(address(locker), amount);
                            locker.lock(amount);
                            // Get the amount of WAR to mint for the deposited amount
                            uint256 mintAmount = ratios.getMintAmount(vlToken, amount);
                            if (mintAmount == 0) revert Errors.ZeroMintAmount();
                            // Mint the WAR to the receiver
                            war.mint(receiver, mintAmount);
                          }
                          /**
                           * @dev Pulls multiple tokens to deposit in the associated Locker & mints WAR based on the deposited amounts
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function _mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts, address receiver) internal {
                            if (vlTokens.length != amounts.length) revert Errors.DifferentSizeArrays(vlTokens.length, amounts.length);
                            if (vlTokens.length == 0) revert Errors.EmptyArray();
                            uint256 length = vlTokens.length;
                            for (uint256 i; i < length;) {
                              _mint(vlTokens[i], amounts[i], receiver);
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          /**
                           * @notice Mints WAR token based of the amounts of tokens deposited
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           * @param receiver Address to receive the minted WAR
                           */
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts, address receiver)
                            external
                            nonReentrant
                          {
                            _mintMultiple(vlTokens, amounts, receiver);
                          }
                          /**
                           * @notice Mints WAR token based of the amounts of tokens deposited
                           * @param vlTokens List of address of tokens to deposit
                           * @param amounts List of amounts to deposit
                           */
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts) external nonReentrant {
                            _mintMultiple(vlTokens, amounts, msg.sender);
                          }
                          /**
                           * @notice Sets the Ratio contract address
                           * @param newRatios Address of the new Ratio contract
                           */
                          function setRatios(address newRatios) external onlyOwner {
                            if (newRatios == address(0)) revert Errors.ZeroAddress();
                            address oldRatios = address(ratios);
                            ratios = IRatios(newRatios);
                            emit MintRatioUpdated(oldRatios, newRatios);
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IHarvestable {
                          function harvest() external;
                          function rewardTokens() external view returns (address[] memory);
                        }
                        // 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/draft-IERC20Permit.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @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 IERC20Permit {
                            /**
                             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                             * given ``owner``'s signed approval.
                             *
                             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                             * ordering also apply here.
                             *
                             * 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}).
                             *
                             * For more information on the signature format, see the
                             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                             * section].
                             */
                            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);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
                        pragma solidity ^0.8.1;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             *
                             * [IMPORTANT]
                             * ====
                             * You shouldn't rely on `isContract` to protect against flash loan attacks!
                             *
                             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                             * constructor.
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize/address.code.length, which returns 0
                                // for contracts in construction, since the code is only stored at the end
                                // of the constructor execution.
                                return account.code.length > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                (bool success, ) = recipient.call{value: amount}("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain `call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                (bool success, bytes memory returndata) = target.call{value: value}(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                             *
                             * _Available since v4.8._
                             */
                            function verifyCallResultFromTarget(
                                address target,
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                if (success) {
                                    if (returndata.length == 0) {
                                        // only check isContract if the call was successful and the return data is empty
                                        // otherwise we already know that it was a contract
                                        require(isContract(target), "Address: call to non-contract");
                                    }
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            /**
                             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                             * revert reason or using the provided one.
                             *
                             * _Available since v4.3._
                             */
                            function verifyCallResult(
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal pure returns (bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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);
                            }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {ERC20} from "solmate/tokens/ERC20.sol";
                        import {AccessControl} from "openzeppelin/access/AccessControl.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Warlord Token contract
                         * @author Paladin
                         * @notice ERC20 token minted by deposit in Warlord
                         */
                        contract WarToken is ERC20, AccessControl {
                          /**
                           * @notice Event emitted when a new pending owner is set
                           */
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          /**
                           * @notice Address of the current pending owner
                           */
                          address public pendingOwner;
                          /**
                           * @notice Address of the current owner
                           */
                          address public owner;
                          /**
                           * @notice Minter role
                           */
                          bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
                          /**
                           * @notice Burner role
                           */
                          bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
                          // Constructor
                          constructor() ERC20("Warlord token", "WAR", 18) {
                            owner = msg.sender;
                            _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
                            _setRoleAdmin(DEFAULT_ADMIN_ROLE, keccak256("NO_ROLE"));
                          }
                          /**
                           * @notice Set the given address as the new pending owner
                           * @param newOwner Address to set as pending owner
                           */
                          function transferOwnership(address newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
                            if (newOwner == address(0)) revert Errors.ZeroAddress();
                            if (newOwner == owner) revert Errors.CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          /**
                           * @notice Accept the ownership transfer (only callable by the current pending owner)
                           */
                          function acceptOwnership() external {
                            if (msg.sender != pendingOwner) revert Errors.CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            // Revoke the previous owner ADMIN role and set it for the new owner
                            _revokeRole(DEFAULT_ADMIN_ROLE, owner);
                            _grantRole(DEFAULT_ADMIN_ROLE, newOwner);
                            owner = newOwner;
                            // Reset the pending owner
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                          /**
                           * @notice Mints the given amount of tokens to the given address
                           * @param to Address to mint token to
                           * @param amount Amount of token to mint
                           */
                          function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
                            _mint(to, amount);
                          }
                          /**
                           * @notice Burns the given amount of tokens from the given address
                           * @param from Address to burn token from
                           * @param amount Amount of token to burn
                           */
                          function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
                            _burn(from, amount);
                          }
                          /**
                           * @dev Atomically increases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param addedValue Amount of token to increase the allowance
                           */
                          function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
                            uint256 newAllowance = allowance[msg.sender][spender] + addedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                          /**
                           * @dev Atomically decreases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param subtractedValue Amount of token to increase the allowance
                           */
                          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
                            uint256 currentAllowance = allowance[msg.sender][spender];
                            if (subtractedValue > currentAllowance) revert Errors.AllowanceUnderflow();
                            uint256 newAllowance = currentAllowance - subtractedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IRatios {
                          function getTokenRatio(address token) external view returns (uint256);
                          function addToken(address token, uint256 maxSupply) external;
                          function getMintAmount(address token, uint256 amount) external view returns (uint256 mintAmount);
                          function getBurnAmount(address token, uint256 amount) external view returns (uint256 burnAmount);
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                        /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                        abstract contract ERC20 {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                    METADATA STORAGE
                            //////////////////////////////////////////////////////////////*/
                            string public name;
                            string public symbol;
                            uint8 public immutable decimals;
                            /*//////////////////////////////////////////////////////////////
                                                      ERC20 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 public totalSupply;
                            mapping(address => uint256) public balanceOf;
                            mapping(address => mapping(address => uint256)) public allowance;
                            /*//////////////////////////////////////////////////////////////
                                                    EIP-2612 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 internal immutable INITIAL_CHAIN_ID;
                            bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                            mapping(address => uint256) public nonces;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                string memory _name,
                                string memory _symbol,
                                uint8 _decimals
                            ) {
                                name = _name;
                                symbol = _symbol;
                                decimals = _decimals;
                                INITIAL_CHAIN_ID = block.chainid;
                                INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                allowance[msg.sender][spender] = amount;
                                emit Approval(msg.sender, spender, amount);
                                return true;
                            }
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                balanceOf[msg.sender] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(msg.sender, to, amount);
                                return true;
                            }
                            function transferFrom(
                                address from,
                                address to,
                                uint256 amount
                            ) public virtual returns (bool) {
                                uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                balanceOf[from] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(from, to, amount);
                                return true;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     EIP-2612 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                // Unchecked because the only math done is incrementing
                                // the owner's nonce which cannot realistically overflow.
                                unchecked {
                                    address recoveredAddress = ecrecover(
                                        keccak256(
                                            abi.encodePacked(
                                                "\\x19\\x01",
                                                DOMAIN_SEPARATOR(),
                                                keccak256(
                                                    abi.encode(
                                                        keccak256(
                                                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                        ),
                                                        owner,
                                                        spender,
                                                        value,
                                                        nonces[owner]++,
                                                        deadline
                                                    )
                                                )
                                            )
                                        ),
                                        v,
                                        r,
                                        s
                                    );
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                    allowance[recoveredAddress][spender] = value;
                                }
                                emit Approval(owner, spender, value);
                            }
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                            }
                            function computeDomainSeparator() internal view virtual returns (bytes32) {
                                return
                                    keccak256(
                                        abi.encode(
                                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                            keccak256(bytes(name)),
                                            keccak256("1"),
                                            block.chainid,
                                            address(this)
                                        )
                                    );
                            }
                            /*//////////////////////////////////////////////////////////////
                                                INTERNAL MINT/BURN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function _mint(address to, uint256 amount) internal virtual {
                                totalSupply += amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(address(0), to, amount);
                            }
                            function _burn(address from, uint256 amount) internal virtual {
                                balanceOf[from] -= amount;
                                // Cannot underflow because a user's balance
                                // will never be larger than the total supply.
                                unchecked {
                                    totalSupply -= amount;
                                }
                                emit Transfer(from, address(0), amount);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
                        pragma solidity ^0.8.0;
                        import "./IAccessControl.sol";
                        import "../utils/Context.sol";
                        import "../utils/Strings.sol";
                        import "../utils/introspection/ERC165.sol";
                        /**
                         * @dev Contract module that allows children to implement role-based access
                         * control mechanisms. This is a lightweight version that doesn't allow enumerating role
                         * members except through off-chain means by accessing the contract event logs. Some
                         * applications may benefit from on-chain enumerability, for those cases see
                         * {AccessControlEnumerable}.
                         *
                         * Roles are referred to by their `bytes32` identifier. These should be exposed
                         * in the external API and be unique. The best way to achieve this is by
                         * using `public constant` hash digests:
                         *
                         * ```
                         * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                         * ```
                         *
                         * Roles can be used to represent a set of permissions. To restrict access to a
                         * function call, use {hasRole}:
                         *
                         * ```
                         * function foo() public {
                         *     require(hasRole(MY_ROLE, msg.sender));
                         *     ...
                         * }
                         * ```
                         *
                         * Roles can be granted and revoked dynamically via the {grantRole} and
                         * {revokeRole} functions. Each role has an associated admin role, and only
                         * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                         *
                         * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                         * that only accounts with this role will be able to grant or revoke other
                         * roles. More complex role relationships can be created by using
                         * {_setRoleAdmin}.
                         *
                         * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                         * grant and revoke this role. Extra precautions should be taken to secure
                         * accounts that have been granted it.
                         */
                        abstract contract AccessControl is Context, IAccessControl, ERC165 {
                            struct RoleData {
                                mapping(address => bool) members;
                                bytes32 adminRole;
                            }
                            mapping(bytes32 => RoleData) private _roles;
                            bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                            /**
                             * @dev Modifier that checks that an account has a specific role. Reverts
                             * with a standardized message including the required role.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             *
                             * _Available since v4.1._
                             */
                            modifier onlyRole(bytes32 role) {
                                _checkRole(role);
                                _;
                            }
                            /**
                             * @dev See {IERC165-supportsInterface}.
                             */
                            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                                return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
                            }
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                                return _roles[role].members[account];
                            }
                            /**
                             * @dev Revert with a standard message if `_msgSender()` is missing `role`.
                             * Overriding this function changes the behavior of the {onlyRole} modifier.
                             *
                             * Format of the revert message is described in {_checkRole}.
                             *
                             * _Available since v4.6._
                             */
                            function _checkRole(bytes32 role) internal view virtual {
                                _checkRole(role, _msgSender());
                            }
                            /**
                             * @dev Revert with a standard message if `account` is missing `role`.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             */
                            function _checkRole(bytes32 role, address account) internal view virtual {
                                if (!hasRole(role, account)) {
                                    revert(
                                        string(
                                            abi.encodePacked(
                                                "AccessControl: account ",
                                                Strings.toHexString(account),
                                                " is missing role ",
                                                Strings.toHexString(uint256(role), 32)
                                            )
                                        )
                                    );
                                }
                            }
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                                return _roles[role].adminRole;
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been revoked `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function renounceRole(bytes32 role, address account) public virtual override {
                                require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event. Note that unlike {grantRole}, this function doesn't perform any
                             * checks on the calling account.
                             *
                             * May emit a {RoleGranted} event.
                             *
                             * [WARNING]
                             * ====
                             * This function should only be called from the constructor when setting
                             * up the initial roles for the system.
                             *
                             * Using this function in any other way is effectively circumventing the admin
                             * system imposed by {AccessControl}.
                             * ====
                             *
                             * NOTE: This function is deprecated in favor of {_grantRole}.
                             */
                            function _setupRole(bytes32 role, address account) internal virtual {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Sets `adminRole` as ``role``'s admin role.
                             *
                             * Emits a {RoleAdminChanged} event.
                             */
                            function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                bytes32 previousAdminRole = getRoleAdmin(role);
                                _roles[role].adminRole = adminRole;
                                emit RoleAdminChanged(role, previousAdminRole, adminRole);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function _grantRole(bytes32 role, address account) internal virtual {
                                if (!hasRole(role, account)) {
                                    _roles[role].members[account] = true;
                                    emit RoleGranted(role, account, _msgSender());
                                }
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function _revokeRole(bytes32 role, address account) internal virtual {
                                if (hasRole(role, account)) {
                                    _roles[role].members[account] = false;
                                    emit RoleRevoked(role, account, _msgSender());
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev External interface of AccessControl declared to support ERC165 detection.
                         */
                        interface IAccessControl {
                            /**
                             * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                             *
                             * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                             * {RoleAdminChanged} not being emitted signaling this.
                             *
                             * _Available since v3.1._
                             */
                            event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                            /**
                             * @dev Emitted when `account` is granted `role`.
                             *
                             * `sender` is the account that originated the contract call, an admin role
                             * bearer except when using {AccessControl-_setupRole}.
                             */
                            event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Emitted when `account` is revoked `role`.
                             *
                             * `sender` is the account that originated the contract call:
                             *   - if using `revokeRole`, it is the admin role bearer
                             *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                             */
                            event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) external view returns (bool);
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {AccessControl-_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) external view returns (bytes32);
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function grantRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function revokeRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been granted `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             */
                            function renounceRole(bytes32 role, address account) external;
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
                        pragma solidity ^0.8.0;
                        import "./math/Math.sol";
                        /**
                         * @dev String operations.
                         */
                        library Strings {
                            bytes16 private constant _SYMBOLS = "0123456789abcdef";
                            uint8 private constant _ADDRESS_LENGTH = 20;
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                             */
                            function toString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    uint256 length = Math.log10(value) + 1;
                                    string memory buffer = new string(length);
                                    uint256 ptr;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        ptr := add(buffer, add(32, length))
                                    }
                                    while (true) {
                                        ptr--;
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                                        }
                                        value /= 10;
                                        if (value == 0) break;
                                    }
                                    return buffer;
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                             */
                            function toHexString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    return toHexString(value, Math.log256(value) + 1);
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                             */
                            function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                                bytes memory buffer = new bytes(2 * length + 2);
                                buffer[0] = "0";
                                buffer[1] = "x";
                                for (uint256 i = 2 * length + 1; i > 1; --i) {
                                    buffer[i] = _SYMBOLS[value & 0xf];
                                    value >>= 4;
                                }
                                require(value == 0, "Strings: hex length insufficient");
                                return string(buffer);
                            }
                            /**
                             * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                             */
                            function toHexString(address addr) internal pure returns (string memory) {
                                return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                            }
                        }
                        // 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/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);
                        }
                        

                        File 7 of 18: CvxLockerV2
                        // File: contracts\interfaces\MathUtil.sol
                        
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.6.12;
                        
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library MathUtil {
                            /**
                             * @dev Returns the smallest of two numbers.
                             */
                            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                return a < b ? a : b;
                            }
                        }
                        
                        // File: contracts\interfaces\IStakingProxy.sol
                        
                        pragma solidity 0.6.12;
                        
                        interface IStakingProxy {
                            function getBalance() external view returns(uint256);
                        
                            function withdraw(uint256 _amount) external;
                        
                            function stake() external;
                        
                            function distribute() external;
                        }
                        
                        // File: contracts\interfaces\IRewardStaking.sol
                        
                        pragma solidity 0.6.12;
                        
                        interface IRewardStaking {
                            function stakeFor(address, uint256) external;
                            function stake( uint256) external;
                            function withdraw(uint256 amount, bool claim) external;
                            function withdrawAndUnwrap(uint256 amount, bool claim) external;
                            function earned(address account) external view returns (uint256);
                            function getReward() external;
                            function getReward(address _account, bool _claimExtras) external;
                            function extraRewardsLength() external view returns (uint256);
                            function extraRewards(uint256 _pid) external view returns (address);
                            function rewardToken() external view returns (address);
                            function balanceOf(address _account) external view returns (uint256);
                        }
                        
                        // File: contracts\interfaces\BoringMath.sol
                        
                        pragma solidity 0.6.12;
                        
                        /// @notice A library for performing overflow-/underflow-safe math,
                        /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
                        library BoringMath {
                            function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        
                            function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
                                require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
                            }
                        
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "BoringMath: division by zero");
                                return a / b;
                            }
                        
                            function to128(uint256 a) internal pure returns (uint128 c) {
                                require(a <= uint128(-1), "BoringMath: uint128 Overflow");
                                c = uint128(a);
                            }
                        
                            function to64(uint256 a) internal pure returns (uint64 c) {
                                require(a <= uint64(-1), "BoringMath: uint64 Overflow");
                                c = uint64(a);
                            }
                        
                            function to32(uint256 a) internal pure returns (uint32 c) {
                                require(a <= uint32(-1), "BoringMath: uint32 Overflow");
                                c = uint32(a);
                            }
                        
                            function to40(uint256 a) internal pure returns (uint40 c) {
                                require(a <= uint40(-1), "BoringMath: uint40 Overflow");
                                c = uint40(a);
                            }
                        
                            function to112(uint256 a) internal pure returns (uint112 c) {
                                require(a <= uint112(-1), "BoringMath: uint112 Overflow");
                                c = uint112(a);
                            }
                        
                            function to224(uint256 a) internal pure returns (uint224 c) {
                                require(a <= uint224(-1), "BoringMath: uint224 Overflow");
                                c = uint224(a);
                            }
                        
                            function to208(uint256 a) internal pure returns (uint208 c) {
                                require(a <= uint208(-1), "BoringMath: uint208 Overflow");
                                c = uint208(a);
                            }
                        
                            function to216(uint256 a) internal pure returns (uint216 c) {
                                require(a <= uint216(-1), "BoringMath: uint216 Overflow");
                                c = uint216(a);
                            }
                        }
                        
                        /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
                        library BoringMath128 {
                            function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        }
                        
                        /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
                        library BoringMath64 {
                            function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        }
                        
                        /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
                        library BoringMath32 {
                            function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        
                            function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
                                require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
                            }
                        
                            function div(uint32 a, uint32 b) internal pure returns (uint32) {
                                require(b > 0, "BoringMath: division by zero");
                                return a / b;
                            }
                        }
                        
                        
                        /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
                        library BoringMath112 {
                            function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        
                            function mul(uint112 a, uint112 b) internal pure returns (uint112 c) {
                                require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
                            }
                            
                            function div(uint112 a, uint112 b) internal pure returns (uint112) {
                                require(b > 0, "BoringMath: division by zero");
                                return a / b;
                            }
                        }
                        
                        /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
                        library BoringMath224 {
                            function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
                                require((c = a + b) >= b, "BoringMath: Add Overflow");
                            }
                        
                            function sub(uint224 a, uint224 b) internal pure returns (uint224 c) {
                                require((c = a - b) <= a, "BoringMath: Underflow");
                            }
                        
                            function mul(uint224 a, uint224 b) internal pure returns (uint224 c) {
                                require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
                            }
                            
                            function div(uint224 a, uint224 b) internal pure returns (uint224) {
                                require(b > 0, "BoringMath: division by zero");
                                return a / b;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\IERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                        
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                        
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                        
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                        
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        
                        // File: @openzeppelin\contracts\math\SafeMath.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                uint256 c = a + b;
                                if (c < a) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b > a) return (false, 0);
                                return (true, a - b);
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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-contracts/pull/522
                                if (a == 0) return (true, 0);
                                uint256 c = a * b;
                                if (c / a != b) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the division of two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a / b);
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a % b);
                            }
                        
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b <= a, "SafeMath: subtraction overflow");
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot overflow.
                             */
                            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                if (a == 0) return 0;
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: division by zero");
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: modulo by zero");
                                return a % b;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {trySub}.
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryDiv}.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting with custom message when dividing by zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryMod}.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a % b;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\utils\Address.sol
                        pragma solidity >=0.6.2 <0.8.0;
                        
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                        
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                        
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                        
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                        
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                require(isContract(target), "Address: delegate call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                        
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                        
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                        
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                        
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                        
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                        
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        
                        // File: @openzeppelin\contracts\math\Math.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library Math {
                            /**
                             * @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 average of two numbers. The result is rounded towards
                             * zero.
                             */
                            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                // (a + b) / 2 can overflow, so we distribute
                                return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
                            }
                        }
                        
                        // File: @openzeppelin\contracts\utils\Context.sol
                        pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                return msg.sender;
                            }
                        
                            function _msgData() internal view virtual returns (bytes memory) {
                                this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                return msg.data;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\access\Ownable.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @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 () internal {
                                address msgSender = _msgSender();
                                _owner = msgSender;
                                emit OwnershipTransferred(address(0), msgSender);
                            }
                        
                            /**
                             * @dev Returns the address of the current owner.
                             */
                            function owner() public view virtual returns (address) {
                                return _owner;
                            }
                        
                            /**
                             * @dev Throws if called by any account other than the owner.
                             */
                            modifier onlyOwner() {
                                require(owner() == _msgSender(), "Ownable: caller is not the owner");
                                _;
                            }
                        
                            /**
                             * @dev Leaves the contract without owner. It will not be possible to call
                             * `onlyOwner` functions anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing any functionality that is only available to the owner.
                             */
                            function renounceOwnership() public virtual onlyOwner {
                                emit OwnershipTransferred(_owner, address(0));
                                _owner = 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");
                                emit OwnershipTransferred(_owner, newOwner);
                                _owner = newOwner;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\utils\ReentrancyGuard.sol
                        
                        pragma solidity >=0.6.0 <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 () internal {
                                _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 make it call a
                             * `private` function that does the actual work.
                             */
                            modifier nonReentrant() {
                                // On the first call to nonReentrant, _notEntered will be true
                                require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                        
                                // Any calls to nonReentrant after this point will fail
                                _status = _ENTERED;
                        
                                _;
                        
                                // By storing the original value once again, a refund is triggered (see
                                // https://eips.ethereum.org/EIPS/eip-2200)
                                _status = _NOT_ENTERED;
                            }
                        }
                        
                        // File: contracts\CvxLockerV2.sol
                        
                        pragma solidity 0.6.12;
                        pragma experimental ABIEncoderV2;
                        /*
                        CVX Locking contract for https://www.convexfinance.com/
                        CVX locked in this contract will be entitled to voting rights for the Convex Finance platform
                        Based on EPS Staking contract for http://ellipsis.finance/
                        Based on SNX MultiRewards by iamdefinitelyahuman - https://github.com/iamdefinitelyahuman/multi-rewards
                        
                        V2:
                        - change locking mechanism to lock to a future epoch instead of current
                        - pending lock getter
                        - relocking allocates weight to the current epoch instead of future,
                            thus allows keeping voting weight in the same epoch a lock expires by relocking before a vote begins
                        - balanceAtEpoch and supplyAtEpoch return proper values for future epochs
                        - do not allow relocking directly to a new address
                        */
                        contract CvxLockerV2 is ReentrancyGuard, Ownable {
                        
                            using BoringMath for uint256;
                            using BoringMath224 for uint224;
                            using BoringMath112 for uint112;
                            using BoringMath32 for uint32;
                            using SafeERC20
                            for IERC20;
                        
                            /* ========== STATE VARIABLES ========== */
                        
                            struct Reward {
                                bool useBoost;
                                uint40 periodFinish;
                                uint208 rewardRate;
                                uint40 lastUpdateTime;
                                uint208 rewardPerTokenStored;
                            }
                            struct Balances {
                                uint112 locked;
                                uint112 boosted;
                                uint32 nextUnlockIndex;
                            }
                            struct LockedBalance {
                                uint112 amount;
                                uint112 boosted;
                                uint32 unlockTime;
                            }
                            struct EarnedData {
                                address token;
                                uint256 amount;
                            }
                            struct Epoch {
                                uint224 supply; //epoch boosted supply
                                uint32 date; //epoch start date
                            }
                        
                            //token constants
                            IERC20 public constant stakingToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); //cvx
                            address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
                        
                            //rewards
                            address[] public rewardTokens;
                            mapping(address => Reward) public rewardData;
                        
                            // Duration that rewards are streamed over
                            uint256 public constant rewardsDuration = 86400 * 7;
                        
                            // Duration of lock/earned penalty period
                            uint256 public constant lockDuration = rewardsDuration * 16;
                        
                            // reward token -> distributor -> is approved to add rewards
                            mapping(address => mapping(address => bool)) public rewardDistributors;
                        
                            // user -> reward token -> amount
                            mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid;
                            mapping(address => mapping(address => uint256)) public rewards;
                        
                            //supplies and epochs
                            uint256 public lockedSupply;
                            uint256 public boostedSupply;
                            Epoch[] public epochs;
                        
                            //mappings for balance data
                            mapping(address => Balances) public balances;
                            mapping(address => LockedBalance[]) public userLocks;
                        
                            //boost
                            address public boostPayment = address(0x1389388d01708118b497f59521f6943Be2541bb7);
                            uint256 public maximumBoostPayment = 0;
                            uint256 public boostRate = 10000;
                            uint256 public nextMaximumBoostPayment = 0;
                            uint256 public nextBoostRate = 10000;
                            uint256 public constant denominator = 10000;
                        
                            //staking
                            uint256 public minimumStake = 10000;
                            uint256 public maximumStake = 10000;
                            address public stakingProxy;
                            address public constant cvxcrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
                            uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing
                        
                            //management
                            uint256 public kickRewardPerEpoch = 100;
                            uint256 public kickRewardEpochDelay = 4;
                        
                            //shutdown
                            bool public isShutdown = false;
                        
                            //erc20-like interface
                            string private _name;
                            string private _symbol;
                            uint8 private immutable _decimals;
                        
                            /* ========== CONSTRUCTOR ========== */
                        
                            constructor() public Ownable() {
                                _name = "Vote Locked Convex Token";
                                _symbol = "vlCVX";
                                _decimals = 18;
                        
                                uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
                                epochs.push(Epoch({
                                    supply: 0,
                                    date: uint32(currentEpoch)
                                }));
                            }
                        
                            function decimals() public view returns (uint8) {
                                return _decimals;
                            }
                            function name() public view returns (string memory) {
                                return _name;
                            }
                            function symbol() public view returns (string memory) {
                                return _symbol;
                            }
                            function version() public view returns(uint256){
                                return 2;
                            }
                        
                            /* ========== ADMIN CONFIGURATION ========== */
                        
                            // Add a new reward token to be distributed to stakers
                            function addReward(
                                address _rewardsToken,
                                address _distributor,
                                bool _useBoost
                            ) public onlyOwner {
                                require(rewardData[_rewardsToken].lastUpdateTime == 0);
                                require(_rewardsToken != address(stakingToken));
                                rewardTokens.push(_rewardsToken);
                                rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
                                rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
                                rewardData[_rewardsToken].useBoost = _useBoost;
                                rewardDistributors[_rewardsToken][_distributor] = true;
                            }
                        
                            // Modify approval for an address to call notifyRewardAmount
                            function approveRewardDistributor(
                                address _rewardsToken,
                                address _distributor,
                                bool _approved
                            ) external onlyOwner {
                                require(rewardData[_rewardsToken].lastUpdateTime > 0);
                                rewardDistributors[_rewardsToken][_distributor] = _approved;
                            }
                        
                            //Set the staking contract for the underlying cvx
                            function setStakingContract(address _staking) external onlyOwner {
                                require(stakingProxy == address(0), "!assign");
                        
                                stakingProxy = _staking;
                            }
                        
                            //set staking limits. will stake the mean of the two once either ratio is crossed
                            function setStakeLimits(uint256 _minimum, uint256 _maximum) external onlyOwner {
                                require(_minimum <= denominator, "min range");
                                require(_maximum <= denominator, "max range");
                                require(_minimum <= _maximum, "min range");
                                minimumStake = _minimum;
                                maximumStake = _maximum;
                                updateStakeRatio(0);
                            }
                        
                            //set boost parameters
                            function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external onlyOwner {
                                require(_max < 1500, "over max payment"); //max 15%
                                require(_rate < 30000, "over max rate"); //max 3x
                                require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
                                nextMaximumBoostPayment = _max;
                                nextBoostRate = _rate;
                                boostPayment = _receivingAddress;
                            }
                        
                            //set kick incentive
                            function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
                                require(_rate <= 500, "over max rate"); //max 5% per epoch
                                require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
                                kickRewardPerEpoch = _rate;
                                kickRewardEpochDelay = _delay;
                            }
                        
                            //shutdown the contract. unstake all tokens. release all locks
                            function shutdown() external onlyOwner {
                                if (stakingProxy != address(0)) {
                                    uint256 stakeBalance = IStakingProxy(stakingProxy).getBalance();
                                    IStakingProxy(stakingProxy).withdraw(stakeBalance);
                                }
                                isShutdown = true;
                            }
                        
                            //set approvals for staking cvx and cvxcrv
                            function setApprovals() external {
                                IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);
                                IERC20(cvxCrv).safeApprove(cvxcrvStaking, uint256(-1));
                        
                                IERC20(stakingToken).safeApprove(stakingProxy, 0);
                                IERC20(stakingToken).safeApprove(stakingProxy, uint256(-1));
                            }
                        
                            /* ========== VIEWS ========== */
                        
                            function _rewardPerToken(address _rewardsToken) internal view returns(uint256) {
                                if (boostedSupply == 0) {
                                    return rewardData[_rewardsToken].rewardPerTokenStored;
                                }
                                return
                                uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
                                    _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish).sub(
                                        rewardData[_rewardsToken].lastUpdateTime).mul(
                                        rewardData[_rewardsToken].rewardRate).mul(1e18).div(rewardData[_rewardsToken].useBoost ? boostedSupply : lockedSupply)
                                );
                            }
                        
                            function _earned(
                                address _user,
                                address _rewardsToken,
                                uint256 _balance
                            ) internal view returns(uint256) {
                                return _balance.mul(
                                    _rewardPerToken(_rewardsToken).sub(userRewardPerTokenPaid[_user][_rewardsToken])
                                ).div(1e18).add(rewards[_user][_rewardsToken]);
                            }
                        
                            function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns(uint256){
                                return Math.min(block.timestamp, _finishTime);
                            }
                        
                            function lastTimeRewardApplicable(address _rewardsToken) public view returns(uint256) {
                                return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
                            }
                        
                            function rewardPerToken(address _rewardsToken) external view returns(uint256) {
                                return _rewardPerToken(_rewardsToken);
                            }
                        
                            function getRewardForDuration(address _rewardsToken) external view returns(uint256) {
                                return uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
                            }
                        
                            // Address and claimable amount of all reward tokens for the given account
                            function claimableRewards(address _account) external view returns(EarnedData[] memory userRewards) {
                                userRewards = new EarnedData[](rewardTokens.length);
                                Balances storage userBalance = balances[_account];
                                uint256 boostedBal = userBalance.boosted;
                                for (uint256 i = 0; i < userRewards.length; i++) {
                                    address token = rewardTokens[i];
                                    userRewards[i].token = token;
                                    userRewards[i].amount = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked);
                                }
                                return userRewards;
                            }
                        
                            // Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
                            function rewardWeightOf(address _user) view external returns(uint256 amount) {
                                return balances[_user].boosted;
                            }
                        
                            // total token balance of an account, including unlocked but not withdrawn tokens
                            function lockedBalanceOf(address _user) view external returns(uint256 amount) {
                                return balances[_user].locked;
                            }
                        
                            //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
                            function balanceOf(address _user) view external returns(uint256 amount) {
                                LockedBalance[] storage locks = userLocks[_user];
                                Balances storage userBalance = balances[_user];
                                uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
                        
                                //start with current boosted amount
                                amount = balances[_user].boosted;
                        
                                uint256 locksLength = locks.length;
                                //remove old records only (will be better gas-wise than adding up)
                                for (uint i = nextUnlockIndex; i < locksLength; i++) {
                                    if (locks[i].unlockTime <= block.timestamp) {
                                        amount = amount.sub(locks[i].boosted);
                                    } else {
                                        //stop now as no futher checks are needed
                                        break;
                                    }
                                }
                        
                                //also remove amount locked in the next epoch
                                uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
                                if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch) {
                                    amount = amount.sub(locks[locksLength - 1].boosted);
                                }
                        
                                return amount;
                            }
                        
                            //BOOSTED balance of an account which only includes properly locked tokens at the given epoch
                            function balanceAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount) {
                                LockedBalance[] storage locks = userLocks[_user];
                        
                                //get timestamp of given epoch index
                                uint256 epochTime = epochs[_epoch].date;
                                //get timestamp of first non-inclusive epoch
                                uint256 cutoffEpoch = epochTime.sub(lockDuration);
                        
                                //need to add up since the range could be in the middle somewhere
                                //traverse inversely to make more current queries more gas efficient
                                for (uint i = locks.length - 1; i + 1 != 0; i--) {
                                    uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
                                    //lock epoch must be less or equal to the epoch we're basing from.
                                    if (lockEpoch <= epochTime) {
                                        if (lockEpoch > cutoffEpoch) {
                                            amount = amount.add(locks[i].boosted);
                                        } else {
                                            //stop now as no futher checks matter
                                            break;
                                        }
                                    }
                                }
                        
                                return amount;
                            }
                        
                            //return currently locked but not active balance
                            function pendingLockOf(address _user) view external returns(uint256 amount) {
                                LockedBalance[] storage locks = userLocks[_user];
                        
                                uint256 locksLength = locks.length;
                        
                                //return amount if latest lock is in the future
                                uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
                                if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) > currentEpoch) {
                                    return locks[locksLength - 1].boosted;
                                }
                        
                                return 0;
                            }
                        
                            function pendingLockAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount) {
                                LockedBalance[] storage locks = userLocks[_user];
                        
                                //get next epoch from the given epoch index
                                uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration);
                        
                                //traverse inversely to make more current queries more gas efficient
                                for (uint i = locks.length - 1; i + 1 != 0; i--) {
                                    uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
                                    
                                    //return the next epoch balance
                                    if (lockEpoch == nextEpoch) {
                                        return locks[i].boosted;
                                    }else if(lockEpoch < nextEpoch){
                                        //no need to check anymore
                                        break;
                                    }
                                }
                        
                                return 0;
                            }
                        
                            //supply of all properly locked BOOSTED balances at most recent eligible epoch
                            function totalSupply() view external returns(uint256 supply) {
                        
                                uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
                                uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
                                uint256 epochindex = epochs.length;
                        
                                //do not include next epoch's supply
                                if ( uint256(epochs[epochindex - 1].date) > currentEpoch ) {
                                    epochindex--;
                                }
                        
                                //traverse inversely to make more current queries more gas efficient
                                for (uint i = epochindex - 1; i + 1 != 0; i--) {
                                    Epoch storage e = epochs[i];
                                    if (uint256(e.date) <= cutoffEpoch) {
                                        break;
                                    }
                                    supply = supply.add(e.supply);
                                }
                        
                                return supply;
                            }
                        
                            //supply of all properly locked BOOSTED balances at the given epoch
                            function totalSupplyAtEpoch(uint256 _epoch) view external returns(uint256 supply) {
                        
                                uint256 epochStart = uint256(epochs[_epoch].date).div(rewardsDuration).mul(rewardsDuration);
                                uint256 cutoffEpoch = epochStart.sub(lockDuration);
                        
                                //traverse inversely to make more current queries more gas efficient
                                for (uint i = _epoch; i + 1 != 0; i--) {
                                    Epoch storage e = epochs[i];
                                    if (uint256(e.date) <= cutoffEpoch) {
                                        break;
                                    }
                                    supply = supply.add(epochs[i].supply);
                                }
                        
                                return supply;
                            }
                        
                            //find an epoch index based on timestamp
                            function findEpochId(uint256 _time) view external returns(uint256 epoch) {
                                uint256 max = epochs.length - 1;
                                uint256 min = 0;
                        
                                //convert to start point
                                _time = _time.div(rewardsDuration).mul(rewardsDuration);
                        
                                for (uint256 i = 0; i < 128; i++) {
                                    if (min >= max) break;
                        
                                    uint256 mid = (min + max + 1) / 2;
                                    uint256 midEpochBlock = epochs[mid].date;
                                    if(midEpochBlock == _time){
                                        //found
                                        return mid;
                                    }else if (midEpochBlock < _time) {
                                        min = mid;
                                    } else{
                                        max = mid - 1;
                                    }
                                }
                                return min;
                            }
                        
                        
                            // Information on a user's locked balances
                            function lockedBalances(
                                address _user
                            ) view external returns(
                                uint256 total,
                                uint256 unlockable,
                                uint256 locked,
                                LockedBalance[] memory lockData
                            ) {
                                LockedBalance[] storage locks = userLocks[_user];
                                Balances storage userBalance = balances[_user];
                                uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
                                uint256 idx;
                                for (uint i = nextUnlockIndex; i < locks.length; i++) {
                                    if (locks[i].unlockTime > block.timestamp) {
                                        if (idx == 0) {
                                            lockData = new LockedBalance[](locks.length - i);
                                        }
                                        lockData[idx] = locks[i];
                                        idx++;
                                        locked = locked.add(locks[i].amount);
                                    } else {
                                        unlockable = unlockable.add(locks[i].amount);
                                    }
                                }
                                return (userBalance.locked, unlockable, locked, lockData);
                            }
                        
                            //number of epochs
                            function epochCount() external view returns(uint256) {
                                return epochs.length;
                            }
                        
                            /* ========== MUTATIVE FUNCTIONS ========== */
                        
                            function checkpointEpoch() external {
                                _checkpointEpoch();
                            }
                        
                            //insert a new epoch if needed. fill in any gaps
                            function _checkpointEpoch() internal {
                                //create new epoch in the future where new non-active locks will lock to
                                uint256 nextEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration).add(rewardsDuration);
                                uint256 epochindex = epochs.length;
                        
                                //first epoch add in constructor, no need to check 0 length
                        
                                //check to add
                                if (epochs[epochindex - 1].date < nextEpoch) {
                                    //fill any epoch gaps
                                    while(epochs[epochs.length-1].date != nextEpoch){
                                        uint256 nextEpochDate = uint256(epochs[epochs.length-1].date).add(rewardsDuration);
                                        epochs.push(Epoch({
                                            supply: 0,
                                            date: uint32(nextEpochDate)
                                        }));
                                    }
                        
                                    //update boost parameters on a new epoch
                                    if(boostRate != nextBoostRate){
                                        boostRate = nextBoostRate;
                                    }
                                    if(maximumBoostPayment != nextMaximumBoostPayment){
                                        maximumBoostPayment = nextMaximumBoostPayment;
                                    }
                                }
                            }
                        
                            // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
                            function lock(address _account, uint256 _amount, uint256 _spendRatio) external nonReentrant updateReward(_account) {
                        
                                //pull tokens
                                stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
                        
                                //lock
                                _lock(_account, _amount, _spendRatio, false);
                            }
                        
                            //lock tokens
                            function _lock(address _account, uint256 _amount, uint256 _spendRatio, bool _isRelock) internal {
                                require(_amount > 0, "Cannot stake 0");
                                require(_spendRatio <= maximumBoostPayment, "over max spend");
                                require(!isShutdown, "shutdown");
                        
                                Balances storage bal = balances[_account];
                        
                                //must try check pointing epoch first
                                _checkpointEpoch();
                        
                                //calc lock and boosted amount
                                uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
                                uint256 boostRatio = boostRate.mul(_spendRatio).div(maximumBoostPayment==0?1:maximumBoostPayment);
                                uint112 lockAmount = _amount.sub(spendAmount).to112();
                                uint112 boostedAmount = _amount.add(_amount.mul(boostRatio).div(denominator)).to112();
                        
                                //add user balances
                                bal.locked = bal.locked.add(lockAmount);
                                bal.boosted = bal.boosted.add(boostedAmount);
                        
                                //add to total supplies
                                lockedSupply = lockedSupply.add(lockAmount);
                                boostedSupply = boostedSupply.add(boostedAmount);
                        
                                //add user lock records or add to current
                                uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
                                //if a fresh lock, add on an extra duration period
                                if(!_isRelock){
                                    lockEpoch = lockEpoch.add(rewardsDuration);
                                }
                                uint256 unlockTime = lockEpoch.add(lockDuration);
                                uint256 idx = userLocks[_account].length;
                        
                                //if the latest user lock is smaller than this lock, always just add new entry to the end of the list
                                if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
                                    userLocks[_account].push(LockedBalance({
                                        amount: lockAmount,
                                        boosted: boostedAmount,
                                        unlockTime: uint32(unlockTime)
                                    }));
                                } else {
                                    //else add to a current lock
                        
                                    //if latest lock is further in the future, lower index
                                    //this can only happen if relocking an expired lock after creating a new lock
                                    if(userLocks[_account][idx - 1].unlockTime > unlockTime){
                                        idx--;
                                    }
                        
                                    //if idx points to the epoch when same unlock time, update
                                    //(this is always true with a normal lock but maybe not with relock)
                                    if(userLocks[_account][idx - 1].unlockTime == unlockTime){
                                        LockedBalance storage userL = userLocks[_account][idx - 1];
                                        userL.amount = userL.amount.add(lockAmount);
                                        userL.boosted = userL.boosted.add(boostedAmount);
                                    }else{
                                        //can only enter here if a relock is made after a lock and there's no lock entry
                                        //for the current epoch.
                                        //ex a list of locks such as "[...][older][current*][next]" but without a "current" lock
                                        //length - 1 is the next epoch
                                        //length - 2 is a past epoch
                                        //thus need to insert an entry for current epoch at the 2nd to last entry
                                        //we will copy and insert the tail entry(next) and then overwrite length-2 entry
                        
                                        //reset idx
                                        idx = userLocks[_account].length;
                        
                                        //get current last item
                                        LockedBalance storage userL = userLocks[_account][idx - 1];
                        
                                        //add a copy to end of list
                                        userLocks[_account].push(LockedBalance({
                                            amount: userL.amount,
                                            boosted: userL.boosted,
                                            unlockTime: userL.unlockTime
                                        }));
                        
                                        //insert current epoch lock entry by overwriting the entry at length-2
                                        userL.amount = lockAmount;
                                        userL.boosted = boostedAmount;
                                        userL.unlockTime = uint32(unlockTime);
                                    }
                                }
                        
                                
                                //update epoch supply, epoch checkpointed above so safe to add to latest
                                uint256 eIndex = epochs.length - 1;
                                //if relock, epoch should be current and not next, thus need to decrease index to length-2
                                if(_isRelock){
                                    eIndex--;
                                }
                                Epoch storage e = epochs[eIndex];
                                e.supply = e.supply.add(uint224(boostedAmount));
                        
                                //send boost payment
                                if (spendAmount > 0) {
                                    stakingToken.safeTransfer(boostPayment, spendAmount);
                                }
                        
                                //update staking, allow a bit of leeway for smaller deposits to reduce gas
                                updateStakeRatio(stakeOffsetOnLock);
                        
                                emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount);
                            }
                        
                            // Withdraw all currently locked tokens where the unlock time has passed
                            function _processExpiredLocks(address _account, bool _relock, uint256 _spendRatio, address _withdrawTo, address _rewardAddress, uint256 _checkDelay) internal updateReward(_account) {
                                LockedBalance[] storage locks = userLocks[_account];
                                Balances storage userBalance = balances[_account];
                                uint112 locked;
                                uint112 boostedAmount;
                                uint256 length = locks.length;
                                uint256 reward = 0;
                                
                                if (isShutdown || locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)) {
                                    //if time is beyond last lock, can just bundle everything together
                                    locked = userBalance.locked;
                                    boostedAmount = userBalance.boosted;
                        
                                    //dont delete, just set next index
                                    userBalance.nextUnlockIndex = length.to32();
                        
                                    //check for kick reward
                                    //this wont have the exact reward rate that you would get if looped through
                                    //but this section is supposed to be for quick and easy low gas processing of all locks
                                    //we'll assume that if the reward was good enough someone would have processed at an earlier epoch
                                    if (_checkDelay > 0) {
                                        uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                                        uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
                                        uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
                                        reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
                                    }
                                } else {
                        
                                    //use a processed index(nextUnlockIndex) to not loop as much
                                    //deleting does not change array length
                                    uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
                                    for (uint i = nextUnlockIndex; i < length; i++) {
                                        //unlock time must be less or equal to time
                                        if (locks[i].unlockTime > block.timestamp.sub(_checkDelay)) break;
                        
                                        //add to cumulative amounts
                                        locked = locked.add(locks[i].amount);
                                        boostedAmount = boostedAmount.add(locks[i].boosted);
                        
                                        //check for kick reward
                                        //each epoch over due increases reward
                                        if (_checkDelay > 0) {
                                            uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
                                            uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);
                                            uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
                                            reward = reward.add( uint256(locks[i].amount).mul(rRate).div(denominator));
                                        }
                                        //set next unlock index
                                        nextUnlockIndex++;
                                    }
                                    //update next unlock index
                                    userBalance.nextUnlockIndex = nextUnlockIndex;
                                }
                                require(locked > 0, "no exp locks");
                        
                                //update user balances and total supplies
                                userBalance.locked = userBalance.locked.sub(locked);
                                userBalance.boosted = userBalance.boosted.sub(boostedAmount);
                                lockedSupply = lockedSupply.sub(locked);
                                boostedSupply = boostedSupply.sub(boostedAmount);
                        
                                emit Withdrawn(_account, locked, _relock);
                        
                                //send process incentive
                                if (reward > 0) {
                                    //if theres a reward(kicked), it will always be a withdraw only
                                    //preallocate enough cvx from stake contract to pay for both reward and withdraw
                                    allocateCVXForTransfer(uint256(locked));
                        
                                    //reduce return amount by the kick reward
                                    locked = locked.sub(reward.to112());
                                    
                                    //transfer reward
                                    transferCVX(_rewardAddress, reward, false);
                        
                                    emit KickReward(_rewardAddress, _account, reward);
                                }else if(_spendRatio > 0){
                                    //preallocate enough cvx to transfer the boost cost
                                    allocateCVXForTransfer( uint256(locked).mul(_spendRatio).div(denominator) );
                                }
                        
                                //relock or return to user
                                if (_relock) {
                                    _lock(_withdrawTo, locked, _spendRatio, true);
                                } else {
                                    transferCVX(_withdrawTo, locked, true);
                                }
                            }
                        
                            // withdraw expired locks to a different address
                            function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant {
                                _processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0);
                            }
                        
                            // Withdraw/relock all currently locked tokens where the unlock time has passed
                            function processExpiredLocks(bool _relock) external nonReentrant {
                                _processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
                            }
                        
                            function kickExpiredLocks(address _account) external nonReentrant {
                                //allow kick after grace period of 'kickRewardEpochDelay'
                                _processExpiredLocks(_account, false, 0, _account, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));
                            }
                        
                            //pull required amount of cvx from staking for an upcoming transfer
                            function allocateCVXForTransfer(uint256 _amount) internal{
                                uint256 balance = stakingToken.balanceOf(address(this));
                                if (_amount > balance) {
                                    IStakingProxy(stakingProxy).withdraw(_amount.sub(balance));
                                }
                            }
                        
                            //transfer helper: pull enough from staking, transfer, updating staking ratio
                            function transferCVX(address _account, uint256 _amount, bool _updateStake) internal {
                                //allocate enough cvx from staking for the transfer
                                allocateCVXForTransfer(_amount);
                                //transfer
                                stakingToken.safeTransfer(_account, _amount);
                        
                                //update staking
                                if(_updateStake){
                                    updateStakeRatio(0);
                                }
                            }
                        
                            //calculate how much cvx should be staked. update if needed
                            function updateStakeRatio(uint256 _offset) internal {
                                if (isShutdown) return;
                        
                                //get balances
                                uint256 local = stakingToken.balanceOf(address(this));
                                uint256 staked = IStakingProxy(stakingProxy).getBalance();
                                uint256 total = local.add(staked);
                                
                                if(total == 0) return;
                        
                                //current staked ratio
                                uint256 ratio = staked.mul(denominator).div(total);
                                //mean will be where we reset to if unbalanced
                                uint256 mean = maximumStake.add(minimumStake).div(2);
                                uint256 max = maximumStake.add(_offset);
                                uint256 min = Math.min(minimumStake, minimumStake - _offset);
                                if (ratio > max) {
                                    //remove
                                    uint256 remove = staked.sub(total.mul(mean).div(denominator));
                                    IStakingProxy(stakingProxy).withdraw(remove);
                                } else if (ratio < min) {
                                    //add
                                    uint256 increase = total.mul(mean).div(denominator).sub(staked);
                                    stakingToken.safeTransfer(stakingProxy, increase);
                                    IStakingProxy(stakingProxy).stake();
                                }
                            }
                        
                            // Claim all pending rewards
                            function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {
                                for (uint i; i < rewardTokens.length; i++) {
                                    address _rewardsToken = rewardTokens[i];
                                    uint256 reward = rewards[_account][_rewardsToken];
                                    if (reward > 0) {
                                        rewards[_account][_rewardsToken] = 0;
                                        if (_rewardsToken == cvxCrv && _stake) {
                                            IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);
                                        } else {
                                            IERC20(_rewardsToken).safeTransfer(_account, reward);
                                        }
                                        emit RewardPaid(_account, _rewardsToken, reward);
                                    }
                                }
                            }
                        
                            // claim all pending rewards
                            function getReward(address _account) external{
                                getReward(_account,false);
                            }
                        
                        
                            /* ========== RESTRICTED FUNCTIONS ========== */
                        
                            function _notifyReward(address _rewardsToken, uint256 _reward) internal {
                                Reward storage rdata = rewardData[_rewardsToken];
                        
                                if (block.timestamp >= rdata.periodFinish) {
                                    rdata.rewardRate = _reward.div(rewardsDuration).to208();
                                } else {
                                    uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);
                                    uint256 leftover = remaining.mul(rdata.rewardRate);
                                    rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to208();
                                }
                        
                                rdata.lastUpdateTime = block.timestamp.to40();
                                rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
                            }
                        
                            function notifyRewardAmount(address _rewardsToken, uint256 _reward) external updateReward(address(0)) {
                                require(rewardDistributors[_rewardsToken][msg.sender]);
                                require(_reward > 0, "No reward");
                        
                                _notifyReward(_rewardsToken, _reward);
                        
                                // handle the transfer of reward tokens via `transferFrom` to reduce the number
                                // of transactions required and ensure correctness of the _reward amount
                                IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);
                                
                                emit RewardAdded(_rewardsToken, _reward);
                        
                                if(_rewardsToken == cvxCrv){
                                    //update staking ratio if main reward
                                    updateStakeRatio(0);
                                }
                            }
                        
                            // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
                            function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
                                require(_tokenAddress != address(stakingToken), "Cannot withdraw staking token");
                                require(rewardData[_tokenAddress].lastUpdateTime == 0, "Cannot withdraw reward token");
                                IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
                                emit Recovered(_tokenAddress, _tokenAmount);
                            }
                        
                            /* ========== MODIFIERS ========== */
                        
                            modifier updateReward(address _account) {
                                {//stack too deep
                                    Balances storage userBalance = balances[_account];
                                    uint256 boostedBal = userBalance.boosted;
                                    for (uint i = 0; i < rewardTokens.length; i++) {
                                        address token = rewardTokens[i];
                                        rewardData[token].rewardPerTokenStored = _rewardPerToken(token).to208();
                                        rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to40();
                                        if (_account != address(0)) {
                                            //check if reward is boostable or not. use boosted or locked balance accordingly
                                            rewards[_account][token] = _earned(_account, token, rewardData[token].useBoost ? boostedBal : userBalance.locked );
                                            userRewardPerTokenPaid[_account][token] = rewardData[token].rewardPerTokenStored;
                                        }
                                    }
                                }
                                _;
                            }
                        
                            /* ========== EVENTS ========== */
                            event RewardAdded(address indexed _token, uint256 _reward);
                            event Staked(address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
                            event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
                            event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
                            event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
                            event Recovered(address _token, uint256 _amount);
                        }

                        File 8 of 18: WarToken
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {ERC20} from "solmate/tokens/ERC20.sol";
                        import {AccessControl} from "openzeppelin/access/AccessControl.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Warlord Token contract
                         * @author Paladin
                         * @notice ERC20 token minted by deposit in Warlord
                         */
                        contract WarToken is ERC20, AccessControl {
                          /**
                           * @notice Event emitted when a new pending owner is set
                           */
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          /**
                           * @notice Address of the current pending owner
                           */
                          address public pendingOwner;
                          /**
                           * @notice Address of the current owner
                           */
                          address public owner;
                          /**
                           * @notice Minter role
                           */
                          bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
                          /**
                           * @notice Burner role
                           */
                          bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
                          // Constructor
                          constructor() ERC20("Warlord token", "WAR", 18) {
                            owner = msg.sender;
                            _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
                            _setRoleAdmin(DEFAULT_ADMIN_ROLE, keccak256("NO_ROLE"));
                          }
                          /**
                           * @notice Set the given address as the new pending owner
                           * @param newOwner Address to set as pending owner
                           */
                          function transferOwnership(address newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
                            if (newOwner == address(0)) revert Errors.ZeroAddress();
                            if (newOwner == owner) revert Errors.CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          /**
                           * @notice Accept the ownership transfer (only callable by the current pending owner)
                           */
                          function acceptOwnership() external {
                            if (msg.sender != pendingOwner) revert Errors.CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            // Revoke the previous owner ADMIN role and set it for the new owner
                            _revokeRole(DEFAULT_ADMIN_ROLE, owner);
                            _grantRole(DEFAULT_ADMIN_ROLE, newOwner);
                            owner = newOwner;
                            // Reset the pending owner
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                          /**
                           * @notice Mints the given amount of tokens to the given address
                           * @param to Address to mint token to
                           * @param amount Amount of token to mint
                           */
                          function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
                            _mint(to, amount);
                          }
                          /**
                           * @notice Burns the given amount of tokens from the given address
                           * @param from Address to burn token from
                           * @param amount Amount of token to burn
                           */
                          function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
                            _burn(from, amount);
                          }
                          /**
                           * @dev Atomically increases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param addedValue Amount of token to increase the allowance
                           */
                          function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
                            uint256 newAllowance = allowance[msg.sender][spender] + addedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                          /**
                           * @dev Atomically decreases the allowance granted to `spender` by the caller.
                           * @param spender The address of the spender
                           * @param subtractedValue Amount of token to increase the allowance
                           */
                          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
                            uint256 currentAllowance = allowance[msg.sender][spender];
                            if (subtractedValue > currentAllowance) revert Errors.AllowanceUnderflow();
                            uint256 newAllowance = currentAllowance - subtractedValue;
                            allowance[msg.sender][spender] = newAllowance;
                            emit Approval(msg.sender, spender, newAllowance);
                            return true;
                          }
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                        /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                        abstract contract ERC20 {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                    METADATA STORAGE
                            //////////////////////////////////////////////////////////////*/
                            string public name;
                            string public symbol;
                            uint8 public immutable decimals;
                            /*//////////////////////////////////////////////////////////////
                                                      ERC20 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 public totalSupply;
                            mapping(address => uint256) public balanceOf;
                            mapping(address => mapping(address => uint256)) public allowance;
                            /*//////////////////////////////////////////////////////////////
                                                    EIP-2612 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 internal immutable INITIAL_CHAIN_ID;
                            bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                            mapping(address => uint256) public nonces;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                string memory _name,
                                string memory _symbol,
                                uint8 _decimals
                            ) {
                                name = _name;
                                symbol = _symbol;
                                decimals = _decimals;
                                INITIAL_CHAIN_ID = block.chainid;
                                INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                allowance[msg.sender][spender] = amount;
                                emit Approval(msg.sender, spender, amount);
                                return true;
                            }
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                balanceOf[msg.sender] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(msg.sender, to, amount);
                                return true;
                            }
                            function transferFrom(
                                address from,
                                address to,
                                uint256 amount
                            ) public virtual returns (bool) {
                                uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                balanceOf[from] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(from, to, amount);
                                return true;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     EIP-2612 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                // Unchecked because the only math done is incrementing
                                // the owner's nonce which cannot realistically overflow.
                                unchecked {
                                    address recoveredAddress = ecrecover(
                                        keccak256(
                                            abi.encodePacked(
                                                "\\x19\\x01",
                                                DOMAIN_SEPARATOR(),
                                                keccak256(
                                                    abi.encode(
                                                        keccak256(
                                                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                        ),
                                                        owner,
                                                        spender,
                                                        value,
                                                        nonces[owner]++,
                                                        deadline
                                                    )
                                                )
                                            )
                                        ),
                                        v,
                                        r,
                                        s
                                    );
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                    allowance[recoveredAddress][spender] = value;
                                }
                                emit Approval(owner, spender, value);
                            }
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                            }
                            function computeDomainSeparator() internal view virtual returns (bytes32) {
                                return
                                    keccak256(
                                        abi.encode(
                                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                            keccak256(bytes(name)),
                                            keccak256("1"),
                                            block.chainid,
                                            address(this)
                                        )
                                    );
                            }
                            /*//////////////////////////////////////////////////////////////
                                                INTERNAL MINT/BURN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function _mint(address to, uint256 amount) internal virtual {
                                totalSupply += amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(address(0), to, amount);
                            }
                            function _burn(address from, uint256 amount) internal virtual {
                                balanceOf[from] -= amount;
                                // Cannot underflow because a user's balance
                                // will never be larger than the total supply.
                                unchecked {
                                    totalSupply -= amount;
                                }
                                emit Transfer(from, address(0), amount);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
                        pragma solidity ^0.8.0;
                        import "./IAccessControl.sol";
                        import "../utils/Context.sol";
                        import "../utils/Strings.sol";
                        import "../utils/introspection/ERC165.sol";
                        /**
                         * @dev Contract module that allows children to implement role-based access
                         * control mechanisms. This is a lightweight version that doesn't allow enumerating role
                         * members except through off-chain means by accessing the contract event logs. Some
                         * applications may benefit from on-chain enumerability, for those cases see
                         * {AccessControlEnumerable}.
                         *
                         * Roles are referred to by their `bytes32` identifier. These should be exposed
                         * in the external API and be unique. The best way to achieve this is by
                         * using `public constant` hash digests:
                         *
                         * ```
                         * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                         * ```
                         *
                         * Roles can be used to represent a set of permissions. To restrict access to a
                         * function call, use {hasRole}:
                         *
                         * ```
                         * function foo() public {
                         *     require(hasRole(MY_ROLE, msg.sender));
                         *     ...
                         * }
                         * ```
                         *
                         * Roles can be granted and revoked dynamically via the {grantRole} and
                         * {revokeRole} functions. Each role has an associated admin role, and only
                         * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                         *
                         * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                         * that only accounts with this role will be able to grant or revoke other
                         * roles. More complex role relationships can be created by using
                         * {_setRoleAdmin}.
                         *
                         * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                         * grant and revoke this role. Extra precautions should be taken to secure
                         * accounts that have been granted it.
                         */
                        abstract contract AccessControl is Context, IAccessControl, ERC165 {
                            struct RoleData {
                                mapping(address => bool) members;
                                bytes32 adminRole;
                            }
                            mapping(bytes32 => RoleData) private _roles;
                            bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                            /**
                             * @dev Modifier that checks that an account has a specific role. Reverts
                             * with a standardized message including the required role.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             *
                             * _Available since v4.1._
                             */
                            modifier onlyRole(bytes32 role) {
                                _checkRole(role);
                                _;
                            }
                            /**
                             * @dev See {IERC165-supportsInterface}.
                             */
                            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                                return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
                            }
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                                return _roles[role].members[account];
                            }
                            /**
                             * @dev Revert with a standard message if `_msgSender()` is missing `role`.
                             * Overriding this function changes the behavior of the {onlyRole} modifier.
                             *
                             * Format of the revert message is described in {_checkRole}.
                             *
                             * _Available since v4.6._
                             */
                            function _checkRole(bytes32 role) internal view virtual {
                                _checkRole(role, _msgSender());
                            }
                            /**
                             * @dev Revert with a standard message if `account` is missing `role`.
                             *
                             * The format of the revert reason is given by the following regular expression:
                             *
                             *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                             */
                            function _checkRole(bytes32 role, address account) internal view virtual {
                                if (!hasRole(role, account)) {
                                    revert(
                                        string(
                                            abi.encodePacked(
                                                "AccessControl: account ",
                                                Strings.toHexString(account),
                                                " is missing role ",
                                                Strings.toHexString(uint256(role), 32)
                                            )
                                        )
                                    );
                                }
                            }
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                                return _roles[role].adminRole;
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been revoked `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function renounceRole(bytes32 role, address account) public virtual override {
                                require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event. Note that unlike {grantRole}, this function doesn't perform any
                             * checks on the calling account.
                             *
                             * May emit a {RoleGranted} event.
                             *
                             * [WARNING]
                             * ====
                             * This function should only be called from the constructor when setting
                             * up the initial roles for the system.
                             *
                             * Using this function in any other way is effectively circumventing the admin
                             * system imposed by {AccessControl}.
                             * ====
                             *
                             * NOTE: This function is deprecated in favor of {_grantRole}.
                             */
                            function _setupRole(bytes32 role, address account) internal virtual {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Sets `adminRole` as ``role``'s admin role.
                             *
                             * Emits a {RoleAdminChanged} event.
                             */
                            function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                bytes32 previousAdminRole = getRoleAdmin(role);
                                _roles[role].adminRole = adminRole;
                                emit RoleAdminChanged(role, previousAdminRole, adminRole);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleGranted} event.
                             */
                            function _grantRole(bytes32 role, address account) internal virtual {
                                if (!hasRole(role, account)) {
                                    _roles[role].members[account] = true;
                                    emit RoleGranted(role, account, _msgSender());
                                }
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * Internal function without access restriction.
                             *
                             * May emit a {RoleRevoked} event.
                             */
                            function _revokeRole(bytes32 role, address account) internal virtual {
                                if (hasRole(role, account)) {
                                    _roles[role].members[account] = false;
                                    emit RoleRevoked(role, account, _msgSender());
                                }
                            }
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev External interface of AccessControl declared to support ERC165 detection.
                         */
                        interface IAccessControl {
                            /**
                             * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                             *
                             * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                             * {RoleAdminChanged} not being emitted signaling this.
                             *
                             * _Available since v3.1._
                             */
                            event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                            /**
                             * @dev Emitted when `account` is granted `role`.
                             *
                             * `sender` is the account that originated the contract call, an admin role
                             * bearer except when using {AccessControl-_setupRole}.
                             */
                            event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Emitted when `account` is revoked `role`.
                             *
                             * `sender` is the account that originated the contract call:
                             *   - if using `revokeRole`, it is the admin role bearer
                             *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                             */
                            event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) external view returns (bool);
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {AccessControl-_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) external view returns (bytes32);
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function grantRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function revokeRole(bytes32 role, address account) external;
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been granted `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             */
                            function renounceRole(bytes32 role, address account) external;
                        }
                        // 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 (last updated v4.8.0) (utils/Strings.sol)
                        pragma solidity ^0.8.0;
                        import "./math/Math.sol";
                        /**
                         * @dev String operations.
                         */
                        library Strings {
                            bytes16 private constant _SYMBOLS = "0123456789abcdef";
                            uint8 private constant _ADDRESS_LENGTH = 20;
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                             */
                            function toString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    uint256 length = Math.log10(value) + 1;
                                    string memory buffer = new string(length);
                                    uint256 ptr;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        ptr := add(buffer, add(32, length))
                                    }
                                    while (true) {
                                        ptr--;
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                                        }
                                        value /= 10;
                                        if (value == 0) break;
                                    }
                                    return buffer;
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                             */
                            function toHexString(uint256 value) internal pure returns (string memory) {
                                unchecked {
                                    return toHexString(value, Math.log256(value) + 1);
                                }
                            }
                            /**
                             * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                             */
                            function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                                bytes memory buffer = new bytes(2 * length + 2);
                                buffer[0] = "0";
                                buffer[1] = "x";
                                for (uint256 i = 2 * length + 1; i > 1; --i) {
                                    buffer[i] = _SYMBOLS[value & 0xf];
                                    value >>= 4;
                                }
                                require(value == 0, "Strings: hex length insufficient");
                                return string(buffer);
                            }
                            /**
                             * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                             */
                            function toHexString(address addr) internal pure returns (string memory) {
                                return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                            }
                        }
                        // 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 (last updated v4.8.0) (utils/math/Math.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library Math {
                            enum Rounding {
                                Down, // Toward negative infinity
                                Up, // Toward infinity
                                Zero // Toward zero
                            }
                            /**
                             * @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 average of two numbers. The result is rounded towards
                             * zero.
                             */
                            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                // (a + b) / 2 can overflow.
                                return (a & b) + (a ^ b) / 2;
                            }
                            /**
                             * @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;
                            }
                            /**
                             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                             * with further edits by Uniswap Labs also under MIT license.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator
                            ) internal pure returns (uint256 result) {
                                unchecked {
                                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                    // variables such that product = prod1 * 2^256 + prod0.
                                    uint256 prod0; // Least significant 256 bits of the product
                                    uint256 prod1; // Most significant 256 bits of the product
                                    assembly {
                                        let mm := mulmod(x, y, not(0))
                                        prod0 := mul(x, y)
                                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                    }
                                    // Handle non-overflow cases, 256 by 256 division.
                                    if (prod1 == 0) {
                                        return prod0 / denominator;
                                    }
                                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                    require(denominator > prod1);
                                    ///////////////////////////////////////////////
                                    // 512 by 256 division.
                                    ///////////////////////////////////////////////
                                    // Make division exact by subtracting the remainder from [prod1 prod0].
                                    uint256 remainder;
                                    assembly {
                                        // Compute remainder using mulmod.
                                        remainder := mulmod(x, y, denominator)
                                        // Subtract 256 bit number from 512 bit number.
                                        prod1 := sub(prod1, gt(remainder, prod0))
                                        prod0 := sub(prod0, remainder)
                                    }
                                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                    // See https://cs.stackexchange.com/q/138556/92363.
                                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                                    uint256 twos = denominator & (~denominator + 1);
                                    assembly {
                                        // Divide denominator by twos.
                                        denominator := div(denominator, twos)
                                        // Divide [prod1 prod0] by twos.
                                        prod0 := div(prod0, twos)
                                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                        twos := add(div(sub(0, twos), twos), 1)
                                    }
                                    // Shift in bits from prod1 into prod0.
                                    prod0 |= prod1 * twos;
                                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                    // four bits. That is, denominator * inv = 1 mod 2^4.
                                    uint256 inverse = (3 * denominator) ^ 2;
                                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                    // in modular arithmetic, doubling the correct bits in each step.
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                    // is no longer required.
                                    result = prod0 * inverse;
                                    return result;
                                }
                            }
                            /**
                             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                             */
                            function mulDiv(
                                uint256 x,
                                uint256 y,
                                uint256 denominator,
                                Rounding rounding
                            ) internal pure returns (uint256) {
                                uint256 result = mulDiv(x, y, denominator);
                                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                    result += 1;
                                }
                                return result;
                            }
                            /**
                             * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                             *
                             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                             */
                            function sqrt(uint256 a) internal pure returns (uint256) {
                                if (a == 0) {
                                    return 0;
                                }
                                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                //
                                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                //
                                // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                //
                                // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                uint256 result = 1 << (log2(a) >> 1);
                                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                // into the expected uint128 result.
                                unchecked {
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    result = (result + a / result) >> 1;
                                    return min(result, a / result);
                                }
                            }
                            /**
                             * @notice Calculates sqrt(a), following the selected rounding direction.
                             */
                            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = sqrt(a);
                                    return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 2, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 128;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 64;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 32;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 16;
                                    }
                                    if (value >> 8 > 0) {
                                        value >>= 8;
                                        result += 8;
                                    }
                                    if (value >> 4 > 0) {
                                        value >>= 4;
                                        result += 4;
                                    }
                                    if (value >> 2 > 0) {
                                        value >>= 2;
                                        result += 2;
                                    }
                                    if (value >> 1 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log2(value);
                                    return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 10, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >= 10**64) {
                                        value /= 10**64;
                                        result += 64;
                                    }
                                    if (value >= 10**32) {
                                        value /= 10**32;
                                        result += 32;
                                    }
                                    if (value >= 10**16) {
                                        value /= 10**16;
                                        result += 16;
                                    }
                                    if (value >= 10**8) {
                                        value /= 10**8;
                                        result += 8;
                                    }
                                    if (value >= 10**4) {
                                        value /= 10**4;
                                        result += 4;
                                    }
                                    if (value >= 10**2) {
                                        value /= 10**2;
                                        result += 2;
                                    }
                                    if (value >= 10**1) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log10(value);
                                    return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                                }
                            }
                            /**
                             * @dev Return the log in base 256, rounded down, of a positive value.
                             * Returns 0 if given 0.
                             *
                             * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                             */
                            function log256(uint256 value) internal pure returns (uint256) {
                                uint256 result = 0;
                                unchecked {
                                    if (value >> 128 > 0) {
                                        value >>= 128;
                                        result += 16;
                                    }
                                    if (value >> 64 > 0) {
                                        value >>= 64;
                                        result += 8;
                                    }
                                    if (value >> 32 > 0) {
                                        value >>= 32;
                                        result += 4;
                                    }
                                    if (value >> 16 > 0) {
                                        value >>= 16;
                                        result += 2;
                                    }
                                    if (value >> 8 > 0) {
                                        result += 1;
                                    }
                                }
                                return result;
                            }
                            /**
                             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                             * Returns 0 if given 0.
                             */
                            function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                unchecked {
                                    uint256 result = log256(value);
                                    return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                                }
                            }
                        }
                        // 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);
                        }
                        

                        File 9 of 18: Vault
                        // SPDX-License-Identifier: GPL-3.0-or-later
                        pragma solidity 0.8.24;
                        import { Pausable } from "openzeppelin-contracts/utils/Pausable.sol";
                        import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                        import { ReentrancyGuard } from "solady/utils/ReentrancyGuard.sol";
                        import { IMinter } from "warlord/interfaces/IMinter.sol";
                        import { IStaker } from "warlord/interfaces/IStaker.sol";
                        import { ERC4626 } from "solady/tokens/ERC4626.sol";
                        import { ERC20 } from "solmate/tokens/ERC20.sol";
                        import { ISwapper } from "./interfaces/ISwapper.sol";
                        import { AOperator } from "./abstracts/AOperator.sol";
                        import { AFees } from "./abstracts/AFees.sol";
                        import { Errors } from "./utils/Errors.sol";
                        import { Allowance } from "../utils/Allowance.sol";
                        import { Owned2Step } from "../utils/Owned2Step.sol";
                        /// @author 0xtekgrinder
                        /// @title Vault contract
                        /// @notice Auto compounding vault for the warlord protocol with token to deposit being WAR and asset() being stkWAR
                        contract Vault is ERC4626, Pausable, ReentrancyGuard, AFees, AOperator {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Event emitted when a staker is updated
                             */
                            event StakerUpdated(address oldStaker, address newStaker);
                            /**
                             * @notice Event emitted when a minter is updated
                             */
                            event MinterUpdated(address oldMinter, address newMinter);
                            /**
                             * @notice Event emitted when a swapper is updated
                             */
                            event SwapperUpdated(address oldSwapper, address newSwapper);
                            /**
                             * @notice Event emitted when reward have been harvested
                             */
                            event Harvested(uint256 amount);
                            /**
                             * @notice Event emitted when rewards are compounded into more stkWAR
                             */
                            event Compounded(uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                  CONSTANTS VARIABLES
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Address of the definitive asset()
                             */
                            address private immutable _asset;
                            /**
                             * @notice Name of the vault
                             */
                            string private constant _NAME = "Tholgar Warlord Vault";
                            /**
                             * @notice Symbol of the vault
                             */
                            string private constant _SYMBOL = "thWAR";
                            /*//////////////////////////////////////////////////////////////
                                                  MUTABLE VARIABLES
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Address of the stkWAR token
                             */
                            address public staker;
                            /**
                             *  @notice Address of the WAR minter contract
                             */
                            address public minter;
                            /**
                             * @notice Address of the swapper contract
                             */
                            address public swapper;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                address initialOwner,
                                address initialStaker,
                                address initialMinter,
                                address initialSwapper,
                                uint256 initialHarvestFee,
                                uint256 initialWithdrawalFee,
                                address initialFeeRecipient,
                                address initialFeeToken,
                                address initialOperator,
                                address definitiveAsset
                            )
                                Owned2Step(initialOwner)
                                AFees(initialHarvestFee, initialWithdrawalFee, initialFeeRecipient, initialFeeToken)
                                AOperator(initialOperator)
                            {
                                if (initialStaker == address(0) || initialMinter == address(0) || initialSwapper == address(0)) {
                                    revert Errors.ZeroAddress();
                                }
                                staker = initialStaker;
                                minter = initialMinter;
                                swapper = initialSwapper;
                                _asset = definitiveAsset;
                                SafeTransferLib.safeApprove(definitiveAsset, initialStaker, type(uint256).max);
                            }
                            /*//////////////////////////////////////////////////////////////
                                                    ADMIN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice update the staker contract to a new one
                             * @param newStaker the new staker contract
                             * @custom:requires owner
                             */
                            function setStaker(address newStaker) external onlyOwner {
                                if (newStaker == address(0)) revert Errors.ZeroAddress();
                                address oldStaker = staker;
                                staker = newStaker;
                                emit StakerUpdated(oldStaker, newStaker);
                                // Unstake all wars from old staker
                                uint256 stakerBalance = ERC20(oldStaker).balanceOf(address(this));
                                if (stakerBalance != 0) {
                                    IStaker(oldStaker).unstake(stakerBalance, address(this));
                                }
                                // revoke allowance from old staker
                                SafeTransferLib.safeApprove(asset(), oldStaker, 0);
                                // approve all war tokens to be spent by new staker
                                SafeTransferLib.safeApprove(asset(), newStaker, type(uint256).max);
                                // Restake all tokens
                                uint256 warBalance = ERC20(asset()).balanceOf(address(this));
                                if (warBalance != 0) {
                                    IStaker(newStaker).stake(warBalance, address(this));
                                }
                            }
                            /**
                             * @notice update the swapper contract to a new one
                             * @param newSwapper the new swapper contract
                             * @custom:requires owner
                             */
                            function setSwapper(address newSwapper) external onlyOwner {
                                if (newSwapper == address(0)) revert Errors.ZeroAddress();
                                address oldSwapper = swapper;
                                swapper = newSwapper;
                                emit SwapperUpdated(oldSwapper, newSwapper);
                            }
                            /**
                             * @notice update the minter contract to a new one
                             * @param newMinter the new minter contract
                             * @custom:requires owner
                             */
                            function setMinter(address newMinter) external onlyOwner {
                                if (newMinter == address(0)) revert Errors.ZeroAddress();
                                address oldMinter = minter;
                                minter = newMinter;
                                emit MinterUpdated(oldMinter, newMinter);
                            }
                            /**
                             * @notice Recover ERC2O tokens in the contract
                             * @dev Recover ERC2O tokens in the contract
                             * @param token Address of the ERC2O token
                             * @return bool: success
                             * @custom:requires owner
                             */
                            function recoverERC20(address token) external onlyOwner returns (bool) {
                                if (token == address(0)) revert Errors.ZeroAddress();
                                uint256 amount = ERC20(token).balanceOf(address(this));
                                if (amount == 0) revert Errors.ZeroValue();
                                SafeTransferLib.safeTransfer(token, owner, amount);
                                return true;
                            }
                            /**
                             * @notice Pause the contract
                             */
                            function pause() external onlyOwner {
                                _pause();
                            }
                            /**
                             * @notice Unpause the contract
                             */
                            function unpause() external onlyOwner {
                                _unpause();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                    ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @dev Returns the name of the token
                             */
                            function name() public view override returns (string memory) {
                                return _NAME;
                            }
                            /**
                             * @dev Returns the symbol of the token
                             */
                            function symbol() public view override returns (string memory) {
                                return _SYMBOL;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                    ERC4626 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @dev previewRedeem returns the amount of assets that will be redeemed minus the withdrawal fees
                             */
                            function previewRedeem(uint256 shares) public view override returns (uint256 assets) {
                                return super.previewRedeem(shares) * (MAX_BPS - withdrawalFee) / MAX_BPS;
                            }
                            /**
                             * @dev asset is the definitive asset of the vault (WAR)
                             */
                            function asset() public view override returns (address) {
                                return _asset;
                            }
                            /**
                             * @dev totalAssets is the total number of stkWAR
                             */
                            function totalAssets() public view override returns (uint256) {
                                uint256 assets = ERC20(staker).balanceOf(address(this));
                                return assets;
                            }
                            /**
                             * @custom:notpaused when not paused
                             */
                            function deposit(uint256 assets, address receiver) public override whenNotPaused returns (uint256 shares) {
                                return super.deposit(assets, receiver);
                            }
                            /**
                             * @custom:notpaused when not paused
                             */
                            function mint(uint256 shares, address receiver) public override whenNotPaused returns (uint256 assets) {
                                return super.mint(shares, receiver);
                            }
                            /**
                             * @custom:notpaused when not paused
                             */
                            function withdraw(uint256 assets, address to, address owner)
                                public
                                override
                                whenNotPaused
                                returns (uint256 shares)
                            {
                                if (assets > maxWithdraw(owner)) revert WithdrawMoreThanMax();
                                shares = previewWithdraw(assets);
                                _withdraw(msg.sender, to, owner, assets * (MAX_BPS - withdrawalFee) / MAX_BPS, shares);
                            }
                            /**
                             * @custom:notpaused when not paused
                             */
                            function redeem(uint256 shares, address to, address owner)
                                public
                                override
                                whenNotPaused
                                returns (uint256 assets)
                            {
                                return super.redeem(shares, to, owner);
                            }
                            /**
                             * @dev stake assets after each deposit
                             */
                            function _afterDeposit(uint256 assets, uint256 /* shares */ ) internal override {
                                IStaker(staker).stake(assets, address(this));
                            }
                            /**
                             * @dev unstake assets before each withdraw to have enough WAR to transfer
                             */
                            function _beforeWithdraw(uint256 assets, uint256 /*shares */ ) internal override {
                                IStaker(staker).unstake(assets, address(this));
                            }
                            /*//////////////////////////////////////////////////////////////
                                                    HARVEST LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Harvest all rewards from staker
                             * @dev calldatas should swap from all reward tokens to feeToken
                             * @param tokensToHarvest tokens to harvest
                             * @param tokensToSwap tokens to swap to feeToken
                             * @param callDatas swapper routes to swap to feeToken
                             * @custom:requires operator or owner
                             */
                            function harvest(address[] calldata tokensToHarvest, address[] calldata tokensToSwap, bytes[] calldata callDatas)
                                external
                                nonReentrant
                                onlyOperatorOrOwner
                            {
                                address _swapper = swapper;
                                address _feeToken = feeToken;
                                uint256 oldFeeBalance = ERC20(_feeToken).balanceOf(address(this));
                                // claim all harvastable rewards and send them to the swapper
                                uint256 length = tokensToHarvest.length;
                                for (uint256 i; i < length;) {
                                    address tokenToHarvest = tokensToHarvest[i];
                                    address recipient;
                                    if (tokenToHarvest == asset() || tokenToHarvest == address(_feeToken)) {
                                        recipient = address(this);
                                    } else {
                                        recipient = _swapper;
                                    }
                                    IStaker(staker).claimRewards(tokenToHarvest, recipient);
                                    unchecked {
                                        ++i;
                                    }
                                }
                                // swap to harvested tokens to feeToken
                                ISwapper(_swapper).swap(tokensToSwap, callDatas);
                                // transfer havestfee %oo to fee recipient
                                uint256 harvestedAmount = ERC20(_feeToken).balanceOf(address(this)) - oldFeeBalance;
                                SafeTransferLib.safeTransfer(_feeToken, feeRecipient, (harvestedAmount * harvestFee) / MAX_BPS);
                                emit Harvested(harvestedAmount);
                            }
                            /**
                             * @notice Turn all rewards into more staked assets
                             * @param callDatas swapper routes to swap to more assets
                             * @param tokensToMint tokens to mint more stkWAR
                             * @param tokensToSwap tokens which includes the feeToken to swap to more assets
                             * @custom:requires operator or owner
                             */
                            function compound(address[] calldata tokensToSwap, bytes[] calldata callDatas, address[] calldata tokensToMint)
                                external
                                nonReentrant
                                onlyOperatorOrOwner
                            {
                                address _feeToken = feeToken;
                                // swap feeToken to WeightedTokens with correct ratios
                                SafeTransferLib.safeTransfer(_feeToken, swapper, ERC20(_feeToken).balanceOf(address(this)));
                                ISwapper(swapper).swap(tokensToSwap, callDatas);
                                // Mint more stkWAR if there are tokens to mint
                                uint256 length = tokensToMint.length;
                                if (length != 0) {
                                    uint256[] memory amounts = new uint256[](length);
                                    for (uint256 i; i < length;) {
                                        address token = tokensToMint[i];
                                        amounts[i] = ERC20(token).balanceOf(address(this));
                                        Allowance._approveTokenIfNeeded(token, minter);
                                        unchecked {
                                            ++i;
                                        }
                                    }
                                    IMinter(minter).mintMultiple(tokensToMint, amounts);
                                }
                                uint256 stakedAmount = IStaker(staker).stake(ERC20(asset()).balanceOf(address(this)), address(this));
                                emit Compounded(stakedAmount);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
                        pragma solidity ^0.8.20;
                        import {Context} from "../utils/Context.sol";
                        /**
                         * @dev Contract module which allows children to implement an emergency stop
                         * mechanism that can be triggered by an authorized account.
                         *
                         * This module is used through inheritance. It will make available the
                         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                         * the functions of your contract. Note that they will not be pausable by
                         * simply including this module, only once the modifiers are put in place.
                         */
                        abstract contract Pausable is Context {
                            bool private _paused;
                            /**
                             * @dev Emitted when the pause is triggered by `account`.
                             */
                            event Paused(address account);
                            /**
                             * @dev Emitted when the pause is lifted by `account`.
                             */
                            event Unpaused(address account);
                            /**
                             * @dev The operation failed because the contract is paused.
                             */
                            error EnforcedPause();
                            /**
                             * @dev The operation failed because the contract is not paused.
                             */
                            error ExpectedPause();
                            /**
                             * @dev Initializes the contract in unpaused state.
                             */
                            constructor() {
                                _paused = false;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is not paused.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            modifier whenNotPaused() {
                                _requireNotPaused();
                                _;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is paused.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            modifier whenPaused() {
                                _requirePaused();
                                _;
                            }
                            /**
                             * @dev Returns true if the contract is paused, and false otherwise.
                             */
                            function paused() public view virtual returns (bool) {
                                return _paused;
                            }
                            /**
                             * @dev Throws if the contract is paused.
                             */
                            function _requireNotPaused() internal view virtual {
                                if (paused()) {
                                    revert EnforcedPause();
                                }
                            }
                            /**
                             * @dev Throws if the contract is not paused.
                             */
                            function _requirePaused() internal view virtual {
                                if (!paused()) {
                                    revert ExpectedPause();
                                }
                            }
                            /**
                             * @dev Triggers stopped state.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            function _pause() internal virtual whenNotPaused {
                                _paused = true;
                                emit Paused(_msgSender());
                            }
                            /**
                             * @dev Returns to normal state.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            function _unpause() internal virtual whenPaused {
                                _paused = false;
                                emit Unpaused(_msgSender());
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                        /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
                        ///
                        /// @dev Note:
                        /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
                        /// - For ERC20s, this implementation won't check that a token has code,
                        ///   responsibility is delegated to the caller.
                        library SafeTransferLib {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The ETH transfer has failed.
                            error ETHTransferFailed();
                            /// @dev The ERC20 `transferFrom` has failed.
                            error TransferFromFailed();
                            /// @dev The ERC20 `transfer` has failed.
                            error TransferFailed();
                            /// @dev The ERC20 `approve` has failed.
                            error ApproveFailed();
                            /// @dev The Permit2 operation has failed.
                            error Permit2Failed();
                            /// @dev The Permit2 amount must be less than `2**160 - 1`.
                            error Permit2AmountOverflow();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
                            uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
                            /// @dev Suggested gas stipend for contract receiving ETH to perform a few
                            /// storage reads and writes, but low enough to prevent griefing.
                            uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
                            /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
                            bytes32 internal constant DAI_DOMAIN_SEPARATOR =
                                0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
                            /// @dev The address for the WETH9 contract on Ethereum mainnet.
                            address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                            /// @dev The canonical Permit2 address.
                            /// [Github](https://github.com/Uniswap/permit2)
                            /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
                            address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       ETH OPERATIONS                       */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
                            //
                            // The regular variants:
                            // - Forwards all remaining gas to the target.
                            // - Reverts if the target reverts.
                            // - Reverts if the current contract has insufficient balance.
                            //
                            // The force variants:
                            // - Forwards with an optional gas stipend
                            //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
                            // - If the target reverts, or if the gas stipend is exhausted,
                            //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
                            //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
                            // - Reverts if the current contract has insufficient balance.
                            //
                            // The try variants:
                            // - Forwards with a mandatory gas stipend.
                            // - Instead of reverting, returns whether the transfer succeeded.
                            /// @dev Sends `amount` (in wei) ETH to `to`.
                            function safeTransferETH(address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                            /// @dev Sends all the ETH in the current contract to `to`.
                            function safeTransferAllETH(address to) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Transfer all the ETH and check if it succeeded or not.
                                    if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                            /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                            function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if lt(selfbalance(), amount) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
                            function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
                            function forceSafeTransferETH(address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if lt(selfbalance(), amount) {
                                        mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
                            function forceSafeTransferAllETH(address to) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // forgefmt: disable-next-item
                                    if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                        mstore(0x00, to) // Store the address in scratch space.
                                        mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                        mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                        if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                    }
                                }
                            }
                            /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                            function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
                                }
                            }
                            /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
                            function trySafeTransferAllETH(address to, uint256 gasStipend)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      ERC20 OPERATIONS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have at least `amount` approved for
                            /// the current contract to manage.
                            function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x60, amount) // Store the `amount` argument.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            ///
                            /// The `from` account must have at least `amount` approved for the current contract to manage.
                            function trySafeTransferFrom(address token, address from, address to, uint256 amount)
                                internal
                                returns (bool success)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x60, amount) // Store the `amount` argument.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                    success :=
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends all of ERC20 `token` from `from` to `to`.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have their entire balance approved for the current contract to manage.
                            function safeTransferAllFrom(address token, address from, address to)
                                internal
                                returns (uint256 amount)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Cache the free memory pointer.
                                    mstore(0x40, to) // Store the `to` argument.
                                    mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                    mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                    // Read the balance, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                                    amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x60, 0) // Restore the zero slot to zero.
                                    mstore(0x40, m) // Restore the free memory pointer.
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
                            /// Reverts upon failure.
                            function safeTransfer(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sends all of ERC20 `token` from the current contract to `to`.
                            /// Reverts upon failure.
                            function safeTransferAll(address token, address to) internal returns (uint256 amount) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                                    mstore(0x20, address()) // Store the address of the current contract.
                                    // Read the balance, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x14, to) // Store the `to` argument.
                                    amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                                    mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                    // Perform the transfer, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                            /// Reverts upon failure.
                            function safeApprove(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                    // Perform the approval, reverting upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                            /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                            /// then retries the approval again (some tokens, e.g. USDT, requires this).
                            /// Reverts upon failure.
                            function safeApproveWithRetry(address token, address to, uint256 amount) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, to) // Store the `to` argument.
                                    mstore(0x34, amount) // Store the `amount` argument.
                                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                    // Perform the approval, retrying upon failure.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        )
                                    ) {
                                        mstore(0x34, 0) // Store 0 for the `amount`.
                                        mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                        pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                                        mstore(0x34, amount) // Store back the original `amount`.
                                        // Retry the approval, reverting upon failure.
                                        if iszero(
                                            and(
                                                or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                                                call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                            )
                                        ) {
                                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                    mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                                }
                            }
                            /// @dev Returns the amount of ERC20 `token` owned by `account`.
                            /// Returns zero if the `token` does not exist.
                            function balanceOf(address token, address account) internal view returns (uint256 amount) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x14, account) // Store the `account` argument.
                                    mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                    amount :=
                                        mul( // The arguments of `mul` are evaluated from right to left.
                                            mload(0x20),
                                            and( // The arguments of `and` are evaluated from right to left.
                                                gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                                staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                            )
                                        )
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                            /// If the initial attempt fails, try to use Permit2 to transfer the token.
                            /// Reverts upon failure.
                            ///
                            /// The `from` account must have at least `amount` approved for the current contract to manage.
                            function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
                                if (!trySafeTransferFrom(token, from, to, amount)) {
                                    permit2TransferFrom(token, from, to, amount);
                                }
                            }
                            /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
                            /// Reverts upon failure.
                            function permit2TransferFrom(address token, address from, address to, uint256 amount)
                                internal
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40)
                                    mstore(add(m, 0x74), shr(96, shl(96, token)))
                                    mstore(add(m, 0x54), amount)
                                    mstore(add(m, 0x34), to)
                                    mstore(add(m, 0x20), shl(96, from))
                                    // `transferFrom(address,address,uint160,address)`.
                                    mstore(m, 0x36c78516000000000000000000000000)
                                    let p := mul(PERMIT2, iszero(shr(160, amount)))
                                    if iszero(mul(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), extcodesize(p)))
                                    {
                                        mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                                        revert(add(0x18, shl(2, iszero(p))), 0x04)
                                    }
                                }
                            }
                            /// @dev Permit a user to spend a given amount of
                            /// another user's tokens via native EIP-2612 permit if possible, falling
                            /// back to Permit2 if native permit fails or is not implemented on the token.
                            function permit2(
                                address token,
                                address owner,
                                address spender,
                                uint256 amount,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                bool success;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for {} shl(96, xor(token, WETH9)) {} {
                                        mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                                        if iszero(
                                            and( // The arguments of `and` are evaluated from right to left.
                                                lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                                                // Gas stipend to limit gas burn for tokens that don't refund gas when
                                                // an non-existing function is called. 5K should be enough for a SLOAD.
                                                staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                                            )
                                        ) { break }
                                        let m := mload(0x40)
                                        mstore(add(m, 0x34), spender)
                                        mstore(add(m, 0x20), shl(96, owner))
                                        mstore(add(m, 0x74), deadline)
                                        if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                                            mstore(0x14, owner)
                                            mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                                            mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                                            mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                                            // `nonces` is already at `add(m, 0x54)`.
                                            // `1` is already stored at `add(m, 0x94)`.
                                            mstore(add(m, 0xb4), and(0xff, v))
                                            mstore(add(m, 0xd4), r)
                                            mstore(add(m, 0xf4), s)
                                            success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                                            break
                                        }
                                        mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                                        mstore(add(m, 0x54), amount)
                                        mstore(add(m, 0x94), and(0xff, v))
                                        mstore(add(m, 0xb4), r)
                                        mstore(add(m, 0xd4), s)
                                        success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                                        break
                                    }
                                }
                                if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
                            }
                            /// @dev Simple permit on the Permit2 contract.
                            function simplePermit2(
                                address token,
                                address owner,
                                address spender,
                                uint256 amount,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40)
                                    mstore(m, 0x927da105) // `allowance(address,address,address)`.
                                    {
                                        let addressMask := shr(96, not(0))
                                        mstore(add(m, 0x20), and(addressMask, owner))
                                        mstore(add(m, 0x40), and(addressMask, token))
                                        mstore(add(m, 0x60), and(addressMask, spender))
                                        mstore(add(m, 0xc0), and(addressMask, spender))
                                    }
                                    let p := mul(PERMIT2, iszero(shr(160, amount)))
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                                            staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                                        )
                                    ) {
                                        mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                                        revert(add(0x18, shl(2, iszero(p))), 0x04)
                                    }
                                    mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                                    // `owner` is already `add(m, 0x20)`.
                                    // `token` is already at `add(m, 0x40)`.
                                    mstore(add(m, 0x60), amount)
                                    mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                                    // `nonce` is already at `add(m, 0xa0)`.
                                    // `spender` is already at `add(m, 0xc0)`.
                                    mstore(add(m, 0xe0), deadline)
                                    mstore(add(m, 0x100), 0x100) // `signature` offset.
                                    mstore(add(m, 0x120), 0x41) // `signature` length.
                                    mstore(add(m, 0x140), r)
                                    mstore(add(m, 0x160), s)
                                    mstore(add(m, 0x180), shl(248, v))
                                    if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
                                        mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Reentrancy guard mixin.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
                        abstract contract ReentrancyGuard {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Unauthorized reentrant call.
                            error Reentrancy();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                          STORAGE                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
                            /// 9 bytes is large enough to avoid collisions with lower slots,
                            /// but not too large to result in excessive bytecode bloat.
                            uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      REENTRANCY GUARD                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Guards a function from reentrancy.
                            modifier nonReentrant() virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                                        mstore(0x00, 0xab143c06) // `Reentrancy()`.
                                        revert(0x1c, 0x04)
                                    }
                                    sstore(_REENTRANCY_GUARD_SLOT, address())
                                }
                                _;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    sstore(_REENTRANCY_GUARD_SLOT, codesize())
                                }
                            }
                            /// @dev Guards a view function from read-only reentrancy.
                            modifier nonReadReentrant() virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                                        mstore(0x00, 0xab143c06) // `Reentrancy()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                _;
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity ^0.8.0;
                        interface IMinter {
                          function mint(address vlToken, uint256 amount) external;
                          function mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts) external;
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity ^0.8.0;
                        interface IStaker {
                          struct UserClaimedRewards {
                            address reward;
                            uint256 amount;
                          }
                          struct UserClaimableRewards {
                            address reward;
                            uint256 claimableAmount;
                          }
                          function queueRewards(address rewardToken, uint256 amount) external returns (bool);
                          function stake(uint256 amount, address receiver) external returns (uint256);
                          function unstake(uint256 amount, address receiver) external returns (uint256);
                          function claimRewards(address reward, address receiver) external returns (uint256);
                          function claimAllRewards(address receiver) external returns (UserClaimedRewards[] memory);
                          function getUserTotalClaimableRewards(address user) external view returns (UserClaimableRewards[] memory);
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        import {ERC20} from "./ERC20.sol";
                        import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";
                        import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
                        /// @notice Simple ERC4626 tokenized Vault implementation.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC4626.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol)
                        abstract contract ERC4626 is ERC20 {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The default underlying decimals.
                            uint8 internal constant _DEFAULT_UNDERLYING_DECIMALS = 18;
                            /// @dev The default decimals offset.
                            uint8 internal constant _DEFAULT_DECIMALS_OFFSET = 0;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Cannot deposit more than the max limit.
                            error DepositMoreThanMax();
                            /// @dev Cannot mint more than the max limit.
                            error MintMoreThanMax();
                            /// @dev Cannot withdraw more than the max limit.
                            error WithdrawMoreThanMax();
                            /// @dev Cannot redeem more than the max limit.
                            error RedeemMoreThanMax();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           EVENTS                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Emitted during a mint call or deposit call.
                            event Deposit(address indexed by, address indexed owner, uint256 assets, uint256 shares);
                            /// @dev Emitted during a withdraw call or redeem call.
                            event Withdraw(
                                address indexed by,
                                address indexed to,
                                address indexed owner,
                                uint256 assets,
                                uint256 shares
                            );
                            /// @dev `keccak256(bytes("Deposit(address,address,uint256,uint256)"))`.
                            uint256 private constant _DEPOSIT_EVENT_SIGNATURE =
                                0xdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7;
                            /// @dev `keccak256(bytes("Withdraw(address,address,address,uint256,uint256)"))`.
                            uint256 private constant _WITHDRAW_EVENT_SIGNATURE =
                                0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     ERC4626 CONSTANTS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev To be overridden to return the address of the underlying asset.
                            ///
                            /// - MUST be an ERC20 token contract.
                            /// - MUST NOT revert.
                            function asset() public view virtual returns (address);
                            /// @dev To be overridden to return the number of decimals of the underlying asset.
                            /// Default: 18.
                            ///
                            /// - MUST NOT revert.
                            function _underlyingDecimals() internal view virtual returns (uint8) {
                                return _DEFAULT_UNDERLYING_DECIMALS;
                            }
                            /// @dev Override to return a non-zero value to make the inflation attack even more unfeasible.
                            /// Only used when {_useVirtualShares} returns true.
                            /// Default: 0.
                            ///
                            /// - MUST NOT revert.
                            function _decimalsOffset() internal view virtual returns (uint8) {
                                return _DEFAULT_DECIMALS_OFFSET;
                            }
                            /// @dev Returns whether virtual shares will be used to mitigate the inflation attack.
                            /// See: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/3706
                            /// Override to return true or false.
                            /// Default: true.
                            ///
                            /// - MUST NOT revert.
                            function _useVirtualShares() internal view virtual returns (bool) {
                                return true;
                            }
                            /// @dev Returns the decimals places of the token.
                            ///
                            /// - MUST NOT revert.
                            function decimals() public view virtual override(ERC20) returns (uint8) {
                                if (!_useVirtualShares()) return _underlyingDecimals();
                                return _underlyingDecimals() + _decimalsOffset();
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                ASSET DECIMALS GETTER HELPER                */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Helper function to get the decimals of the underlying asset.
                            /// Useful for setting the return value of `_underlyingDecimals` during initialization.
                            /// If the retrieval succeeds, `success` will be true, and `result` will hold the result.
                            /// Otherwise, `success` will be false, and `result` will be zero.
                            ///
                            /// Example usage:
                            /// ```
                            /// (bool success, uint8 result) = _tryGetAssetDecimals(underlying);
                            /// _decimals = success ? result : _DEFAULT_UNDERLYING_DECIMALS;
                            /// ```
                            function _tryGetAssetDecimals(address underlying)
                                internal
                                view
                                returns (bool success, uint8 result)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Store the function selector of `decimals()`.
                                    mstore(0x00, 0x313ce567)
                                    // Arguments are evaluated last to first.
                                    success :=
                                        and(
                                            // Returned value is less than 256, at left-padded to 32 bytes.
                                            and(lt(mload(0x00), 0x100), gt(returndatasize(), 0x1f)),
                                            // The staticcall succeeds.
                                            staticcall(gas(), underlying, 0x1c, 0x04, 0x00, 0x20)
                                        )
                                    result := mul(mload(0x00), success)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      ACCOUNTING LOGIC                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the total amount of the underlying asset managed by the Vault.
                            ///
                            /// - SHOULD include any compounding that occurs from the yield.
                            /// - MUST be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT revert.
                            function totalAssets() public view virtual returns (uint256 assets) {
                                assets = SafeTransferLib.balanceOf(asset(), address(this));
                            }
                            /// @dev Returns the amount of shares that the Vault will exchange for the amount of
                            /// assets provided, in an ideal scenario where all conditions are met.
                            ///
                            /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT show any variations depending on the caller.
                            /// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
                            /// - MUST NOT revert.
                            ///
                            /// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
                            /// should reflect the "average-user's" price-per-share, i.e. what the average user should
                            /// expect to see when exchanging to and from.
                            function convertToShares(uint256 assets) public view virtual returns (uint256 shares) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return _eitherIsZero(assets, supply)
                                        ? _initialConvertToShares(assets)
                                        : FixedPointMathLib.fullMulDiv(assets, supply, totalAssets());
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 1, _inc(totalAssets()));
                                }
                                return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
                            }
                            /// @dev Returns the amount of assets that the Vault will exchange for the amount of
                            /// shares provided, in an ideal scenario where all conditions are met.
                            ///
                            /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                            /// - MUST NOT show any variations depending on the caller.
                            /// - MUST NOT reflect slippage or other on-chain conditions, during the actual exchange.
                            /// - MUST NOT revert.
                            ///
                            /// Note: This calculation MAY NOT reflect the "per-user" price-per-share, and instead
                            /// should reflect the "average-user's" price-per-share, i.e. what the average user should
                            /// expect to see when exchanging to and from.
                            function convertToAssets(uint256 shares) public view virtual returns (uint256 assets) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return supply == 0
                                        ? _initialConvertToAssets(shares)
                                        : FixedPointMathLib.fullMulDiv(shares, totalAssets(), supply);
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, _inc(totalSupply()));
                                }
                                return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, totalSupply() + 10 ** o);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their deposit
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no more than the exact amount of Vault shares that
                            ///   will be minted in a deposit call in the same transaction, i.e. deposit should
                            ///   return the same or more shares as `previewDeposit` if call in the same transaction.
                            /// - MUST NOT account for deposit limits like those returned from `maxDeposit` and should
                            ///   always act as if the deposit will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of deposit fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToShares` and `previewDeposit` SHOULD
                            /// be considered slippage in share price or some other type of condition, meaning
                            /// the depositor will lose assets by depositing.
                            function previewDeposit(uint256 assets) public view virtual returns (uint256 shares) {
                                shares = convertToShares(assets);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their mint
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no fewer than the exact amount of assets that
                            ///   will be deposited in a mint call in the same transaction, i.e. mint should
                            ///   return the same or fewer assets as `previewMint` if called in the same transaction.
                            /// - MUST NOT account for mint limits like those returned from `maxMint` and should
                            ///   always act as if the mint will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of deposit fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToAssets` and `previewMint` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by minting.
                            function previewMint(uint256 shares) public view virtual returns (uint256 assets) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return supply == 0
                                        ? _initialConvertToAssets(shares)
                                        : FixedPointMathLib.fullMulDivUp(shares, totalAssets(), supply);
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, _inc(totalSupply()));
                                }
                                return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, totalSupply() + 10 ** o);
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal
                            /// at the current block, given the current on-chain conditions.
                            ///
                            /// - MUST return as close to and no fewer than the exact amount of Vault shares that
                            ///   will be burned in a withdraw call in the same transaction, i.e. withdraw should
                            ///   return the same or fewer shares as `previewWithdraw` if call in the same transaction.
                            /// - MUST NOT account for withdrawal limits like those returned from `maxWithdraw` and should
                            ///   always act as if the withdrawal will be accepted, regardless of share balance, etc.
                            /// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
                            /// - MUST not revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToShares` and `previewWithdraw` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by depositing.
                            function previewWithdraw(uint256 assets) public view virtual returns (uint256 shares) {
                                if (!_useVirtualShares()) {
                                    uint256 supply = totalSupply();
                                    return _eitherIsZero(assets, supply)
                                        ? _initialConvertToShares(assets)
                                        : FixedPointMathLib.fullMulDivUp(assets, supply, totalAssets());
                                }
                                uint256 o = _decimalsOffset();
                                if (o == 0) {
                                    return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 1, _inc(totalAssets()));
                                }
                                return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
                            }
                            /// @dev Allows an on-chain or off-chain user to simulate the effects of their redemption
                            /// at the current block, given current on-chain conditions.
                            ///
                            /// - MUST return as close to and no more than the exact amount of assets that
                            ///   will be withdrawn in a redeem call in the same transaction, i.e. redeem should
                            ///   return the same or more assets as `previewRedeem` if called in the same transaction.
                            /// - MUST NOT account for redemption limits like those returned from `maxRedeem` and should
                            ///   always act as if the redemption will be accepted, regardless of approvals, etc.
                            /// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
                            /// - MUST NOT revert.
                            ///
                            /// Note: Any unfavorable discrepancy between `convertToAssets` and `previewRedeem` SHOULD
                            /// be considered slippage in share price or some other type of condition,
                            /// meaning the depositor will lose assets by depositing.
                            function previewRedeem(uint256 shares) public view virtual returns (uint256 assets) {
                                assets = convertToAssets(shares);
                            }
                            /// @dev Private helper to return if either value is zero.
                            function _eitherIsZero(uint256 a, uint256 b) private pure returns (bool result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    result := or(iszero(a), iszero(b))
                                }
                            }
                            /// @dev Private helper to return `x + 1` without the overflow check.
                            /// Used for computing the denominator input to `FixedPointMathLib.fullMulDiv(a, b, x + 1)`.
                            /// When `x == type(uint256).max`, we get `x + 1 == 0` (mod 2**256 - 1),
                            /// and `FixedPointMathLib.fullMulDiv` will revert as the denominator is zero.
                            function _inc(uint256 x) private pure returns (uint256) {
                                unchecked {
                                    return x + 1;
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*              DEPOSIT / WITHDRAWAL LIMIT LOGIC              */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the maximum amount of the underlying asset that can be deposited
                            /// into the Vault for `to`, via a deposit call.
                            ///
                            /// - MUST return a limited value if `to` is subject to some deposit limit.
                            /// - MUST return `2**256-1` if there is no maximum limit.
                            /// - MUST NOT revert.
                            function maxDeposit(address to) public view virtual returns (uint256 maxAssets) {
                                to = to; // Silence unused variable warning.
                                maxAssets = type(uint256).max;
                            }
                            /// @dev Returns the maximum amount of the Vault shares that can be minter for `to`,
                            /// via a mint call.
                            ///
                            /// - MUST return a limited value if `to` is subject to some mint limit.
                            /// - MUST return `2**256-1` if there is no maximum limit.
                            /// - MUST NOT revert.
                            function maxMint(address to) public view virtual returns (uint256 maxShares) {
                                to = to; // Silence unused variable warning.
                                maxShares = type(uint256).max;
                            }
                            /// @dev Returns the maximum amount of the underlying asset that can be withdrawn
                            /// from the `owner`'s balance in the Vault, via a withdraw call.
                            ///
                            /// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
                            /// - MUST NOT revert.
                            function maxWithdraw(address owner) public view virtual returns (uint256 maxAssets) {
                                maxAssets = convertToAssets(balanceOf(owner));
                            }
                            /// @dev Returns the maximum amount of Vault shares that can be redeemed
                            /// from the `owner`'s balance in the Vault, via a redeem call.
                            ///
                            /// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
                            /// - MUST return `balanceOf(owner)` otherwise.
                            /// - MUST NOT revert.
                            function maxRedeem(address owner) public view virtual returns (uint256 maxShares) {
                                maxShares = balanceOf(owner);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                 DEPOSIT / WITHDRAWAL LOGIC                 */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Mints `shares` Vault shares to `to` by depositing exactly `assets`
                            /// of underlying tokens.
                            ///
                            /// - MUST emit the {Deposit} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the deposit execution, and are accounted for during deposit.
                            /// - MUST revert if all of `assets` cannot be deposited, such as due to deposit limit,
                            ///   slippage, insufficient approval, etc.
                            ///
                            /// Note: Most implementations will require pre-approval of the Vault with the
                            /// Vault's underlying `asset` token.
                            function deposit(uint256 assets, address to) public virtual returns (uint256 shares) {
                                if (assets > maxDeposit(to)) _revert(0xb3c61a83); // `DepositMoreThanMax()`.
                                shares = previewDeposit(assets);
                                _deposit(msg.sender, to, assets, shares);
                            }
                            /// @dev Mints exactly `shares` Vault shares to `to` by depositing `assets`
                            /// of underlying tokens.
                            ///
                            /// - MUST emit the {Deposit} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the mint execution, and are accounted for during mint.
                            /// - MUST revert if all of `shares` cannot be deposited, such as due to deposit limit,
                            ///   slippage, insufficient approval, etc.
                            ///
                            /// Note: Most implementations will require pre-approval of the Vault with the
                            /// Vault's underlying `asset` token.
                            function mint(uint256 shares, address to) public virtual returns (uint256 assets) {
                                if (shares > maxMint(to)) _revert(0x6a695959); // `MintMoreThanMax()`.
                                assets = previewMint(shares);
                                _deposit(msg.sender, to, assets, shares);
                            }
                            /// @dev Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `to`.
                            ///
                            /// - MUST emit the {Withdraw} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the withdraw execution, and are accounted for during withdraw.
                            /// - MUST revert if all of `assets` cannot be withdrawn, such as due to withdrawal limit,
                            ///   slippage, insufficient balance, etc.
                            ///
                            /// Note: Some implementations will require pre-requesting to the Vault before a withdrawal
                            /// may be performed. Those methods should be performed separately.
                            function withdraw(uint256 assets, address to, address owner)
                                public
                                virtual
                                returns (uint256 shares)
                            {
                                if (assets > maxWithdraw(owner)) _revert(0x936941fc); // `WithdrawMoreThanMax()`.
                                shares = previewWithdraw(assets);
                                _withdraw(msg.sender, to, owner, assets, shares);
                            }
                            /// @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `to`.
                            ///
                            /// - MUST emit the {Withdraw} event.
                            /// - MAY support an additional flow in which the underlying tokens are owned by the Vault
                            ///   contract before the redeem execution, and are accounted for during redeem.
                            /// - MUST revert if all of shares cannot be redeemed, such as due to withdrawal limit,
                            ///   slippage, insufficient balance, etc.
                            ///
                            /// Note: Some implementations will require pre-requesting to the Vault before a redeem
                            /// may be performed. Those methods should be performed separately.
                            function redeem(uint256 shares, address to, address owner)
                                public
                                virtual
                                returns (uint256 assets)
                            {
                                if (shares > maxRedeem(owner)) _revert(0x4656425a); // `RedeemMoreThanMax()`.
                                assets = previewRedeem(shares);
                                _withdraw(msg.sender, to, owner, assets, shares);
                            }
                            /// @dev Internal helper for reverting efficiently.
                            function _revert(uint256 s) private pure {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x00, s)
                                    revert(0x1c, 0x04)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                      INTERNAL HELPERS                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev For deposits and mints.
                            ///
                            /// Emits a {Deposit} event.
                            function _deposit(address by, address to, uint256 assets, uint256 shares) internal virtual {
                                SafeTransferLib.safeTransferFrom(asset(), by, address(this), assets);
                                _mint(to, shares);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Emit the {Deposit} event.
                                    mstore(0x00, assets)
                                    mstore(0x20, shares)
                                    let m := shr(96, not(0))
                                    log3(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, and(m, by), and(m, to))
                                }
                                _afterDeposit(assets, shares);
                            }
                            /// @dev For withdrawals and redemptions.
                            ///
                            /// Emits a {Withdraw} event.
                            function _withdraw(address by, address to, address owner, uint256 assets, uint256 shares)
                                internal
                                virtual
                            {
                                if (by != owner) _spendAllowance(owner, by, shares);
                                _beforeWithdraw(assets, shares);
                                _burn(owner, shares);
                                SafeTransferLib.safeTransfer(asset(), to, assets);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Emit the {Withdraw} event.
                                    mstore(0x00, assets)
                                    mstore(0x20, shares)
                                    let m := shr(96, not(0))
                                    log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
                                }
                            }
                            /// @dev Internal conversion function (from assets to shares) to apply when the Vault is empty.
                            /// Only used when {_useVirtualShares} returns false.
                            ///
                            /// Note: Make sure to keep this function consistent with {_initialConvertToAssets}
                            /// when overriding it.
                            function _initialConvertToShares(uint256 assets)
                                internal
                                view
                                virtual
                                returns (uint256 shares)
                            {
                                shares = assets;
                            }
                            /// @dev Internal conversion function (from shares to assets) to apply when the Vault is empty.
                            /// Only used when {_useVirtualShares} returns false.
                            ///
                            /// Note: Make sure to keep this function consistent with {_initialConvertToShares}
                            /// when overriding it.
                            function _initialConvertToAssets(uint256 shares)
                                internal
                                view
                                virtual
                                returns (uint256 assets)
                            {
                                assets = shares;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     HOOKS TO OVERRIDE                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Hook that is called before any withdrawal or redemption.
                            function _beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
                            /// @dev Hook that is called after any deposit or mint.
                            function _afterDeposit(uint256 assets, uint256 shares) internal virtual {}
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                        /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                        abstract contract ERC20 {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /*//////////////////////////////////////////////////////////////
                                                    METADATA STORAGE
                            //////////////////////////////////////////////////////////////*/
                            string public name;
                            string public symbol;
                            uint8 public immutable decimals;
                            /*//////////////////////////////////////////////////////////////
                                                      ERC20 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 public totalSupply;
                            mapping(address => uint256) public balanceOf;
                            mapping(address => mapping(address => uint256)) public allowance;
                            /*//////////////////////////////////////////////////////////////
                                                    EIP-2612 STORAGE
                            //////////////////////////////////////////////////////////////*/
                            uint256 internal immutable INITIAL_CHAIN_ID;
                            bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                            mapping(address => uint256) public nonces;
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                string memory _name,
                                string memory _symbol,
                                uint8 _decimals
                            ) {
                                name = _name;
                                symbol = _symbol;
                                decimals = _decimals;
                                INITIAL_CHAIN_ID = block.chainid;
                                INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       ERC20 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                allowance[msg.sender][spender] = amount;
                                emit Approval(msg.sender, spender, amount);
                                return true;
                            }
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                balanceOf[msg.sender] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(msg.sender, to, amount);
                                return true;
                            }
                            function transferFrom(
                                address from,
                                address to,
                                uint256 amount
                            ) public virtual returns (bool) {
                                uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                                if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                                balanceOf[from] -= amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(from, to, amount);
                                return true;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     EIP-2612 LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                                // Unchecked because the only math done is incrementing
                                // the owner's nonce which cannot realistically overflow.
                                unchecked {
                                    address recoveredAddress = ecrecover(
                                        keccak256(
                                            abi.encodePacked(
                                                "\\x19\\x01",
                                                DOMAIN_SEPARATOR(),
                                                keccak256(
                                                    abi.encode(
                                                        keccak256(
                                                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                        ),
                                                        owner,
                                                        spender,
                                                        value,
                                                        nonces[owner]++,
                                                        deadline
                                                    )
                                                )
                                            )
                                        ),
                                        v,
                                        r,
                                        s
                                    );
                                    require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                    allowance[recoveredAddress][spender] = value;
                                }
                                emit Approval(owner, spender, value);
                            }
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                                return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                            }
                            function computeDomainSeparator() internal view virtual returns (bytes32) {
                                return
                                    keccak256(
                                        abi.encode(
                                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                            keccak256(bytes(name)),
                                            keccak256("1"),
                                            block.chainid,
                                            address(this)
                                        )
                                    );
                            }
                            /*//////////////////////////////////////////////////////////////
                                                INTERNAL MINT/BURN LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function _mint(address to, uint256 amount) internal virtual {
                                totalSupply += amount;
                                // Cannot overflow because the sum of all user
                                // balances can't exceed the max uint256 value.
                                unchecked {
                                    balanceOf[to] += amount;
                                }
                                emit Transfer(address(0), to, amount);
                            }
                            function _burn(address from, uint256 amount) internal virtual {
                                balanceOf[from] -= amount;
                                // Cannot underflow because a user's balance
                                // will never be larger than the total supply.
                                unchecked {
                                    totalSupply -= amount;
                                }
                                emit Transfer(from, address(0), amount);
                            }
                        }
                        // SPDX-License-Identifier: GPL-3.0-or-later
                        pragma solidity ^0.8.0;
                        interface ISwapper {
                            function swap(address[] calldata tokens, bytes[] calldata callDatas) external;
                        }
                        // SPDX-License-Identifier: GPL-3.0-or-later
                        pragma solidity 0.8.24;
                        import { Errors } from "../utils/Errors.sol";
                        import { Owned2Step } from "../../utils/Owned2Step.sol";
                        /// @author 0xtekgrinder
                        /// @title AOperator
                        /// @notice Abstract contract to allow access only to operator or owner
                        abstract contract AOperator is Owned2Step {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Event emitted when a output tokens and/or ratios are updated
                             */
                            event OperatorUpdated(address oldOperator, address newOperator);
                            /*//////////////////////////////////////////////////////////////
                                                    MUTABLE VARIABLES
                            //////////////////////////////////////////////////////////////*/
                            /**
                             *  @notice operator caller address to allow access only to web3 function
                             */
                            address public operator;
                            /*//////////////////////////////////////////////////////////////
                                                       MODIFIERS
                            //////////////////////////////////////////////////////////////*/
                            modifier onlyOperatorOrOwner() {
                                if (msg.sender != operator && msg.sender != owner) revert Errors.NotOperatorOrOwner();
                                _;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(address initialOperator) {
                                if (initialOperator == address(0)) revert Errors.ZeroAddress();
                                operator = initialOperator;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONTRACT LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function setOperator(address newOperator) external onlyOwner {
                                if (newOperator == address(0)) revert Errors.ZeroAddress();
                                address oldOperator = operator;
                                operator = newOperator;
                                emit OperatorUpdated(oldOperator, newOperator);
                            }
                        }
                        // SPDX-License-Identifier: GPL-3.0-or-later
                        pragma solidity 0.8.24;
                        import { Owned2Step } from "../../utils/Owned2Step.sol";
                        import { Errors } from "../utils/Errors.sol";
                        /// @author 0xtekgrinder
                        /// @title AFees
                        /// @notice Abstract contract to allow access only to operator or owner
                        abstract contract AFees is Owned2Step {
                            /*//////////////////////////////////////////////////////////////
                                                          EVENTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Event emitted when harvestFee is updated
                             */
                            event HarvestFeeUpdated(uint256 oldHarvestFee, uint256 newHarvestFee);
                            /**
                             * @notice Event emitted when feeRecipient is updated
                             */
                            event FeeRecipientUpdated(address oldFeeRecipient, address newFeeRecipient);
                            /**
                             * @notice Event emitted when feeToken is updated
                             */
                            event FeeTokenUpdated(address oldFeeToken, address newFeeToken);
                            /**
                             * @notice Event emitted when withdrawalFee is updated
                             */
                            event WithdrawalFeeUpdated(uint256 oldWithdrawalFee, uint256 newWithdrawalFee);
                            /*//////////////////////////////////////////////////////////////
                                                        CONSTANTS
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice Max BPS value (100%)
                             */
                            uint256 public constant MAX_BPS = 10_000;
                            /**
                             * @notice Max withdrawal fee value (10%)
                             */
                            uint256 public constant MAX_WITHDRAWAL_FEE = 1000;
                            /**
                             * @notice Max harvest fee value (20%)
                             */
                            uint256 public constant MAX_HARVEST_FEE = 2000;
                            /*//////////////////////////////////////////////////////////////
                                                    MUTABLE VARIABLES
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @notice fee to be applied when harvesting rewards
                             */
                            uint256 public harvestFee;
                            /**
                             * @notice fee to be applied when withdrawing funds
                             */
                            uint256 public withdrawalFee;
                            /**
                             * @notice address to receive the harvest fee
                             */
                            address public feeRecipient;
                            /**
                             * @notice token to be used to pay the harvest fee
                             */
                            address public feeToken;
                            /*//////////////////////////////////////////////////////////////
                                                        CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(
                                uint256 initialHarvestFee,
                                uint256 initialWithdrawalFee,
                                address initialFeeRecipient,
                                address initialFeeToken
                            ) {
                                if (initialFeeRecipient == address(0) || initialFeeToken == address(0)) revert Errors.ZeroAddress();
                                if (initialHarvestFee > MAX_HARVEST_FEE || initialWithdrawalFee > MAX_WITHDRAWAL_FEE) {
                                    revert Errors.InvalidFee();
                                }
                                harvestFee = initialHarvestFee;
                                feeRecipient = initialFeeRecipient;
                                feeToken = initialFeeToken;
                                withdrawalFee = initialWithdrawalFee;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                      FEES LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function setHarvestFee(uint256 newHarvestFee) external virtual onlyOwner {
                                if (newHarvestFee > MAX_HARVEST_FEE) {
                                    revert Errors.InvalidFee();
                                }
                                uint256 oldHarvestFee = harvestFee;
                                harvestFee = newHarvestFee;
                                emit HarvestFeeUpdated(oldHarvestFee, newHarvestFee);
                            }
                            function setWithdrawalFee(uint256 newWithdrawalFee) external virtual onlyOwner {
                                if (newWithdrawalFee > MAX_WITHDRAWAL_FEE) {
                                    revert Errors.InvalidFee();
                                }
                                uint256 oldWithdrawalFee = withdrawalFee;
                                withdrawalFee = newWithdrawalFee;
                                emit WithdrawalFeeUpdated(oldWithdrawalFee, newWithdrawalFee);
                            }
                            function setFeeRecipient(address newFeeRecipient) external virtual onlyOwner {
                                if (newFeeRecipient == address(0)) revert Errors.ZeroAddress();
                                address oldFeeRecipient = feeRecipient;
                                feeRecipient = newFeeRecipient;
                                emit FeeRecipientUpdated(oldFeeRecipient, newFeeRecipient);
                            }
                            function setFeeToken(address newFeeToken) external virtual onlyOwner {
                                if (newFeeToken == address(0)) revert Errors.ZeroAddress();
                                address oldFeeToken = feeToken;
                                feeToken = newFeeToken;
                                emit FeeTokenUpdated(oldFeeToken, newFeeToken);
                            }
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.0;
                        library Errors {
                            // General errors
                            error ZeroValue();
                            error ZeroAddress();
                            error EmptyArray();
                            error DifferentSizeArrays(uint256 length1, uint256 length2);
                            // Fee errors
                            error InvalidFee();
                            // Swapper errors
                            error SwapError();
                            // Weighted tokens errors
                            error RatioOverflow();
                            error NoWeightedTokens();
                            // Operator errors
                            error NotOperator();
                            error NotOperatorOrOwner();
                            // Swapper errors
                            error NotVault();
                            error WithdrawMoreThanMax();
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity 0.8.24;
                        import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
                        import { ERC20 } from "solmate/tokens/ERC20.sol";
                        library Allowance {
                            /**
                             * @notice Approve the router/aggregator to spend the token if needed
                             * @param _token address of the token to approve
                             * @param _spender address of the router/aggregator
                             */
                            function _approveTokenIfNeeded(address _token, address _spender) internal {
                                if (ERC20(_token).allowance(address(this), _spender) == 0) {
                                    SafeTransferLib.safeApprove(_token, _spender, type(uint256).max);
                                }
                            }
                        }
                        //SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.0;
                        import { Owned } from "solmate/auth/Owned.sol";
                        /// @author 0xtekgrinder
                        /// @title Owned2Step contract
                        /// @notice Simple single owner authorization mixin with 2 step transfer ownership
                        abstract contract Owned2Step is Owned {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event OwnershipTransferStarted(address indexed user, address indexed newOwner);
                            /*//////////////////////////////////////////////////////////////
                                                    OWNERSHIP STORAGE
                            //////////////////////////////////////////////////////////////*/
                            address public pendingOwner;
                            /*//////////////////////////////////////////////////////////////
                                                       MODIFIERS
                            //////////////////////////////////////////////////////////////*/
                            modifier onlyPendingOwner() {
                                require(pendingOwner == msg.sender, "UNAUTHORIZED");
                                _;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(address _owner) Owned(_owner) { }
                            /*//////////////////////////////////////////////////////////////
                                                     OWNERSHIP LOGIC
                            //////////////////////////////////////////////////////////////*/
                            /**
                             * @dev Starts the ownership transfer of the contract to a new account.
                             * @dev Can only be called by the current owner.
                             */
                            function transferOwnership(address newOwner) public virtual override onlyOwner {
                                pendingOwner = newOwner;
                                emit OwnershipTransferStarted(owner, newOwner);
                            }
                            /**
                             * @dev The new owner accepts the ownership transfer.
                             */
                            function acceptOwnership() public virtual onlyPendingOwner {
                                delete pendingOwner;
                                super.transferOwnership(msg.sender);
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
                        pragma solidity ^0.8.20;
                        /**
                         * @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;
                            }
                            function _contextSuffixLength() internal view virtual returns (uint256) {
                                return 0;
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Simple ERC20 + EIP-2612 implementation.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
                        ///
                        /// @dev Note:
                        /// - The ERC20 standard allows minting and transferring to and from the zero address,
                        ///   minting and transferring zero tokens, as well as self-approvals.
                        ///   For performance, this implementation WILL NOT revert for such actions.
                        ///   Please add any checks with overrides if desired.
                        /// - The `permit` function uses the ecrecover precompile (0x1).
                        ///
                        /// If you are overriding:
                        /// - NEVER violate the ERC20 invariant:
                        ///   the total sum of all balances must be equal to `totalSupply()`.
                        /// - Check that the overridden function is actually used in the function you want to
                        ///   change the behavior of. Much of the code has been manually inlined for performance.
                        abstract contract ERC20 {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The total supply has overflowed.
                            error TotalSupplyOverflow();
                            /// @dev The allowance has overflowed.
                            error AllowanceOverflow();
                            /// @dev The allowance has underflowed.
                            error AllowanceUnderflow();
                            /// @dev Insufficient balance.
                            error InsufficientBalance();
                            /// @dev Insufficient allowance.
                            error InsufficientAllowance();
                            /// @dev The permit is invalid.
                            error InvalidPermit();
                            /// @dev The permit has expired.
                            error PermitExpired();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           EVENTS                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
                            event Transfer(address indexed from, address indexed to, uint256 amount);
                            /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
                            event Approval(address indexed owner, address indexed spender, uint256 amount);
                            /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
                            uint256 private constant _TRANSFER_EVENT_SIGNATURE =
                                0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
                            /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
                            uint256 private constant _APPROVAL_EVENT_SIGNATURE =
                                0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                          STORAGE                           */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The storage slot for the total supply.
                            uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
                            /// @dev The balance slot of `owner` is given by:
                            /// ```
                            ///     mstore(0x0c, _BALANCE_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let balanceSlot := keccak256(0x0c, 0x20)
                            /// ```
                            uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
                            /// @dev The allowance slot of (`owner`, `spender`) is given by:
                            /// ```
                            ///     mstore(0x20, spender)
                            ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let allowanceSlot := keccak256(0x0c, 0x34)
                            /// ```
                            uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
                            /// @dev The nonce slot of `owner` is given by:
                            /// ```
                            ///     mstore(0x0c, _NONCES_SLOT_SEED)
                            ///     mstore(0x00, owner)
                            ///     let nonceSlot := keccak256(0x0c, 0x20)
                            /// ```
                            uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
                            uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
                            /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
                            bytes32 private constant _DOMAIN_TYPEHASH =
                                0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
                            /// @dev `keccak256("1")`.
                            bytes32 private constant _VERSION_HASH =
                                0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
                            /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
                            bytes32 private constant _PERMIT_TYPEHASH =
                                0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       ERC20 METADATA                       */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the name of the token.
                            function name() public view virtual returns (string memory);
                            /// @dev Returns the symbol of the token.
                            function symbol() public view virtual returns (string memory);
                            /// @dev Returns the decimals places of the token.
                            function decimals() public view virtual returns (uint8) {
                                return 18;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                           ERC20                            */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns the amount of tokens in existence.
                            function totalSupply() public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    result := sload(_TOTAL_SUPPLY_SLOT)
                                }
                            }
                            /// @dev Returns the amount of tokens owned by `owner`.
                            function balanceOf(address owner) public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x20))
                                }
                            }
                            /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
                            function allowance(address owner, address spender)
                                public
                                view
                                virtual
                                returns (uint256 result)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x34))
                                }
                            }
                            /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                            ///
                            /// Emits a {Approval} event.
                            function approve(address spender, uint256 amount) public virtual returns (bool) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the allowance slot and store the amount.
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, caller())
                                    sstore(keccak256(0x0c, 0x34), amount)
                                    // Emit the {Approval} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
                                }
                                return true;
                            }
                            /// @dev Transfer `amount` tokens from the caller to `to`.
                            ///
                            /// Requirements:
                            /// - `from` must at least have `amount`.
                            ///
                            /// Emits a {Transfer} event.
                            function transfer(address to, uint256 amount) public virtual returns (bool) {
                                _beforeTokenTransfer(msg.sender, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, caller())
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(msg.sender, to, amount);
                                return true;
                            }
                            /// @dev Transfers `amount` tokens from `from` to `to`.
                            ///
                            /// Note: Does not update the allowance if it is the maximum uint256 value.
                            ///
                            /// Requirements:
                            /// - `from` must at least have `amount`.
                            /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
                            ///
                            /// Emits a {Transfer} event.
                            function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
                                _beforeTokenTransfer(from, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let from_ := shl(96, from)
                                    // Compute the allowance slot and load its value.
                                    mstore(0x20, caller())
                                    mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
                                    let allowanceSlot := keccak256(0x0c, 0x34)
                                    let allowance_ := sload(allowanceSlot)
                                    // If the allowance is not the maximum uint256 value.
                                    if add(allowance_, 1) {
                                        // Revert if the amount to be transferred exceeds the allowance.
                                        if gt(amount, allowance_) {
                                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                                            revert(0x1c, 0x04)
                                        }
                                        // Subtract and store the updated allowance.
                                        sstore(allowanceSlot, sub(allowance_, amount))
                                    }
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(from, to, amount);
                                return true;
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                          EIP-2612                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev For more performance, override to return the constant value
                            /// of `keccak256(bytes(name()))` if `name()` will never change.
                            function _constantNameHash() internal view virtual returns (bytes32 result) {}
                            /// @dev Returns the current nonce for `owner`.
                            /// This value is used to compute the signature for EIP-2612 permit.
                            function nonces(address owner) public view virtual returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the nonce slot and load its value.
                                    mstore(0x0c, _NONCES_SLOT_SEED)
                                    mstore(0x00, owner)
                                    result := sload(keccak256(0x0c, 0x20))
                                }
                            }
                            /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
                            /// authorized by a signed approval by `owner`.
                            ///
                            /// Emits a {Approval} event.
                            function permit(
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) public virtual {
                                bytes32 nameHash = _constantNameHash();
                                //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
                                if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Revert if the block timestamp is greater than `deadline`.
                                    if gt(timestamp(), deadline) {
                                        mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
                                        revert(0x1c, 0x04)
                                    }
                                    let m := mload(0x40) // Grab the free memory pointer.
                                    // Clean the upper 96 bits.
                                    owner := shr(96, shl(96, owner))
                                    spender := shr(96, shl(96, spender))
                                    // Compute the nonce slot and load its value.
                                    mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
                                    mstore(0x00, owner)
                                    let nonceSlot := keccak256(0x0c, 0x20)
                                    let nonceValue := sload(nonceSlot)
                                    // Prepare the domain separator.
                                    mstore(m, _DOMAIN_TYPEHASH)
                                    mstore(add(m, 0x20), nameHash)
                                    mstore(add(m, 0x40), _VERSION_HASH)
                                    mstore(add(m, 0x60), chainid())
                                    mstore(add(m, 0x80), address())
                                    mstore(0x2e, keccak256(m, 0xa0))
                                    // Prepare the struct hash.
                                    mstore(m, _PERMIT_TYPEHASH)
                                    mstore(add(m, 0x20), owner)
                                    mstore(add(m, 0x40), spender)
                                    mstore(add(m, 0x60), value)
                                    mstore(add(m, 0x80), nonceValue)
                                    mstore(add(m, 0xa0), deadline)
                                    mstore(0x4e, keccak256(m, 0xc0))
                                    // Prepare the ecrecover calldata.
                                    mstore(0x00, keccak256(0x2c, 0x42))
                                    mstore(0x20, and(0xff, v))
                                    mstore(0x40, r)
                                    mstore(0x60, s)
                                    let t := staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)
                                    // If the ecrecover fails, the returndatasize will be 0x00,
                                    // `owner` will be checked if it equals the hash at 0x00,
                                    // which evaluates to false (i.e. 0), and we will revert.
                                    // If the ecrecover succeeds, the returndatasize will be 0x20,
                                    // `owner` will be compared against the returned address at 0x20.
                                    if iszero(eq(mload(returndatasize()), owner)) {
                                        mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Increment and store the updated nonce.
                                    sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
                                    // Compute the allowance slot and store the value.
                                    // The `owner` is already at slot 0x20.
                                    mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
                                    sstore(keccak256(0x2c, 0x34), value)
                                    // Emit the {Approval} event.
                                    log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
                                    mstore(0x40, m) // Restore the free memory pointer.
                                    mstore(0x60, 0) // Restore the zero pointer.
                                }
                            }
                            /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
                            function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
                                bytes32 nameHash = _constantNameHash();
                                //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
                                if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let m := mload(0x40) // Grab the free memory pointer.
                                    mstore(m, _DOMAIN_TYPEHASH)
                                    mstore(add(m, 0x20), nameHash)
                                    mstore(add(m, 0x40), _VERSION_HASH)
                                    mstore(add(m, 0x60), chainid())
                                    mstore(add(m, 0x80), address())
                                    result := keccak256(m, 0xa0)
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  INTERNAL MINT FUNCTIONS                   */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Mints `amount` tokens to `to`, increasing the total supply.
                            ///
                            /// Emits a {Transfer} event.
                            function _mint(address to, uint256 amount) internal virtual {
                                _beforeTokenTransfer(address(0), to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
                                    let totalSupplyAfter := add(totalSupplyBefore, amount)
                                    // Revert if the total supply overflows.
                                    if lt(totalSupplyAfter, totalSupplyBefore) {
                                        mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Store the updated total supply.
                                    sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(address(0), to, amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  INTERNAL BURN FUNCTIONS                   */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Burns `amount` tokens from `from`, reducing the total supply.
                            ///
                            /// Emits a {Transfer} event.
                            function _burn(address from, uint256 amount) internal virtual {
                                _beforeTokenTransfer(from, address(0), amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, _BALANCE_SLOT_SEED)
                                    mstore(0x00, from)
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Subtract and store the updated total supply.
                                    sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
                                }
                                _afterTokenTransfer(from, address(0), amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                INTERNAL TRANSFER FUNCTIONS                 */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Moves `amount` of tokens from `from` to `to`.
                            function _transfer(address from, address to, uint256 amount) internal virtual {
                                _beforeTokenTransfer(from, to, amount);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let from_ := shl(96, from)
                                    // Compute the balance slot and load its value.
                                    mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
                                    let fromBalanceSlot := keccak256(0x0c, 0x20)
                                    let fromBalance := sload(fromBalanceSlot)
                                    // Revert if insufficient balance.
                                    if gt(amount, fromBalance) {
                                        mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Subtract and store the updated balance.
                                    sstore(fromBalanceSlot, sub(fromBalance, amount))
                                    // Compute the balance slot of `to`.
                                    mstore(0x00, to)
                                    let toBalanceSlot := keccak256(0x0c, 0x20)
                                    // Add and store the updated balance of `to`.
                                    // Will not overflow because the sum of all user balances
                                    // cannot exceed the maximum uint256 value.
                                    sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
                                    // Emit the {Transfer} event.
                                    mstore(0x20, amount)
                                    log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
                                }
                                _afterTokenTransfer(from, to, amount);
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                INTERNAL ALLOWANCE FUNCTIONS                */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
                            function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute the allowance slot and load its value.
                                    mstore(0x20, spender)
                                    mstore(0x0c, _ALLOWANCE_SLOT_SEED)
                                    mstore(0x00, owner)
                                    let allowanceSlot := keccak256(0x0c, 0x34)
                                    let allowance_ := sload(allowanceSlot)
                                    // If the allowance is not the maximum uint256 value.
                                    if add(allowance_, 1) {
                                        // Revert if the amount to be transferred exceeds the allowance.
                                        if gt(amount, allowance_) {
                                            mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                                            revert(0x1c, 0x04)
                                        }
                                        // Subtract and store the updated allowance.
                                        sstore(allowanceSlot, sub(allowance_, amount))
                                    }
                                }
                            }
                            /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
                            ///
                            /// Emits a {Approval} event.
                            function _approve(address owner, address spender, uint256 amount) internal virtual {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let owner_ := shl(96, owner)
                                    // Compute the allowance slot and store the amount.
                                    mstore(0x20, spender)
                                    mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
                                    sstore(keccak256(0x0c, 0x34), amount)
                                    // Emit the {Approval} event.
                                    mstore(0x00, amount)
                                    log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                     HOOKS TO OVERRIDE                      */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Hook that is called before any transfer of tokens.
                            /// This includes minting and burning.
                            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.
                            function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity ^0.8.4;
                        /// @notice Arithmetic library with operations for fixed-point numbers.
                        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
                        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
                        library FixedPointMathLib {
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                       CUSTOM ERRORS                        */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                            error ExpOverflow();
                            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                            error FactorialOverflow();
                            /// @dev The operation failed, due to an overflow.
                            error RPowOverflow();
                            /// @dev The mantissa is too big to fit.
                            error MantissaOverflow();
                            /// @dev The operation failed, due to an multiplication overflow.
                            error MulWadFailed();
                            /// @dev The operation failed, due to an multiplication overflow.
                            error SMulWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error DivWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error SDivWadFailed();
                            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                            error MulDivFailed();
                            /// @dev The division failed, as the denominator is zero.
                            error DivFailed();
                            /// @dev The full precision multiply-divide operation failed, either due
                            /// to the result being larger than 256 bits, or a division by a zero.
                            error FullMulDivFailed();
                            /// @dev The output is undefined, as the input is less-than-or-equal to zero.
                            error LnWadUndefined();
                            /// @dev The input outside the acceptable domain.
                            error OutOfDomain();
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                         CONSTANTS                          */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev The scalar of ETH and most ERC20s.
                            uint256 internal constant WAD = 1e18;
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*              SIMPLIFIED FIXED POINT OPERATIONS             */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Equivalent to `(x * y) / WAD` rounded down.
                            function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                    if mul(y, gt(x, div(not(0), y))) {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down.
                            function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(x, y)
                                    // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
                                    if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                                        mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := sdiv(z, WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                            function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                            function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(mul(x, y), WAD)
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded up.
                            function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                    if mul(y, gt(x, div(not(0), y))) {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                                }
                            }
                            /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
                            function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down.
                            function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down.
                            function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(x, WAD)
                                    // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
                                    if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                                        mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := sdiv(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                            function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                            function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(mul(x, WAD), y)
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded up.
                            function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                                }
                            }
                            /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
                            function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                                }
                            }
                            /// @dev Equivalent to `x` to the power of `y`.
                            /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
                            function powWad(int256 x, int256 y) internal pure returns (int256) {
                                // Using `ln(x)` means `x` must be greater than 0.
                                return expWad((lnWad(x) * y) / int256(WAD));
                            }
                            /// @dev Returns `exp(x)`, denominated in `WAD`.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                            function expWad(int256 x) internal pure returns (int256 r) {
                                unchecked {
                                    // When the result is less than 0.5 we return zero.
                                    // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
                                    if (x <= -41446531673892822313) return r;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                                        // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                                        if iszero(slt(x, 135305999368893231589)) {
                                            mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                    // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
                                    // for more intermediate precision and a binary basis. This base conversion
                                    // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                                    x = (x << 78) / 5 ** 18;
                                    // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                                    // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                                    // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                                    int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
                                    x = x - k * 54916777467707473351141471128;
                                    // `k` is in the range `[-61, 195]`.
                                    // Evaluate using a (6, 7)-term rational approximation.
                                    // `p` is made monic, we'll multiply by a scale factor later.
                                    int256 y = x + 1346386616545796478920950773328;
                                    y = ((y * x) >> 96) + 57155421227552351082224309758442;
                                    int256 p = y + x - 94201549194550492254356042504812;
                                    p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                                    p = p * x + (4385272521454847904659076985693276 << 96);
                                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                    int256 q = x - 2855989394907223263936484059900;
                                    q = ((q * x) >> 96) + 50020603652535783019961831881945;
                                    q = ((q * x) >> 96) - 533845033583426703283633433725380;
                                    q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                                    q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                                    q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Div in assembly because solidity adds a zero check despite the unchecked.
                                        // The q polynomial won't have zeros in the domain as all its roots are complex.
                                        // No scaling is necessary because p is already `2**96` too large.
                                        r := sdiv(p, q)
                                    }
                                    // r should be in the range `(0.09, 0.25) * 2**96`.
                                    // We now need to multiply r by:
                                    // - The scale factor `s ≈ 6.031367120`.
                                    // - The `2**k` factor from the range reduction.
                                    // - The `1e18 / 2**96` factor for base conversion.
                                    // We do this all at once, with an intermediate result in `2**213`
                                    // basis, so the final right shift is always by a positive amount.
                                    r = int256(
                                        (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
                                    );
                                }
                            }
                            /// @dev Returns `ln(x)`, denominated in `WAD`.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                            function lnWad(int256 x) internal pure returns (int256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
                                    // We do this by multiplying by `2**96 / 10**18`. But since
                                    // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
                                    // and add `ln(2**96 / 10**18)` at the end.
                                    // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    // We place the check here for more optimal stack operations.
                                    if iszero(sgt(x, 0)) {
                                        mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // forgefmt: disable-next-item
                                    r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                        0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
                                    // Reduce range of x to (1, 2) * 2**96
                                    // ln(2^k * x) = k * ln(2) + ln(x)
                                    x := shr(159, shl(r, x))
                                    // Evaluate using a (8, 8)-term rational approximation.
                                    // `p` is made monic, we will multiply by a scale factor later.
                                    // forgefmt: disable-next-item
                                    let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                                        sar(96, mul(add(43456485725739037958740375743393,
                                        sar(96, mul(add(24828157081833163892658089445524,
                                        sar(96, mul(add(3273285459638523848632254066296,
                                            x), x))), x))), x)), 11111509109440967052023855526967)
                                    p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
                                    p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
                                    p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
                                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                    // `q` is monic by convention.
                                    let q := add(5573035233440673466300451813936, x)
                                    q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
                                    q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
                                    q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
                                    q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
                                    q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
                                    q := add(909429971244387300277376558375, sar(96, mul(x, q)))
                                    // `p / q` is in the range `(0, 0.125) * 2**96`.
                                    // Finalization, we need to:
                                    // - Multiply by the scale factor `s = 5.549…`.
                                    // - Add `ln(2**96 / 10**18)`.
                                    // - Add `k * ln(2)`.
                                    // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
                                    // The q polynomial is known not to have zeros in the domain.
                                    // No scaling required because p is already `2**96` too large.
                                    p := sdiv(p, q)
                                    // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
                                    p := mul(1677202110996718588342820967067443963516166, p)
                                    // Add `ln(2) * k * 5**18 * 2**192`.
                                    // forgefmt: disable-next-item
                                    p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
                                    // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
                                    p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
                                    // Base conversion: mul `2**18 / 2**192`.
                                    r := sar(174, p)
                                }
                            }
                            /// @dev Returns `W_0(x)`, denominated in `WAD`.
                            /// See: https://en.wikipedia.org/wiki/Lambert_W_function
                            /// a.k.a. Product log function. This is an approximation of the principal branch.
                            function lambertW0Wad(int256 x) internal pure returns (int256 w) {
                                // forgefmt: disable-next-item
                                unchecked {
                                    if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
                                    int256 wad = int256(WAD);
                                    int256 p = x;
                                    uint256 c; // Whether we need to avoid catastrophic cancellation.
                                    uint256 i = 4; // Number of iterations.
                                    if (w <= 0x1ffffffffffff) {
                                        if (-0x4000000000000 <= w) {
                                            i = 1; // Inputs near zero only take one step to converge.
                                        } else if (w <= -0x3ffffffffffffff) {
                                            i = 32; // Inputs near `-1/e` take very long to converge.
                                        }
                                    } else if (w >> 63 == 0) {
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            // Inline log2 for more performance, since the range is small.
                                            let v := shr(49, w)
                                            let l := shl(3, lt(0xff, v))
                                            l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                                                0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                                            w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                                            c := gt(l, 60)
                                            i := add(2, add(gt(l, 53), c))
                                        }
                                    } else {
                                        int256 ll = lnWad(w = lnWad(w));
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                                            w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                                            i := add(3, iszero(shr(68, x)))
                                            c := iszero(shr(143, x))
                                        }
                                        if (c == 0) {
                                            do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                                                int256 e = expWad(w);
                                                /// @solidity memory-safe-assembly
                                                assembly {
                                                    let t := mul(w, div(e, wad))
                                                    w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                                                }
                                                if (p <= w) break;
                                                p = w;
                                            } while (--i != 0);
                                            /// @solidity memory-safe-assembly
                                            assembly {
                                                w := sub(w, sgt(w, 2))
                                            }
                                            return w;
                                        }
                                    }
                                    do { // Otherwise, use Halley's for faster convergence.
                                        int256 e = expWad(w);
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            let t := add(w, wad)
                                            let s := sub(mul(w, e), mul(x, wad))
                                            w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                                        }
                                        if (p <= w) break;
                                        p = w;
                                    } while (--i != c);
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        w := sub(w, sgt(w, 2))
                                    }
                                    // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
                                    // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
                                    if (c != 0) {
                                        int256 t = w | 1;
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            x := sdiv(mul(x, wad), t)
                                        }
                                        x = (t * (wad + lnWad(x)));
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            w := sdiv(x, add(wad, t))
                                        }
                                    }
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                  GENERAL NUMBER UTILITIES                  */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Calculates `floor(x * y / d)` with full precision.
                            /// Throws if result overflows a uint256 or when `d` is zero.
                            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
                            function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for {} 1 {} {
                                        // 512-bit multiply `[p1 p0] = x * y`.
                                        // Compute the product mod `2**256` and mod `2**256 - 1`
                                        // then use the Chinese Remainder Theorem to reconstruct
                                        // the 512 bit result. The result is stored in two 256
                                        // variables such that `product = p1 * 2**256 + p0`.
                                        // Least significant 256 bits of the product.
                                        result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                                        let mm := mulmod(x, y, not(0))
                                        // Most significant 256 bits of the product.
                                        let p1 := sub(mm, add(result, lt(mm, result)))
                                        // Handle non-overflow cases, 256 by 256 division.
                                        if iszero(p1) {
                                            if iszero(d) {
                                                mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                                revert(0x1c, 0x04)
                                            }
                                            result := div(result, d)
                                            break
                                        }
                                        // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                                        if iszero(gt(d, p1)) {
                                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                        /*------------------- 512 by 256 division --------------------*/
                                        // Make division exact by subtracting the remainder from `[p1 p0]`.
                                        // Compute remainder using mulmod.
                                        let r := mulmod(x, y, d)
                                        // `t` is the least significant bit of `d`.
                                        // Always greater or equal to 1.
                                        let t := and(d, sub(0, d))
                                        // Divide `d` by `t`, which is a power of two.
                                        d := div(d, t)
                                        // Invert `d mod 2**256`
                                        // Now that `d` is an odd number, it has an inverse
                                        // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                                        // Compute the inverse by starting with a seed that is correct
                                        // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                                        let inv := xor(2, mul(3, d))
                                        // Now use Newton-Raphson iteration to improve the precision.
                                        // Thanks to Hensel's lifting lemma, this also works in modular
                                        // arithmetic, doubling the correct bits in each step.
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                                        result :=
                                            mul(
                                                // Divide [p1 p0] by the factors of two.
                                                // Shift in bits from `p1` into `p0`. For this we need
                                                // to flip `t` such that it is `2**256 / t`.
                                                or(
                                                    mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                                                    div(sub(result, r), t)
                                                ),
                                                // inverse mod 2**256
                                                mul(inv, sub(2, mul(d, inv)))
                                            )
                                        break
                                    }
                                }
                            }
                            /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
                            /// Throws if result overflows a uint256 or when `d` is zero.
                            /// Credit to Uniswap-v3-core under MIT license:
                            /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
                            function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                                result = fullMulDiv(x, y, d);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if mulmod(x, y, d) {
                                        result := add(result, 1)
                                        if iszero(result) {
                                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                    }
                                }
                            }
                            /// @dev Returns `floor(x * y / d)`.
                            /// Reverts if `x * y` overflows, or `d` is zero.
                            function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := div(mul(x, y), d)
                                }
                            }
                            /// @dev Returns `ceil(x * y / d)`.
                            /// Reverts if `x * y` overflows, or `d` is zero.
                            function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
                                }
                            }
                            /// @dev Returns `ceil(x / d)`.
                            /// Reverts if `d` is zero.
                            function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(d) {
                                        mstore(0x00, 0x65244e4e) // `DivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := add(iszero(iszero(mod(x, d))), div(x, d))
                                }
                            }
                            /// @dev Returns `max(0, x - y)`.
                            function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(gt(x, y), sub(x, y))
                                }
                            }
                            /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
                            /// Reverts if the computation overflows.
                            function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
                                    if x {
                                        z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                                        let half := shr(1, b) // Divide `b` by 2.
                                        // Divide `y` by 2 every iteration.
                                        for { y := shr(1, y) } y { y := shr(1, y) } {
                                            let xx := mul(x, x) // Store x squared.
                                            let xxRound := add(xx, half) // Round to the nearest number.
                                            // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                                            if or(lt(xxRound, xx), shr(128, x)) {
                                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                                revert(0x1c, 0x04)
                                            }
                                            x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                                            // If `y` is odd:
                                            if and(y, 1) {
                                                let zx := mul(z, x) // Compute `z * x`.
                                                let zxRound := add(zx, half) // Round to the nearest number.
                                                // If `z * x` overflowed or `zx + half` overflowed:
                                                if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                                                    // Revert if `x` is non-zero.
                                                    if iszero(iszero(x)) {
                                                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                                        revert(0x1c, 0x04)
                                                    }
                                                }
                                                z := div(zxRound, b) // Return properly scaled `zxRound`.
                                            }
                                        }
                                    }
                                }
                            }
                            /// @dev Returns the square root of `x`.
                            function sqrt(uint256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
                                    z := 181 // The "correct" value is 1, but this saves a multiplication later.
                                    // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                                    // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                                    // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
                                    // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
                                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffffff, shr(r, x))))
                                    z := shl(shr(1, r), z)
                                    // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
                                    // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
                                    // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
                                    // That's not possible if `x < 256` but we can just verify those cases exhaustively.
                                    // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
                                    // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
                                    // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
                                    // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
                                    // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
                                    // with largest error when `s = 1` and when `s = 256` or `1/256`.
                                    // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
                                    // Then we can estimate `sqrt(y)` using
                                    // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
                                    // There is no overflow risk here since `y < 2**136` after the first branch above.
                                    z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
                                    // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    z := shr(1, add(z, div(x, z)))
                                    // If `x+1` is a perfect square, the Babylonian method cycles between
                                    // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
                                    // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                                    z := sub(z, lt(div(x, z), z))
                                }
                            }
                            /// @dev Returns the cube root of `x`.
                            /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
                            /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
                            function cbrt(uint256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                    z := sub(z, lt(div(x, mul(z, z)), z))
                                }
                            }
                            /// @dev Returns the square root of `x`, denominated in `WAD`.
                            function sqrtWad(uint256 x) internal pure returns (uint256 z) {
                                unchecked {
                                    z = 10 ** 9;
                                    if (x <= type(uint256).max / 10 ** 36 - 1) {
                                        x *= 10 ** 18;
                                        z = 1;
                                    }
                                    z *= sqrt(x);
                                }
                            }
                            /// @dev Returns the cube root of `x`, denominated in `WAD`.
                            function cbrtWad(uint256 x) internal pure returns (uint256 z) {
                                unchecked {
                                    z = 10 ** 12;
                                    if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                                        if (x >= type(uint256).max / 10 ** 36) {
                                            x *= 10 ** 18;
                                            z = 10 ** 6;
                                        } else {
                                            x *= 10 ** 36;
                                            z = 1;
                                        }
                                    }
                                    z *= cbrt(x);
                                }
                            }
                            /// @dev Returns the factorial of `x`.
                            function factorial(uint256 x) internal pure returns (uint256 result) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(lt(x, 58)) {
                                        mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
                                }
                            }
                            /// @dev Returns the log2 of `x`.
                            /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
                            /// Returns 0 if `x` is zero.
                            function log2(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                                    // forgefmt: disable-next-item
                                    r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                        0x0706060506020504060203020504030106050205030304010505030400000000))
                                }
                            }
                            /// @dev Returns the log2 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log2Up(uint256 x) internal pure returns (uint256 r) {
                                r = log2(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(shl(r, 1), x))
                                }
                            }
                            /// @dev Returns the log10 of `x`.
                            /// Returns 0 if `x` is zero.
                            function log10(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if iszero(lt(x, 100000000000000000000000000000000000000)) {
                                        x := div(x, 100000000000000000000000000000000000000)
                                        r := 38
                                    }
                                    if iszero(lt(x, 100000000000000000000)) {
                                        x := div(x, 100000000000000000000)
                                        r := add(r, 20)
                                    }
                                    if iszero(lt(x, 10000000000)) {
                                        x := div(x, 10000000000)
                                        r := add(r, 10)
                                    }
                                    if iszero(lt(x, 100000)) {
                                        x := div(x, 100000)
                                        r := add(r, 5)
                                    }
                                    r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
                                }
                            }
                            /// @dev Returns the log10 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log10Up(uint256 x) internal pure returns (uint256 r) {
                                r = log10(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(exp(10, r), x))
                                }
                            }
                            /// @dev Returns the log256 of `x`.
                            /// Returns 0 if `x` is zero.
                            function log256(uint256 x) internal pure returns (uint256 r) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                    r := or(shr(3, r), lt(0xff, shr(r, x)))
                                }
                            }
                            /// @dev Returns the log256 of `x`, rounded up.
                            /// Returns 0 if `x` is zero.
                            function log256Up(uint256 x) internal pure returns (uint256 r) {
                                r = log256(x);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := add(r, lt(shl(shl(3, r), 1), x))
                                }
                            }
                            /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
                            /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
                            function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    mantissa := x
                                    if mantissa {
                                        if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                                            mantissa := div(mantissa, 1000000000000000000000000000000000)
                                            exponent := 33
                                        }
                                        if iszero(mod(mantissa, 10000000000000000000)) {
                                            mantissa := div(mantissa, 10000000000000000000)
                                            exponent := add(exponent, 19)
                                        }
                                        if iszero(mod(mantissa, 1000000000000)) {
                                            mantissa := div(mantissa, 1000000000000)
                                            exponent := add(exponent, 12)
                                        }
                                        if iszero(mod(mantissa, 1000000)) {
                                            mantissa := div(mantissa, 1000000)
                                            exponent := add(exponent, 6)
                                        }
                                        if iszero(mod(mantissa, 10000)) {
                                            mantissa := div(mantissa, 10000)
                                            exponent := add(exponent, 4)
                                        }
                                        if iszero(mod(mantissa, 100)) {
                                            mantissa := div(mantissa, 100)
                                            exponent := add(exponent, 2)
                                        }
                                        if iszero(mod(mantissa, 10)) {
                                            mantissa := div(mantissa, 10)
                                            exponent := add(exponent, 1)
                                        }
                                    }
                                }
                            }
                            /// @dev Convenience function for packing `x` into a smaller number using `sci`.
                            /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
                            /// The `exponent` will be in bits [0..6] (the lower 7 bits).
                            /// Use `SafeCastLib` to safely ensure that the `packed` number is small
                            /// enough to fit in the desired unsigned integer type:
                            /// ```
                            ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
                            /// ```
                            function packSci(uint256 x) internal pure returns (uint256 packed) {
                                (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
                                /// @solidity memory-safe-assembly
                                assembly {
                                    if shr(249, x) {
                                        mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                    packed := or(shl(7, x), packed)
                                }
                            }
                            /// @dev Convenience function for unpacking a packed number from `packSci`.
                            function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
                                unchecked {
                                    unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
                                }
                            }
                            /// @dev Returns the average of `x` and `y`.
                            function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = (x & y) + ((x ^ y) >> 1);
                                }
                            }
                            /// @dev Returns the average of `x` and `y`.
                            function avg(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = (x >> 1) + (y >> 1) + (x & y & 1);
                                }
                            }
                            /// @dev Returns the absolute value of `x`.
                            function abs(int256 x) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
                                }
                            }
                            /// @dev Returns the absolute distance between `x` and `y`.
                            function dist(int256 x, int256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
                                }
                            }
                            /// @dev Returns the minimum of `x` and `y`.
                            function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), lt(y, x)))
                                }
                            }
                            /// @dev Returns the minimum of `x` and `y`.
                            function min(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), slt(y, x)))
                                }
                            }
                            /// @dev Returns the maximum of `x` and `y`.
                            function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), gt(y, x)))
                                }
                            }
                            /// @dev Returns the maximum of `x` and `y`.
                            function max(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, y), sgt(y, x)))
                                }
                            }
                            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                            function clamp(uint256 x, uint256 minValue, uint256 maxValue)
                                internal
                                pure
                                returns (uint256 z)
                            {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
                                    z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
                                }
                            }
                            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                            function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
                                    z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
                                }
                            }
                            /// @dev Returns greatest common divisor of `x` and `y`.
                            function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    for { z := x } y {} {
                                        let t := y
                                        y := mod(z, y)
                                        z := t
                                    }
                                }
                            }
                            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                            /*                   RAW NUMBER OPERATIONS                    */
                            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                            /// @dev Returns `x + y`, without checking for overflow.
                            function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x + y;
                                }
                            }
                            /// @dev Returns `x + y`, without checking for overflow.
                            function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x + y;
                                }
                            }
                            /// @dev Returns `x - y`, without checking for underflow.
                            function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x - y;
                                }
                            }
                            /// @dev Returns `x - y`, without checking for underflow.
                            function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x - y;
                                }
                            }
                            /// @dev Returns `x * y`, without checking for overflow.
                            function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                unchecked {
                                    z = x * y;
                                }
                            }
                            /// @dev Returns `x * y`, without checking for overflow.
                            function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
                                unchecked {
                                    z = x * y;
                                }
                            }
                            /// @dev Returns `x / y`, returning 0 if `y` is zero.
                            function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := div(x, y)
                                }
                            }
                            /// @dev Returns `x / y`, returning 0 if `y` is zero.
                            function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := sdiv(x, y)
                                }
                            }
                            /// @dev Returns `x % y`, returning 0 if `y` is zero.
                            function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mod(x, y)
                                }
                            }
                            /// @dev Returns `x % y`, returning 0 if `y` is zero.
                            function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := smod(x, y)
                                }
                            }
                            /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
                            function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := addmod(x, y, d)
                                }
                            }
                            /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
                            function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    z := mulmod(x, y, d)
                                }
                            }
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Simple single owner authorization mixin.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
                        abstract contract Owned {
                            /*//////////////////////////////////////////////////////////////
                                                         EVENTS
                            //////////////////////////////////////////////////////////////*/
                            event OwnershipTransferred(address indexed user, address indexed newOwner);
                            /*//////////////////////////////////////////////////////////////
                                                    OWNERSHIP STORAGE
                            //////////////////////////////////////////////////////////////*/
                            address public owner;
                            modifier onlyOwner() virtual {
                                require(msg.sender == owner, "UNAUTHORIZED");
                                _;
                            }
                            /*//////////////////////////////////////////////////////////////
                                                       CONSTRUCTOR
                            //////////////////////////////////////////////////////////////*/
                            constructor(address _owner) {
                                owner = _owner;
                                emit OwnershipTransferred(address(0), _owner);
                            }
                            /*//////////////////////////////////////////////////////////////
                                                     OWNERSHIP LOGIC
                            //////////////////////////////////////////////////////////////*/
                            function transferOwnership(address newOwner) public virtual onlyOwner {
                                owner = newOwner;
                                emit OwnershipTransferred(msg.sender, newOwner);
                            }
                        }
                        

                        File 10 of 18: WarStaker
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IFarmer} from "interfaces/IFarmer.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {ERC20} from "openzeppelin/token/ERC20/ERC20.sol";
                        import {Pausable} from "openzeppelin/security/Pausable.sol";
                        import {ReentrancyGuard} from "openzeppelin/security/ReentrancyGuard.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Warlord Staking contract
                         * @author Paladin
                         * @notice Staking system for Warlord to distribute yield & rewards,
                         *         mints an ERC20 token representing user staked amounts.
                         */
                        contract WarStaker is ERC20, ReentrancyGuard, Pausable, Owner {
                          using SafeERC20 for IERC20;
                          // Constants
                          /**
                           * @notice 1e18 scale
                           */
                          uint256 private constant UNIT = 1e18;
                          /**
                           * @notice Max value for BPS - 100%
                           */
                          uint256 private constant MAX_BPS = 10_000;
                          /**
                           * @notice Max value possible for an uint256
                           */
                          uint256 private constant MAX_UINT256 = 2 ** 256 - 1;
                          /**
                           * @notice Duration in second of a reward distribution
                           */
                          uint256 private constant DISTRIBUTION_DURATION = 604_800; // 1 week
                          /**
                           * @notice Ratio of the total reward amount to be in the queue before moving it to distribution
                           */
                          uint256 private constant UPDATE_REWARD_RATIO = 8500; // 85 %
                          // Structs
                          /**
                           * @notice UserRewardState struct
                           *   lastRewardPerToken: last update reward per token value
                           *   accruedRewards: total amount of rewards accrued
                           */
                          struct UserRewardState {
                            uint256 lastRewardPerToken;
                            uint256 accruedRewards;
                          }
                          /**
                           * @notice RewardState struct
                           *   rewardPerToken: current reward per token value
                           *   lastUpdate: last state update timestamp
                           *   distributionEndTimestamp: timestamp of the end of the current distribution
                           *   ratePerSecond: current distribution rate per second
                           *   currentRewardAmount: current amount of rewards in the distribution
                           *   queuedRewardAmount: current amount of reward queued for the distribution
                           *   userStates: users reward state for the reward token
                           */
                          struct RewardState {
                            uint256 rewardPerToken;
                            uint128 lastUpdate;
                            uint128 distributionEndTimestamp;
                            uint256 ratePerSecond;
                            uint256 currentRewardAmount;
                            uint256 queuedRewardAmount;
                            // user address => user reward state
                            mapping(address => UserRewardState) userStates;
                          }
                          /**
                           * @notice UserClaimableRewards struct
                           *   reward: address of the reward token
                           *   claimableAmount: amount of rewards accrued by the user
                           */
                          struct UserClaimableRewards {
                            address reward;
                            uint256 claimableAmount;
                          }
                          /**
                           * @notice UserClaimedRewards struct
                           *   reward: address of the reward token
                           *   amount: amount of rewards claimed by the user
                           */
                          struct UserClaimedRewards {
                            address reward;
                            uint256 amount;
                          }
                          // Storage
                          /**
                           * @notice Address of the Warlord token
                           */
                          address public immutable warToken;
                          /**
                           * @notice List of reward token distributed by this contract (past & current)
                           */
                          address[] public rewardTokens;
                          /**
                           * @notice Reward state for each reward token
                           */
                          mapping(address => RewardState) public rewardStates;
                          /**
                           * @notice Address of Farmer contract for specific reward tokens
                           */
                          mapping(address => address) public rewardFarmers;
                          /**
                           * @notice Last indexes for reward token from Farmer contracts
                           */
                          mapping(address => uint256) public farmerLastIndex;
                          /**
                           * @notice Address allowed to deposit reward tokens
                           */
                          mapping(address => bool) public rewardDepositors;
                          // Events
                          /**
                           * @notice Event emitted when staking
                           */
                          event Staked(address indexed caller, address indexed receiver, uint256 amount);
                          /**
                           * @notice Event emitted when unstaking
                           */
                          event Unstaked(address indexed owner, address indexed receiver, uint256 amount);
                          /**
                           * @notice Event emitted when rewards are claimed
                           */
                          event ClaimedRewards(address indexed reward, address indexed user, address indexed receiver, uint256 amount);
                          /**
                           * @notice Event emitted when a new Claimer is set for an user
                           */
                          event SetUserAllowedClaimer(address indexed user, address indexed claimer);
                          /**
                           * @notice Event emitted when a new reward is added
                           */
                          event NewRewards(address indexed rewardToken, uint256 amount, uint256 endTimestamp);
                          /**
                           * @notice Event emitted when a new reward depositor is added
                           */
                          event AddedRewardDepositor(address indexed depositor);
                          /**
                           * @notice Event emitted when a reward depositor is removed
                           */
                          event RemovedRewardDepositor(address indexed depositor);
                          event SetRewardFarmer(address indexed rewardToken, address indexed farmer);
                          // Modifiers
                          /**
                           * @notice Check that the caller is allowed to deposit rewards
                           */
                          modifier onlyRewardDepositors() {
                            if (!rewardDepositors[msg.sender]) revert Errors.CallerNotAllowed();
                            _;
                          }
                          // Constructor
                          constructor(address _warToken) ERC20("Staked Warlord token", "stkWAR") {
                            if (_warToken == address(0)) revert Errors.ZeroAddress();
                            warToken = _warToken;
                          }
                          // View functions
                          /**
                           * @notice Get the last update timestamp for a reward token
                           * @param reward Address of the reward token
                           * @return uint256 : Last update timestamp
                           */
                          function lastRewardUpdateTimestamp(address reward) public view returns (uint256) {
                            uint256 rewardEndTimestamp = rewardStates[reward].distributionEndTimestamp;
                            // If the distribution is already over, return the timestamp of the end of distribution
                            // to prevent from accruing rewards that do not exist
                            return block.timestamp > rewardEndTimestamp ? rewardEndTimestamp : block.timestamp;
                          }
                          /**
                           * @notice Get the list of all reward tokens
                           * @return address[] : List of reward tokens
                           */
                          function getRewardTokens() external view returns (address[] memory) {
                            return rewardTokens;
                          }
                          /**
                           * @notice Get the current reward state of an user for a given reward token
                           * @param reward Address of the reward token
                           * @param user Address of the user
                           * @return UserRewardState : User reward state
                           */
                          function getUserRewardState(address reward, address user) external view returns (UserRewardState memory) {
                            return rewardStates[reward].userStates[user];
                          }
                          /**
                           * @notice Get the current amount of rewards accrued by an user for a given reward token
                           * @param reward Address of the reward token
                           * @param user Address of the user
                           * @return uint256 : amount of rewards accrued
                           */
                          function getUserAccruedRewards(address reward, address user) external view returns (uint256) {
                            return rewardStates[reward].userStates[user].accruedRewards
                              + _getUserEarnedRewards(reward, user, _getNewRewardPerToken(reward));
                          }
                          /**
                           * @notice Get all current claimable amount of rewards for all reward tokens for a given user
                           * @param user Address of the user
                           * @return UserClaimableRewards[] : Amounts of rewards claimable by reward token
                           */
                          function getUserTotalClaimableRewards(address user) external view returns (UserClaimableRewards[] memory) {
                            address[] memory rewards = rewardTokens;
                            uint256 rewardsLength = rewards.length;
                            UserClaimableRewards[] memory rewardAmounts = new UserClaimableRewards[](rewardsLength);
                            // For each listed reward
                            for (uint256 i; i < rewardsLength;) {
                              // Add the reward token to the list
                              rewardAmounts[i].reward = rewards[i];
                              // And add the calculated claimable amount of the given reward
                              // Accrued rewards from previous stakes + accrued rewards from current stake
                              rewardAmounts[i].claimableAmount = rewardStates[rewards[i]].userStates[user].accruedRewards
                                + _getUserEarnedRewards(rewards[i], user, _getNewRewardPerToken(rewards[i]));
                              unchecked {
                                ++i;
                              }
                            }
                            return rewardAmounts;
                          }
                          // State-changing functions
                          // Can give MAX_UINT256 to stake full balance
                          /**
                           * @notice Stake WAR tokens
                           * @param amount Amount to stake
                           * @param receiver Address of the address to stake for
                           * @return uint256 : scaled amount for the deposit
                           */
                          function stake(uint256 amount, address receiver) external nonReentrant whenNotPaused returns (uint256) {
                            // If given MAX_UINT256, we want to deposit the full user balance
                            if (amount == MAX_UINT256) amount = IERC20(warToken).balanceOf(msg.sender);
                            if (amount == 0) revert Errors.ZeroValue();
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            // Pull the tokens from the user
                            IERC20(warToken).safeTransferFrom(msg.sender, address(this), amount);
                            // Mint the staked tokens
                            // It will also update the reward states for the user who's balance gonna change
                            _mint(receiver, amount);
                            emit Staked(msg.sender, receiver, amount);
                            return amount;
                          }
                          // Can give MAX_UINT256 to unstake full balance
                          /**
                           * @notice Unstake WAR tokens
                           * @param amount Amount to unstake
                           * @param receiver Address to receive the tokens
                           * @return uint256 : amount unstaked
                           */
                          function unstake(uint256 amount, address receiver) external nonReentrant returns (uint256) {
                            // If given MAX_UINT256, we want to withdraw the full user balance
                            if (amount == MAX_UINT256) amount = balanceOf(msg.sender);
                            if (amount == 0) revert Errors.ZeroValue();
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            // Burn the staked tokens
                            // It will also update the reward states for the user who's balance gonna change
                            _burn(msg.sender, amount);
                            // And send the tokens to the given receiver
                            IERC20(warToken).safeTransfer(receiver, amount);
                            emit Unstaked(msg.sender, receiver, amount);
                            return amount;
                          }
                          /**
                           * @notice Claim the accrued rewards for a given reward token
                           * @param reward Address of the reward token
                           * @param receiver Address to receive the rewards
                           * @return uint256 : Amount of rewards claimed
                           */
                          function claimRewards(address reward, address receiver) external nonReentrant whenNotPaused returns (uint256) {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            return _claimRewards(reward, msg.sender, receiver);
                          }
                          /**
                           * @notice Claim all accrued rewards for all reward tokens
                           * @param receiver Address to receive the rewards
                           * @return UserClaimedRewards[] : Amounts of reward claimed
                           */
                          function claimAllRewards(address receiver) external nonReentrant whenNotPaused returns (UserClaimedRewards[] memory) {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            return _claimAllRewards(msg.sender, receiver);
                          }
                          /**
                           * @notice Update the reward state for a given reward token
                           * @param reward Address of the reward token
                           */
                          function updateRewardState(address reward) external nonReentrant whenNotPaused {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            _updateRewardState(reward);
                          }
                          /**
                           * @notice Update the reward state for all reward tokens
                           */
                          function updateAllRewardStates() external nonReentrant whenNotPaused {
                            address[] memory _rewards = rewardTokens;
                            uint256 length = _rewards.length;
                            // For all reward token in the list, update the reward state
                            for (uint256 i; i < length;) {
                              _updateRewardState(_rewards[i]);
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          // Reward Managers functions
                          /**
                           * @notice Add rewards to the distribution queue
                           * @dev Set the amount of reward in the queue & push it to distribution if reaching the ratio
                           * @param rewardToken Address of the reward token
                           * @param amount Amount to queue
                           * @return bool : success
                           */
                          function queueRewards(address rewardToken, uint256 amount)
                            external
                            nonReentrant
                            whenNotPaused
                            onlyRewardDepositors
                            returns (bool)
                          {
                            if (amount == 0) revert Errors.ZeroValue();
                            if (rewardToken == address(0)) revert Errors.ZeroAddress();
                            RewardState storage state = rewardStates[rewardToken];
                            // If the given reward token is new (no previous distribution),
                            // add it to the reward list
                            if (state.lastUpdate == 0) {
                              rewardTokens.push(rewardToken);
                            }
                            // Update the reward token state before queueing new rewards
                            _updateRewardState(rewardToken);
                            // Get the total queued amount (previous queued amount + new amount)
                            uint256 totalQueued = amount + state.queuedRewardAmount;
                            // If there is no current distribution (previous is over or new reward token):
                            // Start the new distribution directly without queueing the rewards
                            if (block.timestamp >= state.distributionEndTimestamp) {
                              _updateRewardDistribution(rewardToken, state, totalQueued);
                              state.queuedRewardAmount = 0;
                              return true;
                            }
                            // Calculate the remaining duration for the current distribution
                            // and the ratio of queued rewards compared to total rewards (queued + remaining in current distribution)
                            // state.distributionEndTimestamp - block.timestamp => remaining time in the current distribution
                            uint256 currentRemainingAmount = state.ratePerSecond * (state.distributionEndTimestamp - block.timestamp);
                            uint256 queuedAmountRatio = (totalQueued * MAX_BPS) / (totalQueued + currentRemainingAmount);
                            // If 85% or more of the total rewards are queued, move them to distribution
                            if (queuedAmountRatio >= UPDATE_REWARD_RATIO) {
                              _updateRewardDistribution(rewardToken, state, totalQueued);
                              state.queuedRewardAmount = 0;
                            } else {
                              state.queuedRewardAmount = totalQueued;
                            }
                            return true;
                          }
                          /**
                           * @dev Update the distribution parameters for a given reward token
                           * @param rewardToken Address of the reward token
                           * @param state State of the reward token
                           * @param rewardAmount Total amount ot distribute
                           */
                          function _updateRewardDistribution(address rewardToken, RewardState storage state, uint256 rewardAmount) internal {
                            // Calculate the remaining duration of the current distribution (if not already over)
                            // to calculate the amount fo rewards not yet distributed, and add them to the new amount to distribute
                            if (block.timestamp < state.distributionEndTimestamp) {
                              uint256 remainingRewards = state.ratePerSecond * (state.distributionEndTimestamp - block.timestamp);
                              rewardAmount += remainingRewards;
                            }
                            // Calculate the new rate per second
                            // & update the storage for the new distribution state
                            state.ratePerSecond = rewardAmount / DISTRIBUTION_DURATION;
                            state.currentRewardAmount = rewardAmount;
                            state.lastUpdate = safe128(block.timestamp);
                            uint256 distributionEnd = block.timestamp + DISTRIBUTION_DURATION;
                            state.distributionEndTimestamp = safe128(distributionEnd);
                            emit NewRewards(rewardToken, rewardAmount, distributionEnd);
                          }
                          // Internal functions
                          function _beforeTokenTransfer(address from, address to, uint256 /*amount*/ ) internal override {
                            if (from != address(0)) {
                              _updateAllUserRewardStates(from);
                            }
                            if (to != address(0)) {
                              _updateAllUserRewardStates(to);
                            }
                          }
                          /**
                           * @dev Calculate the new rewardPerToken value for a reward token distribution
                           * @param reward Address of the reward token
                           * @return uint256 : new rewardPerToken value
                           */
                          function _getNewRewardPerToken(address reward) internal view returns (uint256) {
                            RewardState storage state = rewardStates[reward];
                            // If no funds are deposited, we don't want to distribute rewards
                            uint256 totalStakedAmount = totalSupply();
                            if (totalStakedAmount == 0) return state.rewardPerToken;
                            uint256 totalAccruedAmount;
                            if (rewardFarmers[reward] == address(0)) {
                              // Get the last update timestamp
                              uint256 lastRewardTimestamp = lastRewardUpdateTimestamp(reward);
                              if (state.lastUpdate == lastRewardTimestamp) return state.rewardPerToken;
                              totalAccruedAmount = (lastRewardTimestamp - state.lastUpdate) * state.ratePerSecond;
                            } else {
                              uint256 currentFarmerIndex = IFarmer(rewardFarmers[reward]).getCurrentIndex();
                              totalAccruedAmount = currentFarmerIndex - farmerLastIndex[reward];
                            }
                            // Calculate the increase since the last update
                            return state.rewardPerToken + ((totalAccruedAmount * UNIT) / totalStakedAmount);
                          }
                          /**
                           * @dev Calculate the amount of rewards accrued by an user since last update for a reward token
                           * @param reward Address of the reward token
                           * @param user Address of the user
                           * @return uint256 : Accrued rewards amount for the user
                           */
                          function _getUserEarnedRewards(address reward, address user, uint256 currentRewardPerToken)
                            internal
                            view
                            returns (uint256)
                          {
                            UserRewardState storage userState = rewardStates[reward].userStates[user];
                            // Get the user staked balance
                            uint256 userStakedAmount = balanceOf(user);
                            if (userStakedAmount == 0) return 0;
                            // If the user has a previous deposit (scaled balance is not null), calculate the
                            // earned rewards based on the increase of the rewardPerToken value
                            return (userStakedAmount * (currentRewardPerToken - userState.lastRewardPerToken)) / UNIT;
                          }
                          /**
                           * @dev Update the reward token distribution state
                           * @param reward Address of the reward token
                           */
                          function _updateRewardState(address reward) internal {
                            RewardState storage state = rewardStates[reward];
                            // Update the storage with the new reward state
                            state.rewardPerToken = _getNewRewardPerToken(reward);
                            state.lastUpdate = safe128(lastRewardUpdateTimestamp(reward));
                            if (rewardFarmers[reward] != address(0)) {
                              farmerLastIndex[reward] = IFarmer(rewardFarmers[reward]).getCurrentIndex();
                            }
                          }
                          /**
                           * @dev Update the user reward state for a given reward token
                           * @param reward Address of the reward token
                           * @param user Address of the user
                           */
                          function _updateUserRewardState(address reward, address user) internal {
                            // Update the reward token state before the user's state
                            _updateRewardState(reward);
                            UserRewardState storage userState = rewardStates[reward].userStates[user];
                            // Update the storage with the new reward state
                            uint256 currentRewardPerToken = rewardStates[reward].rewardPerToken;
                            userState.accruedRewards += _getUserEarnedRewards(reward, user, currentRewardPerToken);
                            userState.lastRewardPerToken = currentRewardPerToken;
                          }
                          /**
                           * @dev Update the reward state of the given user for all the reward tokens
                           * @param user Address of the user
                           */
                          function _updateAllUserRewardStates(address user) internal {
                            address[] memory _rewards = rewardTokens;
                            uint256 length = _rewards.length;
                            // For all reward token in the list, update the user's reward state
                            for (uint256 i; i < length;) {
                              _updateUserRewardState(_rewards[i], user);
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          /**
                           * @dev Claims rewards of an user for a given reward token and sends them to the receiver address
                           * @param reward Address of reward token
                           * @param user Address of the user
                           * @param receiver Address to receive the rewards
                           * @return uint256 : claimed amount
                           */
                          function _claimRewards(address reward, address user, address receiver) internal returns (uint256) {
                            // Update all user states to get all current claimable rewards
                            _updateUserRewardState(reward, user);
                            UserRewardState storage userState = rewardStates[reward].userStates[user];
                            // Fetch the amount of rewards accrued by the user
                            uint256 rewardAmount = userState.accruedRewards;
                            if (rewardAmount == 0) return 0;
                            // Reset user's accrued rewards
                            userState.accruedRewards = 0;
                            // If the user accrued rewards, send them to the given receiver
                            _sendRewards(reward, receiver, rewardAmount);
                            emit ClaimedRewards(reward, user, receiver, rewardAmount);
                            return rewardAmount;
                          }
                          /**
                           * @dev Claims all rewards of an user and sends them to the receiver address
                           * @param user Address of the user
                           * @param receiver Address to receive the rewards
                           * @return UserClaimedRewards[] : list of claimed rewards
                           */
                          function _claimAllRewards(address user, address receiver) internal returns (UserClaimedRewards[] memory) {
                            address[] memory rewards = rewardTokens;
                            uint256 rewardsLength = rewards.length;
                            UserClaimedRewards[] memory rewardAmounts = new UserClaimedRewards[](rewardsLength);
                            // Update all user states to get all current claimable rewards
                            _updateAllUserRewardStates(user);
                            // For each reward token in the reward list
                            for (uint256 i; i < rewardsLength;) {
                              UserRewardState storage userState = rewardStates[rewards[i]].userStates[user];
                              // Fetch the amount of rewards accrued by the user
                              uint256 rewardAmount = userState.accruedRewards;
                              // Track the claimed amount for the reward token
                              rewardAmounts[i].reward = rewards[i];
                              rewardAmounts[i].amount = rewardAmount;
                              // If the user accrued no rewards, skip
                              if (rewardAmount == 0) {
                                unchecked {
                                  ++i;
                                }
                                continue;
                              }
                              // Reset user's accrued rewards
                              userState.accruedRewards = 0;
                              // For each reward token, send the accrued rewards to the given receiver
                              _sendRewards(rewards[i], receiver, rewardAmount);
                              emit ClaimedRewards(rewards[i], user, receiver, rewardAmounts[i].amount);
                              unchecked {
                                ++i;
                              }
                            }
                            return rewardAmounts;
                          }
                          /**
                           * @dev Sends reward token to the given receiver. Send them from the Farmer for tokens listed with a Farmer contract
                           * @param token Address of the token
                           * @param receiver Address to receive the rewards
                           * @param amount Amount to send
                           */
                          function _sendRewards(address token, address receiver, uint256 amount) internal {
                            if (rewardFarmers[token] == address(0)) {
                              IERC20(token).safeTransfer(receiver, amount);
                            } else {
                              IFarmer(rewardFarmers[token]).sendTokens(receiver, amount);
                            }
                          }
                          // Admin functions
                          /**
                           * @notice Pause the contract
                           */
                          function pause() external onlyOwner {
                            _pause();
                          }
                          /**
                           * @notice Unpause the contract
                           */
                          function unpause() external onlyOwner {
                            _unpause();
                          }
                          /**
                           * @notice Add an address to the list of allowed reward depositors
                           * @param depositor Address to deposit rewards
                           */
                          function addRewardDepositor(address depositor) external onlyOwner {
                            if (depositor == address(0)) revert Errors.ZeroAddress();
                            if (rewardDepositors[depositor]) revert Errors.AlreadyListedDepositor();
                            rewardDepositors[depositor] = true;
                            emit AddedRewardDepositor(depositor);
                          }
                          /**
                           * @notice Remove an address from the list of allowed reward depositors
                           * @param depositor Address to deposit rewards
                           */
                          function removeRewardDepositor(address depositor) external onlyOwner {
                            if (depositor == address(0)) revert Errors.ZeroAddress();
                            if (!rewardDepositors[depositor]) revert Errors.NotListedDepositor();
                            rewardDepositors[depositor] = false;
                            emit RemovedRewardDepositor(depositor);
                          }
                          /**
                           * @notice Add an Farmer contract for a reward token
                           * @param rewardToken Address of the reward token
                           * @param farmer Address of the Farmer contract
                           */
                          function setRewardFarmer(address rewardToken, address farmer) external onlyOwner {
                            if (rewardToken == address(0) || farmer == address(0)) revert Errors.ZeroAddress();
                            address expectedToken = IFarmer(farmer).token();
                            if (rewardToken != expectedToken) revert Errors.MismatchingFarmer();
                            rewardFarmers[rewardToken] = farmer;
                            rewardTokens.push(rewardToken);
                            emit SetRewardFarmer(rewardToken, farmer);
                          }
                          // Maths
                          function safe128(uint256 n) internal pure returns (uint128) {
                            if (n > type(uint128).max) revert Errors.NumberExceed128Bits();
                            return uint128(n);
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IFarmer {
                          // the index stored by the farmer represents all the recevied tokens
                          function getCurrentIndex() external view returns (uint256);
                          function sendTokens(address receiver, uint256 amount) external;
                          function stake(address token, uint256 amount) external;
                          function token() external view returns (address);
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.6.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.8.0) (token/ERC20/utils/SafeERC20.sol)
                        pragma solidity ^0.8.0;
                        import "../IERC20.sol";
                        import "../extensions/draft-IERC20Permit.sol";
                        import "../../../utils/Address.sol";
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using Address for address;
                            function safeTransfer(
                                IERC20 token,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(
                                IERC20 token,
                                address from,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                require(
                                    (value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                uint256 newAllowance = token.allowance(address(this), spender) + value;
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                unchecked {
                                    uint256 oldAllowance = token.allowance(address(this), spender);
                                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                    uint256 newAllowance = oldAllowance - value;
                                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                }
                            }
                            function safePermit(
                                IERC20Permit token,
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                uint256 nonceBefore = token.nonces(owner);
                                token.permit(owner, spender, value, deadline, v, r, s);
                                uint256 nonceAfter = token.nonces(owner);
                                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) {
                                    // Return data is optional
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.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].
                         *
                         * 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}.
                             *
                             * The default value of {decimals} is 18. To select a different value for
                             * {decimals} you should overload it.
                             *
                             * 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 value {ERC20} uses, unless this function is
                             * 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.7.0) (security/Pausable.sol)
                        pragma solidity ^0.8.0;
                        import "../utils/Context.sol";
                        /**
                         * @dev Contract module which allows children to implement an emergency stop
                         * mechanism that can be triggered by an authorized account.
                         *
                         * This module is used through inheritance. It will make available the
                         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                         * the functions of your contract. Note that they will not be pausable by
                         * simply including this module, only once the modifiers are put in place.
                         */
                        abstract contract Pausable is Context {
                            /**
                             * @dev Emitted when the pause is triggered by `account`.
                             */
                            event Paused(address account);
                            /**
                             * @dev Emitted when the pause is lifted by `account`.
                             */
                            event Unpaused(address account);
                            bool private _paused;
                            /**
                             * @dev Initializes the contract in unpaused state.
                             */
                            constructor() {
                                _paused = false;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is not paused.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            modifier whenNotPaused() {
                                _requireNotPaused();
                                _;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is paused.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            modifier whenPaused() {
                                _requirePaused();
                                _;
                            }
                            /**
                             * @dev Returns true if the contract is paused, and false otherwise.
                             */
                            function paused() public view virtual returns (bool) {
                                return _paused;
                            }
                            /**
                             * @dev Throws if the contract is paused.
                             */
                            function _requireNotPaused() internal view virtual {
                                require(!paused(), "Pausable: paused");
                            }
                            /**
                             * @dev Throws if the contract is not paused.
                             */
                            function _requirePaused() internal view virtual {
                                require(paused(), "Pausable: not paused");
                            }
                            /**
                             * @dev Triggers stopped state.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            function _pause() internal virtual whenNotPaused {
                                _paused = true;
                                emit Paused(_msgSender());
                            }
                            /**
                             * @dev Returns to normal state.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            function _unpause() internal virtual whenPaused {
                                _paused = false;
                                emit Unpaused(_msgSender());
                            }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.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;
                            }
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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
                        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @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 IERC20Permit {
                            /**
                             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                             * given ``owner``'s signed approval.
                             *
                             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                             * ordering also apply here.
                             *
                             * 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}).
                             *
                             * For more information on the signature format, see the
                             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                             * section].
                             */
                            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);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
                        pragma solidity ^0.8.1;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             *
                             * [IMPORTANT]
                             * ====
                             * You shouldn't rely on `isContract` to protect against flash loan attacks!
                             *
                             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                             * constructor.
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize/address.code.length, which returns 0
                                // for contracts in construction, since the code is only stored at the end
                                // of the constructor execution.
                                return account.code.length > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                (bool success, ) = recipient.call{value: amount}("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain `call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                (bool success, bytes memory returndata) = target.call{value: value}(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                             *
                             * _Available since v4.8._
                             */
                            function verifyCallResultFromTarget(
                                address target,
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                if (success) {
                                    if (returndata.length == 0) {
                                        // only check isContract if the call was successful and the return data is empty
                                        // otherwise we already know that it was a contract
                                        require(isContract(target), "Address: call to non-contract");
                                    }
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            /**
                             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                             * revert reason or using the provided one.
                             *
                             * _Available since v4.3._
                             */
                            function verifyCallResult(
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal pure returns (bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                        // 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 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;
                            }
                        }
                        

                        File 11 of 18: AugustusSwapper
                        // File: openzeppelin-solidity/contracts/utils/EnumerableSet.sol
                        pragma solidity >=0.6.0 <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.
                         *
                         * ```
                         * 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.
                         */
                        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;
                                    // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                    // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                                    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] = toDeleteIndex + 1; // All indexes are 1-based
                                    // 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) {
                                require(set._values.length > index, "EnumerableSet: index out of bounds");
                                return set._values[index];
                            }
                            // 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);
                            }
                            // 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(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(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(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(uint256(_at(set._inner, index)));
                            }
                            // 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 on 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));
                            }
                        }
                        // File: openzeppelin-solidity/contracts/utils/Address.sol
                        pragma solidity >=0.6.2 <0.8.0;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        // File: openzeppelin-solidity/contracts/GSN/Context.sol
                        pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                return msg.sender;
                            }
                            function _msgData() internal view virtual returns (bytes memory) {
                                this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                return msg.data;
                            }
                        }
                        // File: openzeppelin-solidity/contracts/access/AccessControl.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @dev Contract module that allows children to implement role-based access
                         * control mechanisms.
                         *
                         * Roles are referred to by their `bytes32` identifier. These should be exposed
                         * in the external API and be unique. The best way to achieve this is by
                         * using `public constant` hash digests:
                         *
                         * ```
                         * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                         * ```
                         *
                         * Roles can be used to represent a set of permissions. To restrict access to a
                         * function call, use {hasRole}:
                         *
                         * ```
                         * function foo() public {
                         *     require(hasRole(MY_ROLE, msg.sender));
                         *     ...
                         * }
                         * ```
                         *
                         * Roles can be granted and revoked dynamically via the {grantRole} and
                         * {revokeRole} functions. Each role has an associated admin role, and only
                         * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                         *
                         * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                         * that only accounts with this role will be able to grant or revoke other
                         * roles. More complex role relationships can be created by using
                         * {_setRoleAdmin}.
                         *
                         * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                         * grant and revoke this role. Extra precautions should be taken to secure
                         * accounts that have been granted it.
                         */
                        abstract contract AccessControl is Context {
                            using EnumerableSet for EnumerableSet.AddressSet;
                            using Address for address;
                            struct RoleData {
                                EnumerableSet.AddressSet members;
                                bytes32 adminRole;
                            }
                            mapping (bytes32 => RoleData) private _roles;
                            bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                            /**
                             * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                             *
                             * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                             * {RoleAdminChanged} not being emitted signaling this.
                             *
                             * _Available since v3.1._
                             */
                            event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                            /**
                             * @dev Emitted when `account` is granted `role`.
                             *
                             * `sender` is the account that originated the contract call, an admin role
                             * bearer except when using {_setupRole}.
                             */
                            event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Emitted when `account` is revoked `role`.
                             *
                             * `sender` is the account that originated the contract call:
                             *   - if using `revokeRole`, it is the admin role bearer
                             *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                             */
                            event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) public view returns (bool) {
                                return _roles[role].members.contains(account);
                            }
                            /**
                             * @dev Returns the number of accounts that have `role`. Can be used
                             * together with {getRoleMember} to enumerate all bearers of a role.
                             */
                            function getRoleMemberCount(bytes32 role) public view returns (uint256) {
                                return _roles[role].members.length();
                            }
                            /**
                             * @dev Returns one of the accounts that have `role`. `index` must be a
                             * value between 0 and {getRoleMemberCount}, non-inclusive.
                             *
                             * Role bearers are not sorted in any particular way, and their ordering may
                             * change at any point.
                             *
                             * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                             * you perform all queries on the same block. See the following
                             * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                             * for more information.
                             */
                            function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
                                return _roles[role].members.at(index);
                            }
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) public view returns (bytes32) {
                                return _roles[role].adminRole;
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function grantRole(bytes32 role, address account) public virtual {
                                require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function revokeRole(bytes32 role, address account) public virtual {
                                require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been granted `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             */
                            function renounceRole(bytes32 role, address account) public virtual {
                                require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                                _revokeRole(role, account);
                            }
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event. Note that unlike {grantRole}, this function doesn't perform any
                             * checks on the calling account.
                             *
                             * [WARNING]
                             * ====
                             * This function should only be called from the constructor when setting
                             * up the initial roles for the system.
                             *
                             * Using this function in any other way is effectively circumventing the admin
                             * system imposed by {AccessControl}.
                             * ====
                             */
                            function _setupRole(bytes32 role, address account) internal virtual {
                                _grantRole(role, account);
                            }
                            /**
                             * @dev Sets `adminRole` as ``role``'s admin role.
                             *
                             * Emits a {RoleAdminChanged} event.
                             */
                            function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
                                _roles[role].adminRole = adminRole;
                            }
                            function _grantRole(bytes32 role, address account) private {
                                if (_roles[role].members.add(account)) {
                                    emit RoleGranted(role, account, _msgSender());
                                }
                            }
                            function _revokeRole(bytes32 role, address account) private {
                                if (_roles[role].members.remove(account)) {
                                    emit RoleRevoked(role, account, _msgSender());
                                }
                            }
                        }
                        // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                return sub(a, b, "SafeMath: subtraction overflow");
                            }
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                uint256 c = a - b;
                                return c;
                            }
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot 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-contracts/pull/522
                                if (a == 0) {
                                    return 0;
                                }
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                return div(a, b, "SafeMath: division by zero");
                            }
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                uint256 c = a / b;
                                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                return c;
                            }
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                return mod(a, b, "SafeMath: modulo by zero");
                            }
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts with custom message when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b != 0, errorMessage);
                                return a % b;
                            }
                        }
                        // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        // File: original_contracts/routers/IRouter.sol
                        pragma solidity 0.7.5;
                        interface IRouter {
                            /**
                            * @dev Certain routers/exchanges needs to be initialized.
                            * This method will be called from Augustus
                            */
                            function initialize(bytes calldata data) external;
                            /**
                            * @dev Returns unique identifier for the router
                            */
                            function getKey() external pure returns(bytes32);
                            event Swapped(
                                bytes16 uuid,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount,
                                uint256 expectedAmount
                            );
                            event Bought(
                                bytes16 uuid,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount
                            );
                            event FeeTaken(
                                uint256 fee,
                                uint256 partnerShare,
                                uint256 paraswapShare
                            );
                        }
                        // File: original_contracts/ITokenTransferProxy.sol
                        pragma solidity 0.7.5;
                        interface ITokenTransferProxy {
                            function transferFrom(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                external;
                        }
                        // File: original_contracts/lib/Utils.sol
                        pragma solidity 0.7.5;
                        pragma experimental ABIEncoderV2;
                        interface IERC20Permit {
                            function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                        }
                        library Utils {
                            using SafeMath for uint256;
                            using SafeERC20 for IERC20;
                            address constant ETH_ADDRESS = address(
                                0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                            );
                            
                            uint256 constant MAX_UINT = type(uint256).max;
                            /**
                           * @param fromToken Address of the source token
                           * @param fromAmount Amount of source tokens to be swapped
                           * @param toAmount Minimum destination token amount expected out of this swap
                           * @param expectedAmount Expected amount of destination tokens without slippage
                           * @param beneficiary Beneficiary address
                           * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                           * @param path Route to be taken for this swap to take place
                           */
                            struct SellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.Path[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct MegaSwapSellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.MegaSwapPath[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct SimpleData {
                                address fromToken;
                                address toToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address[] callees;
                                bytes exchangeData;
                                uint256[] startIndexes;
                                uint256[] values;
                                address payable beneficiary;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct Adapter {
                                address payable adapter;
                                uint256 percent;
                                uint256 networkFee;
                                Route[] route;
                            }
                            struct Route {
                                uint256 index;//Adapter at which index needs to be used
                                address targetExchange;
                                uint percent;
                                bytes payload;
                                uint256 networkFee;//Network fee is associated with 0xv3 trades
                            }
                            struct MegaSwapPath {
                                uint256 fromAmountPercent;
                                Path[] path;
                            }
                            struct Path {
                                address to;
                                uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
                                Adapter[] adapters;
                            }
                            function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                            function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                            function approve(
                                address addressToApprove,
                                address token,
                                uint256 amount
                            ) internal {
                                if (token != ETH_ADDRESS) {
                                    IERC20 _token = IERC20(token);
                                    uint allowance = _token.allowance(address(this), addressToApprove);
                                    if (allowance < amount) {
                                        _token.safeApprove(addressToApprove, 0);
                                        _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                    }
                                }
                            }
                            function transferTokens(
                                address token,
                                address payable destination,
                                uint256 amount
                            )
                            internal
                            {
                                if (amount > 0) {
                                    if (token == ETH_ADDRESS) {
                                        (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                        require(result, "Failed to transfer Ether");
                                    }
                                    else {
                                        IERC20(token).safeTransfer(destination, amount);
                                    }
                                }
                            }
                            function tokenBalance(
                                address token,
                                address account
                            )
                            internal
                            view
                            returns (uint256)
                            {
                                if (token == ETH_ADDRESS) {
                                    return account.balance;
                                } else {
                                    return IERC20(token).balanceOf(account);
                                }
                            }
                            function permit(
                                address token,
                                bytes memory permit
                            )
                                internal
                            {
                                if (permit.length == 32 * 7) {
                                    (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                    require(success, "Permit failed");
                                }
                            }
                        }
                        // File: original_contracts/adapters/IAdapter.sol
                        pragma solidity 0.7.5;
                        interface IAdapter {
                            /**
                            * @dev Certain adapters needs to be initialized.
                            * This method will be called from Augustus
                            */
                            function initialize(bytes calldata data) external;
                            /**
                           * @dev The function which performs the swap on an exchange.
                           * @param fromToken Address of the source token
                           * @param toToken Address of the destination token
                           * @param fromAmount Amount of source tokens to be swapped
                           * @param networkFee Network fee to be used in this router
                           * @param route Route to be followed
                           */
                            function swap(
                                IERC20 fromToken,
                                IERC20 toToken,
                                uint256 fromAmount,
                                uint256 networkFee,
                                Utils.Route[] calldata route
                            )
                                external
                                payable;
                        }
                        // File: openzeppelin-solidity/contracts/access/Ownable.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @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 () internal {
                                address msgSender = _msgSender();
                                _owner = msgSender;
                                emit OwnershipTransferred(address(0), msgSender);
                            }
                            /**
                             * @dev Returns the address of the current owner.
                             */
                            function owner() public view returns (address) {
                                return _owner;
                            }
                            /**
                             * @dev Throws if called by any account other than the owner.
                             */
                            modifier onlyOwner() {
                                require(_owner == _msgSender(), "Ownable: caller is not the owner");
                                _;
                            }
                            /**
                             * @dev Leaves the contract without owner. It will not be possible to call
                             * `onlyOwner` functions anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing any functionality that is only available to the owner.
                             */
                            function renounceOwnership() public virtual onlyOwner {
                                emit OwnershipTransferred(_owner, address(0));
                                _owner = 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");
                                emit OwnershipTransferred(_owner, newOwner);
                                _owner = newOwner;
                            }
                        }
                        // File: original_contracts/TokenTransferProxy.sol
                        pragma solidity 0.7.5;
                        /**
                        * @dev Allows owner of the contract to transfer tokens on behalf of user.
                        * User will need to approve this contract to spend tokens on his/her behalf
                        * on Paraswap platform
                        */
                        contract TokenTransferProxy is Ownable, ITokenTransferProxy {
                            using SafeERC20 for IERC20;
                            using Address for address;
                            /**
                            * @dev Allows owner of the contract to transfer tokens on user's behalf
                            * @dev Swapper contract will be the owner of this contract
                            * @param token Address of the token
                            * @param from Address from which tokens will be transferred
                            * @param to Receipent address of the tokens
                            * @param amount Amount of tokens to transfer
                            */
                            function transferFrom(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                external
                                override
                                onlyOwner
                            {   
                                require(
                                    from == tx.origin ||
                                    from.isContract(),
                                    "Invalid from address"
                                );
                                
                                IERC20(token).safeTransferFrom(from, to, amount);
                            }
                        }
                        // File: original_contracts/AugustusStorage.sol
                        pragma solidity 0.7.5;
                        contract AugustusStorage {
                            struct FeeStructure {
                                uint256 partnerShare;
                                bool noPositiveSlippage;
                                bool positiveSlippageToUser;
                                uint16 feePercent;
                                string partnerId;
                                bytes data;
                            }
                            ITokenTransferProxy internal tokenTransferProxy;
                            address payable internal feeWallet;
                            
                            mapping(address => FeeStructure) internal registeredPartners;
                            mapping (bytes4 => address) internal selectorVsRouter;
                            mapping (bytes32 => bool) internal adapterInitialized;
                            mapping (bytes32 => bytes) internal adapterVsData;
                            mapping (bytes32 => bytes) internal routerData;
                            mapping (bytes32 => bool) internal routerInitialized;
                            bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                            bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                        }
                        // File: original_contracts/AugustusSwapper.sol
                        pragma solidity 0.7.5;
                        contract AugustusSwapper is AugustusStorage, AccessControl {
                            using SafeMath for uint256;
                            using SafeERC20 for IERC20;
                            event AdapterInitialized(address indexed adapter);
                            event RouterInitialized(address indexed router);
                            /**
                             * @dev Throws if called by any account other than the admin.
                             */
                            modifier onlyAdmin() {
                                require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "caller is not the admin");
                                _;
                            }
                            constructor(address payable _feeWallet) public {
                                TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy();
                                tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);
                                feeWallet = _feeWallet;
                                _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
                            }
                            
                            receive () payable external {
                            }
                            fallback() external payable {
                                bytes4 selector = msg.sig;
                                //Figure out the router contract for the given function
                                address implementation = getImplementation(selector);
                                if (implementation == address(0)) {
                                    _revertWithData(
                                        abi.encodeWithSelector(
                                            bytes4(keccak256("NotImplementedError(bytes4)")),
                                            selector
                                        )
                                    );
                                }
                                //Delegate call to the router
                                (bool success, bytes memory resultData) = implementation.delegatecall(msg.data);
                                if (!success) {
                                    _revertWithData(resultData);
                                }
                                _returnWithData(resultData);
                            }
                            function initializeAdapter(address adapter, bytes calldata data) external onlyAdmin {
                                require(
                                    hasRole(WHITELISTED_ROLE, adapter),
                                    "Exchange not whitelisted"
                                );
                                (bool success,) = adapter.delegatecall(abi.encodeWithSelector(IAdapter.initialize.selector, data));
                                require(success, "Failed to initialize adapter");
                                emit AdapterInitialized(adapter);
                            }
                            function initializeRouter(address router, bytes calldata data) external onlyAdmin {
                                require(
                                    hasRole(ROUTER_ROLE, router),
                                    "Router not whitelisted"
                                );
                                (bool success,) = router.delegatecall(abi.encodeWithSelector(IRouter.initialize.selector, data));
                                require(success, "Failed to initialize router");
                                emit RouterInitialized(router);
                            } 
                            
                            function getImplementation(bytes4 selector) public view returns(address) {
                                return selectorVsRouter[selector];
                            }
                            function getVersion() external pure returns(string memory) {
                                return "5.0.0";
                            }
                            function getPartnerFeeStructure(address partner) public view returns (FeeStructure memory) {
                                return registeredPartners[partner];
                            }
                            function getFeeWallet() external view returns(address) {
                                return feeWallet;
                            }
                            function setFeeWallet(address payable _feeWallet) external onlyAdmin {
                                require(_feeWallet != address(0), "Invalid address");
                                feeWallet = _feeWallet;
                            }
                            function registerPartner(
                                address partner,
                                uint256 _partnerShare,
                                bool _noPositiveSlippage,
                                bool _positiveSlippageToUser,
                                uint16 _feePercent,
                                string calldata partnerId,
                                bytes calldata _data
                            )
                                external
                                onlyAdmin
                            {   
                                require(partner != address(0), "Invalid partner");
                                FeeStructure storage feeStructure = registeredPartners[partner];
                                require(feeStructure.partnerShare == 0, "Already registered");
                                require(_partnerShare > 0 && _partnerShare < 10000, "Invalid values");
                                require(_feePercent <= 10000, "Invalid values");
                                feeStructure.partnerShare = _partnerShare;
                                feeStructure.noPositiveSlippage = _noPositiveSlippage;
                                feeStructure.positiveSlippageToUser = _positiveSlippageToUser;
                                feeStructure.partnerId = partnerId;
                                feeStructure.feePercent = _feePercent;
                                feeStructure.data = _data;
                            }
                            function setImplementation(bytes4 selector, address implementation) external onlyAdmin {
                                require(
                                    hasRole(ROUTER_ROLE, implementation),
                                    "Router is not whitelisted"
                                );
                                selectorVsRouter[selector] = implementation;
                            }
                            /**
                            * @dev Allows admin of the contract to transfer any tokens which are assigned to the contract
                            * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake
                            * @dev token Address of the token to be transferred
                            * @dev destination Recepient of the token
                            * @dev amount Amount of tokens to be transferred
                            */
                            function transferTokens(
                                address token,
                                address payable destination,
                                uint256 amount
                            )
                                external
                                onlyAdmin
                            {
                                if (amount > 0) {
                                    if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
                                        (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                        require(result, "Failed to transfer Ether");
                                    }
                                    else {
                                        IERC20(token).safeTransfer(destination, amount);
                                    }
                                }
                            }
                              function isAdapterInitialized(bytes32 key) public view returns(bool) {
                                return adapterInitialized[key];
                            }
                            function getAdapterData(bytes32 key) public view returns(bytes memory) {
                                return adapterVsData[key];
                            }
                            function isRouterInitialized(bytes32 key) public view returns (bool) {
                                return routerInitialized[key];
                            }
                            function getRouterData(bytes32 key) public view returns (bytes memory) {
                                return routerData[key];
                            }
                            function getTokenTransferProxy() public view returns (address) {
                                return address(tokenTransferProxy);
                            }
                            function _revertWithData(bytes memory data) private pure {
                                assembly { revert(add(data, 32), mload(data)) }
                            }
                            function _returnWithData(bytes memory data) private pure {
                                assembly { return(add(data, 32), mload(data)) }
                            }
                        }
                        

                        File 12 of 18: NewUniswapV2Router
                        // File: original_contracts/ITokenTransferProxy.sol
                        pragma solidity 0.7.5;
                        interface ITokenTransferProxy {
                            function transferFrom(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                external;
                        }
                        // File: original_contracts/AugustusStorage.sol
                        pragma solidity 0.7.5;
                        contract AugustusStorage {
                            struct FeeStructure {
                                uint256 partnerShare;
                                bool noPositiveSlippage;
                                bool positiveSlippageToUser;
                                uint16 feePercent;
                                string partnerId;
                                bytes data;
                            }
                            ITokenTransferProxy internal tokenTransferProxy;
                            address payable internal feeWallet;
                            
                            mapping(address => FeeStructure) internal registeredPartners;
                            mapping (bytes4 => address) internal selectorVsRouter;
                            mapping (bytes32 => bool) internal adapterInitialized;
                            mapping (bytes32 => bytes) internal adapterVsData;
                            mapping (bytes32 => bytes) internal routerData;
                            mapping (bytes32 => bool) internal routerInitialized;
                            bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                            bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                        }
                        // File: original_contracts/routers/IRouter.sol
                        pragma solidity 0.7.5;
                        interface IRouter {
                            /**
                            * @dev Certain routers/exchanges needs to be initialized.
                            * This method will be called from Augustus
                            */
                            function initialize(bytes calldata data) external;
                            /**
                            * @dev Returns unique identifier for the router
                            */
                            function getKey() external pure returns(bytes32);
                            event Swapped2(
                                bytes16 uuid,
                                address partner,
                                uint256 feePercent,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount,
                                uint256 expectedAmount
                            );
                            event Bought2(
                                bytes16 uuid,
                                address partner,
                                uint256 feePercent,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount
                            );
                        }
                        // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        // File: original_contracts/lib/weth/IWETH.sol
                        pragma solidity 0.7.5;
                        abstract contract IWETH is IERC20 {
                            function deposit() external virtual payable;
                            function withdraw(uint256 amount) external virtual;
                        }
                        // File: original_contracts/lib/uniswapv2/IUniswapV2Pair.sol
                        pragma solidity 0.7.5;
                        interface IUniswapV2Pair {
                            function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                            function swap(
                                uint amount0Out,
                                uint amount1Out,
                                address to,
                                bytes calldata data
                            )
                                external;
                        }
                        // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                return sub(a, b, "SafeMath: subtraction overflow");
                            }
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                uint256 c = a - b;
                                return c;
                            }
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot 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-contracts/pull/522
                                if (a == 0) {
                                    return 0;
                                }
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                return div(a, b, "SafeMath: division by zero");
                            }
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                uint256 c = a / b;
                                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                return c;
                            }
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                return mod(a, b, "SafeMath: modulo by zero");
                            }
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts with custom message when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b != 0, errorMessage);
                                return a % b;
                            }
                        }
                        // File: original_contracts/lib/uniswapv2/NewUniswapV2Lib.sol
                        pragma solidity 0.7.5;
                        library NewUniswapV2Lib {
                            using SafeMath for uint256;
                            function getReservesByPair(
                                address pair,
                                bool direction
                            )
                                internal
                                view
                                returns (uint256 reserveIn, uint256 reserveOut)
                            {
                                (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pair).getReserves();
                                (reserveIn, reserveOut) = direction ? (reserve0, reserve1) : (reserve1, reserve0);
                            }
                            function getAmountOut(
                                uint256 amountIn,
                                address pair,
                                bool direction,
                                uint256 fee
                            )
                                internal
                                view
                                returns (uint256 amountOut)
                            {
                                require(amountIn > 0, "UniswapV2Lib: INSUFFICIENT_INPUT_AMOUNT");
                                (uint256 reserveIn, uint256 reserveOut) = getReservesByPair(pair, direction);
                                uint256 amountInWithFee = amountIn.mul(fee);
                                uint256 numerator = amountInWithFee.mul(reserveOut);
                                uint256 denominator = reserveIn.mul(10000).add(amountInWithFee);
                                amountOut = uint256(numerator / denominator);
                            }
                            function getAmountIn(
                                uint256 amountOut,
                                address pair,
                                bool direction,
                                uint256 fee
                            )
                                internal
                                view
                                returns (uint256 amountIn)
                            {
                                require(amountOut > 0, "UniswapV2Lib: INSUFFICIENT_OUTPUT_AMOUNT");
                                (uint256 reserveIn, uint256 reserveOut) = getReservesByPair(pair, direction);
                                require(reserveOut > amountOut, "UniswapV2Lib: reserveOut should be greater than amountOut");
                                uint256 numerator = reserveIn.mul(amountOut).mul(10000);
                                uint256 denominator = reserveOut.sub(amountOut).mul(fee);
                                amountIn = (numerator / denominator).add(1);
                            }
                        }
                        // File: openzeppelin-solidity/contracts/utils/Address.sol
                        pragma solidity >=0.6.2 <0.8.0;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        // File: original_contracts/lib/Utils.sol
                        pragma solidity 0.7.5;
                        pragma experimental ABIEncoderV2;
                        interface IERC20Permit {
                            function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                        }
                        interface IERC20PermitLegacy {
                            function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
                        }
                        library Utils {
                            using SafeMath for uint256;
                            using SafeERC20 for IERC20;
                            address constant ETH_ADDRESS = address(
                                0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                            );
                            
                            uint256 constant MAX_UINT = type(uint256).max;
                            /**
                           * @param fromToken Address of the source token
                           * @param fromAmount Amount of source tokens to be swapped
                           * @param toAmount Minimum destination token amount expected out of this swap
                           * @param expectedAmount Expected amount of destination tokens without slippage
                           * @param beneficiary Beneficiary address
                           * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                           * @param path Route to be taken for this swap to take place
                           */
                            struct SellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.Path[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct BuyData {
                                address adapter;
                                address fromToken;
                                address toToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                address payable beneficiary;
                                Utils.Route[] route;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct MegaSwapSellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.MegaSwapPath[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct SimpleData {
                                address fromToken;
                                address toToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address[] callees;
                                bytes exchangeData;
                                uint256[] startIndexes;
                                uint256[] values;
                                address payable beneficiary;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                            struct Adapter {
                                address payable adapter;
                                uint256 percent;
                                uint256 networkFee;//NOT USED
                                Route[] route;
                            }
                            struct Route {
                                uint256 index;//Adapter at which index needs to be used
                                address targetExchange;
                                uint percent;
                                bytes payload;
                                uint256 networkFee;//NOT USED - Network fee is associated with 0xv3 trades
                            }
                            struct MegaSwapPath {
                                uint256 fromAmountPercent;
                                Path[] path;
                            }
                            struct Path {
                                address to;
                                uint256 totalNetworkFee;//NOT USED - Network fee is associated with 0xv3 trades
                                Adapter[] adapters;
                            }
                            function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                            function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                            function approve(
                                address addressToApprove,
                                address token,
                                uint256 amount
                            ) internal {
                                if (token != ETH_ADDRESS) {
                                    IERC20 _token = IERC20(token);
                                    uint allowance = _token.allowance(address(this), addressToApprove);
                                    if (allowance < amount) {
                                        _token.safeApprove(addressToApprove, 0);
                                        _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                    }
                                }
                            }
                            function transferTokens(
                                address token,
                                address payable destination,
                                uint256 amount
                            )
                            internal
                            {
                                if (amount > 0) {
                                    if (token == ETH_ADDRESS) {
                                        (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                        require(result, "Failed to transfer Ether");
                                    }
                                    else {
                                        IERC20(token).safeTransfer(destination, amount);
                                    }
                                }
                            }
                            function tokenBalance(
                                address token,
                                address account
                            )
                            internal
                            view
                            returns (uint256)
                            {
                                if (token == ETH_ADDRESS) {
                                    return account.balance;
                                } else {
                                    return IERC20(token).balanceOf(account);
                                }
                            }
                            function permit(
                                address token,
                                bytes memory permit
                            )
                                internal
                            {
                                if (permit.length == 32 * 7) {
                                    (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                    require(success, "Permit failed");
                                }
                                if (permit.length == 32 * 8) {
                                    (bool success,) = token.call(abi.encodePacked(IERC20PermitLegacy.permit.selector, permit));
                                    require(success, "Permit failed");
                                }
                            }
                        }
                        // File: @uniswap/lib/contracts/libraries/TransferHelper.sol
                        pragma solidity >=0.6.0;
                        // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                        library TransferHelper {
                            function safeApprove(address token, address to, uint value) internal {
                                // bytes4(keccak256(bytes('approve(address,uint256)')));
                                (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                                require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
                            }
                            function safeTransfer(address token, address to, uint value) internal {
                                // bytes4(keccak256(bytes('transfer(address,uint256)')));
                                (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                                require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
                            }
                            function safeTransferFrom(address token, address from, address to, uint value) internal {
                                // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                                (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                                require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
                            }
                            function safeTransferETH(address to, uint value) internal {
                                (bool success,) = to.call{value:value}(new bytes(0));
                                require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
                            }
                        }
                        // File: original_contracts/routers/NewUniswapV2Router.sol
                        pragma solidity 0.7.5;
                        contract NewUniswapV2Router is AugustusStorage, IRouter {
                            using SafeMath for uint256;
                            address constant ETH_IDENTIFIER = address(
                                0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                            );
                            // Pool bits are 255-161: fee, 160: direction flag, 159-0: address
                            uint256 constant FEE_OFFSET = 161;
                            uint256 constant DIRECTION_FLAG =
                                0x0000000000000000000000010000000000000000000000000000000000000000;
                            
                            function initialize(bytes calldata data) override external {
                                revert("METHOD NOT IMPLEMENTED");
                            }
                            function getKey() override external pure returns(bytes32) {
                                return keccak256(abi.encodePacked("UNISWAP_DIRECT_ROUTER", "2.0.0"));
                            }
                            function swapOnUniswapV2Fork(
                                address tokenIn,
                                uint256 amountIn,
                                uint256 amountOutMin,
                                address weth,
                                uint256[] calldata pools
                            )
                                external
                                payable
                            {
                                _swap(
                                    tokenIn,
                                    amountIn,
                                    amountOutMin,
                                    weth,
                                    pools
                                );
                            }
                            function buyOnUniswapV2Fork(
                                address tokenIn,
                                uint256 amountInMax,
                                uint256 amountOut,
                                address weth,
                                uint256[] calldata pools
                            )
                                external
                                payable
                            {
                                _buy(
                                    tokenIn,
                                    amountInMax,
                                    amountOut,
                                    weth,
                                    pools
                                );
                            }
                            function swapOnUniswapV2ForkWithPermit(
                                address tokenIn,
                                uint256 amountIn,
                                uint256 amountOutMin,
                                address weth,
                                uint256[] calldata pools,
                                bytes calldata permit
                            )
                                external
                                payable
                            {
                                _swapWithPermit(
                                    tokenIn,
                                    amountIn,
                                    amountOutMin,
                                    weth,
                                    pools,
                                    permit
                                );
                            }
                            function buyOnUniswapV2ForkWithPermit(
                                address tokenIn,
                                uint256 amountInMax,
                                uint256 amountOut,
                                address weth,
                                uint256[] calldata pools,
                                bytes calldata permit
                            )
                                external
                                payable
                            {
                                _buyWithPermit(
                                    tokenIn,
                                    amountInMax,
                                    amountOut,
                                    weth,
                                    pools,
                                    permit
                                );
                            }
                            function transferTokens(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                private
                            {
                                ITokenTransferProxy(tokenTransferProxy).transferFrom(
                                    token, from, to, amount
                                );
                            }
                            function transferTokensWithPermit(
                                address token,
                                address from,
                                address to,
                                uint256 amount,
                                bytes calldata permit
                            )
                                private
                            {   
                                Utils.permit(token, permit);
                                ITokenTransferProxy(tokenTransferProxy).transferFrom(
                                    token, from, to, amount
                                );
                            }
                            function _swap(
                                address tokenIn,
                                uint256 amountIn,
                                uint256 amountOutMin,
                                address weth,
                                uint256[] memory pools
                            )
                                private
                                returns (uint256 tokensBought)
                            {
                                uint256 pairs = pools.length;
                                require(pairs != 0, "At least one pool required");
                                bool tokensBoughtEth;
                                if (tokenIn == ETH_IDENTIFIER) {
                                    require(amountIn == msg.value, "Incorrect msg.value");
                                    IWETH(weth).deposit{value: msg.value}();
                                    require(IWETH(weth).transfer(address(pools[0]), msg.value));
                                } else {
                                    require(msg.value == 0, "Incorrect msg.value");
                                    transferTokens(tokenIn, msg.sender, address(pools[0]), amountIn);
                                    tokensBoughtEth = weth != address(0);
                                }
                                tokensBought = amountIn;
                                for (uint256 i = 0; i < pairs; ++i) {
                                    uint256 p = pools[i];
                                    address pool = address(p);
                                    bool direction = p & DIRECTION_FLAG == 0;
                                    tokensBought = NewUniswapV2Lib.getAmountOut(
                                        tokensBought, pool, direction, p >> FEE_OFFSET
                                    );
                                    (uint256 amount0Out, uint256 amount1Out) = direction
                                        ? (uint256(0), tokensBought) : (tokensBought, uint256(0));
                                    IUniswapV2Pair(pool).swap(
                                        amount0Out,
                                        amount1Out,
                                        i + 1 == pairs
                                            ? (tokensBoughtEth ? address(this) : msg.sender)
                                            : address(pools[i + 1]),
                                        ""
                                    );
                                }
                                if (tokensBoughtEth) {
                                    IWETH(weth).withdraw(tokensBought);
                                    TransferHelper.safeTransferETH(msg.sender, tokensBought);
                                }
                                require(tokensBought >= amountOutMin, "UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT");
                            }
                            function _buy(
                                address tokenIn,
                                uint256 amountInMax,
                                uint256 amountOut,
                                address weth,
                                uint256[] memory pools
                            )
                                private
                                returns (uint256 tokensSold)
                            {
                                uint256 pairs = pools.length;
                                require(pairs != 0, "At least one pool required");
                                uint256[] memory amounts = new uint256[](pairs + 1);
                                amounts[pairs] = amountOut;
                                for (uint256 i = pairs; i != 0; --i) {
                                    uint256 p = pools[i - 1];
                                    amounts[i - 1] = NewUniswapV2Lib.getAmountIn(
                                        amounts[i],
                                        address(p),
                                        p & DIRECTION_FLAG == 0,
                                        p >> FEE_OFFSET
                                    );
                                }
                                tokensSold = amounts[0];
                                require(tokensSold <= amountInMax, "UniswapV2Router: INSUFFICIENT_INPUT_AMOUNT");
                                bool tokensBoughtEth;
                                if (tokenIn == ETH_IDENTIFIER) {
                                    TransferHelper.safeTransferETH(
                                        msg.sender, msg.value.sub(tokensSold)
                                    );
                                    IWETH(weth).deposit{value: tokensSold}();
                                    require(IWETH(weth).transfer(address(pools[0]), tokensSold));
                                } else {
                                    require(msg.value == 0, "Incorrect msg.value");
                                    transferTokens(tokenIn, msg.sender, address(pools[0]), tokensSold);
                                    tokensBoughtEth = weth != address(0);
                                }
                                for (uint256 i = 0; i < pairs; ++i) {
                                    uint256 p = pools[i];
                                    (uint256 amount0Out, uint256 amount1Out) = p & DIRECTION_FLAG == 0
                                        ? (uint256(0), amounts[i + 1]) : (amounts[i + 1], uint256(0));
                                    IUniswapV2Pair(address(p)).swap(
                                        amount0Out,
                                        amount1Out,
                                        i + 1 == pairs
                                            ? (tokensBoughtEth ? address(this) : msg.sender)
                                            : address(pools[i + 1]),
                                        ""
                                    );
                                }
                                if (tokensBoughtEth) {
                                    IWETH(weth).withdraw(amountOut);
                                    TransferHelper.safeTransferETH(msg.sender, amountOut);
                                }
                            }
                            function _swapWithPermit(
                                address tokenIn,
                                uint256 amountIn,
                                uint256 amountOutMin,
                                address weth,
                                uint256[] memory pools,
                                bytes calldata permit
                            )
                                private
                                returns (uint256 tokensBought)
                            {
                                uint256 pairs = pools.length;
                                require(pairs != 0, "At least one pool required");
                                bool tokensBoughtEth;
                                if (tokenIn == ETH_IDENTIFIER) {
                                    require(amountIn == msg.value, "Incorrect msg.value");
                                    IWETH(weth).deposit{value: msg.value}();
                                    require(IWETH(weth).transfer(address(pools[0]), msg.value));
                                } else {
                                    require(msg.value == 0, "Incorrect msg.value");
                                    transferTokensWithPermit(tokenIn, msg.sender, address(pools[0]), amountIn, permit);
                                    tokensBoughtEth = weth != address(0);
                                }
                                tokensBought = amountIn;
                                for (uint256 i = 0; i < pairs; ++i) {
                                    uint256 p = pools[i];
                                    address pool = address(p);
                                    bool direction = p & DIRECTION_FLAG == 0;
                                    tokensBought = NewUniswapV2Lib.getAmountOut(
                                        tokensBought, pool, direction, p >> FEE_OFFSET
                                    );
                                    (uint256 amount0Out, uint256 amount1Out) = direction
                                        ? (uint256(0), tokensBought) : (tokensBought, uint256(0));
                                    IUniswapV2Pair(pool).swap(
                                        amount0Out,
                                        amount1Out,
                                        i + 1 == pairs
                                            ? (tokensBoughtEth ? address(this) : msg.sender)
                                            : address(pools[i + 1]),
                                        ""
                                    );
                                }
                                if (tokensBoughtEth) {
                                    IWETH(weth).withdraw(tokensBought);
                                    TransferHelper.safeTransferETH(msg.sender, tokensBought);
                                }
                                require(tokensBought >= amountOutMin, "UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT");
                            }
                            function _buyWithPermit(
                                address tokenIn,
                                uint256 amountInMax,
                                uint256 amountOut,
                                address weth,
                                uint256[] memory pools,
                                bytes calldata permit
                            )
                                private
                                returns (uint256 tokensSold)
                            {
                                uint256 pairs = pools.length;
                                require(pairs != 0, "At least one pool required");
                                uint256[] memory amounts = new uint256[](pairs + 1);
                                amounts[pairs] = amountOut;
                                for (uint256 i = pairs; i != 0; --i) {
                                    uint256 p = pools[i - 1];
                                    amounts[i - 1] = NewUniswapV2Lib.getAmountIn(
                                        amounts[i],
                                        address(p),
                                        p & DIRECTION_FLAG == 0,
                                        p >> FEE_OFFSET
                                    );
                                }
                                tokensSold = amounts[0];
                                require(tokensSold <= amountInMax, "UniswapV2Router: INSUFFICIENT_INPUT_AMOUNT");
                                bool tokensBoughtEth;
                                if (tokenIn == ETH_IDENTIFIER) {
                                    TransferHelper.safeTransferETH(
                                        msg.sender, msg.value.sub(tokensSold)
                                    );
                                    IWETH(weth).deposit{value: tokensSold}();
                                    require(IWETH(weth).transfer(address(pools[0]), tokensSold));
                                } else {
                                    require(msg.value == 0, "Incorrect msg.value");
                                    transferTokensWithPermit(tokenIn, msg.sender, address(pools[0]), tokensSold, permit);
                                    tokensBoughtEth = weth != address(0);
                                }
                                for (uint256 i = 0; i < pairs; ++i) {
                                    uint256 p = pools[i];
                                    (uint256 amount0Out, uint256 amount1Out) = p & DIRECTION_FLAG == 0
                                        ? (uint256(0), amounts[i + 1]) : (amounts[i + 1], uint256(0));
                                    IUniswapV2Pair(address(p)).swap(
                                        amount0Out,
                                        amount1Out,
                                        i + 1 == pairs
                                            ? (tokensBoughtEth ? address(this) : msg.sender)
                                            : address(pools[i + 1]),
                                        ""
                                    );
                                }
                                if (tokensBoughtEth) {
                                    IWETH(weth).withdraw(amountOut);
                                    TransferHelper.safeTransferETH(msg.sender, amountOut);
                                }
                            }
                        }
                        

                        File 13 of 18: TokenTransferProxy
                        // File: openzeppelin-solidity/contracts/utils/EnumerableSet.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <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.
                         *
                         * ```
                         * 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.
                         */
                        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;
                        
                                    // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                    // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                        
                                    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] = toDeleteIndex + 1; // All indexes are 1-based
                        
                                    // 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) {
                                require(set._values.length > index, "EnumerableSet: index out of bounds");
                                return set._values[index];
                            }
                        
                            // 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);
                            }
                        
                            // 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(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(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(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(uint256(_at(set._inner, index)));
                            }
                        
                        
                            // 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 on 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));
                            }
                        }
                        
                        // File: openzeppelin-solidity/contracts/utils/Address.sol
                        
                        
                        
                        pragma solidity >=0.6.2 <0.8.0;
                        
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                        
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                        
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                        
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                        
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                        
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        
                        // File: openzeppelin-solidity/contracts/GSN/Context.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                return msg.sender;
                            }
                        
                            function _msgData() internal view virtual returns (bytes memory) {
                                this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                return msg.data;
                            }
                        }
                        
                        // File: openzeppelin-solidity/contracts/access/AccessControl.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        
                        
                        /**
                         * @dev Contract module that allows children to implement role-based access
                         * control mechanisms.
                         *
                         * Roles are referred to by their `bytes32` identifier. These should be exposed
                         * in the external API and be unique. The best way to achieve this is by
                         * using `public constant` hash digests:
                         *
                         * ```
                         * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                         * ```
                         *
                         * Roles can be used to represent a set of permissions. To restrict access to a
                         * function call, use {hasRole}:
                         *
                         * ```
                         * function foo() public {
                         *     require(hasRole(MY_ROLE, msg.sender));
                         *     ...
                         * }
                         * ```
                         *
                         * Roles can be granted and revoked dynamically via the {grantRole} and
                         * {revokeRole} functions. Each role has an associated admin role, and only
                         * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                         *
                         * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                         * that only accounts with this role will be able to grant or revoke other
                         * roles. More complex role relationships can be created by using
                         * {_setRoleAdmin}.
                         *
                         * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                         * grant and revoke this role. Extra precautions should be taken to secure
                         * accounts that have been granted it.
                         */
                        abstract contract AccessControl is Context {
                            using EnumerableSet for EnumerableSet.AddressSet;
                            using Address for address;
                        
                            struct RoleData {
                                EnumerableSet.AddressSet members;
                                bytes32 adminRole;
                            }
                        
                            mapping (bytes32 => RoleData) private _roles;
                        
                            bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                        
                            /**
                             * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                             *
                             * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                             * {RoleAdminChanged} not being emitted signaling this.
                             *
                             * _Available since v3.1._
                             */
                            event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                        
                            /**
                             * @dev Emitted when `account` is granted `role`.
                             *
                             * `sender` is the account that originated the contract call, an admin role
                             * bearer except when using {_setupRole}.
                             */
                            event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                        
                            /**
                             * @dev Emitted when `account` is revoked `role`.
                             *
                             * `sender` is the account that originated the contract call:
                             *   - if using `revokeRole`, it is the admin role bearer
                             *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                             */
                            event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                        
                            /**
                             * @dev Returns `true` if `account` has been granted `role`.
                             */
                            function hasRole(bytes32 role, address account) public view returns (bool) {
                                return _roles[role].members.contains(account);
                            }
                        
                            /**
                             * @dev Returns the number of accounts that have `role`. Can be used
                             * together with {getRoleMember} to enumerate all bearers of a role.
                             */
                            function getRoleMemberCount(bytes32 role) public view returns (uint256) {
                                return _roles[role].members.length();
                            }
                        
                            /**
                             * @dev Returns one of the accounts that have `role`. `index` must be a
                             * value between 0 and {getRoleMemberCount}, non-inclusive.
                             *
                             * Role bearers are not sorted in any particular way, and their ordering may
                             * change at any point.
                             *
                             * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                             * you perform all queries on the same block. See the following
                             * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                             * for more information.
                             */
                            function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
                                return _roles[role].members.at(index);
                            }
                        
                            /**
                             * @dev Returns the admin role that controls `role`. See {grantRole} and
                             * {revokeRole}.
                             *
                             * To change a role's admin, use {_setRoleAdmin}.
                             */
                            function getRoleAdmin(bytes32 role) public view returns (bytes32) {
                                return _roles[role].adminRole;
                            }
                        
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function grantRole(bytes32 role, address account) public virtual {
                                require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
                        
                                _grantRole(role, account);
                            }
                        
                            /**
                             * @dev Revokes `role` from `account`.
                             *
                             * If `account` had been granted `role`, emits a {RoleRevoked} event.
                             *
                             * Requirements:
                             *
                             * - the caller must have ``role``'s admin role.
                             */
                            function revokeRole(bytes32 role, address account) public virtual {
                                require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
                        
                                _revokeRole(role, account);
                            }
                        
                            /**
                             * @dev Revokes `role` from the calling account.
                             *
                             * Roles are often managed via {grantRole} and {revokeRole}: this function's
                             * purpose is to provide a mechanism for accounts to lose their privileges
                             * if they are compromised (such as when a trusted device is misplaced).
                             *
                             * If the calling account had been granted `role`, emits a {RoleRevoked}
                             * event.
                             *
                             * Requirements:
                             *
                             * - the caller must be `account`.
                             */
                            function renounceRole(bytes32 role, address account) public virtual {
                                require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                        
                                _revokeRole(role, account);
                            }
                        
                            /**
                             * @dev Grants `role` to `account`.
                             *
                             * If `account` had not been already granted `role`, emits a {RoleGranted}
                             * event. Note that unlike {grantRole}, this function doesn't perform any
                             * checks on the calling account.
                             *
                             * [WARNING]
                             * ====
                             * This function should only be called from the constructor when setting
                             * up the initial roles for the system.
                             *
                             * Using this function in any other way is effectively circumventing the admin
                             * system imposed by {AccessControl}.
                             * ====
                             */
                            function _setupRole(bytes32 role, address account) internal virtual {
                                _grantRole(role, account);
                            }
                        
                            /**
                             * @dev Sets `adminRole` as ``role``'s admin role.
                             *
                             * Emits a {RoleAdminChanged} event.
                             */
                            function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                                emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
                                _roles[role].adminRole = adminRole;
                            }
                        
                            function _grantRole(bytes32 role, address account) private {
                                if (_roles[role].members.add(account)) {
                                    emit RoleGranted(role, account, _msgSender());
                                }
                            }
                        
                            function _revokeRole(bytes32 role, address account) private {
                                if (_roles[role].members.remove(account)) {
                                    emit RoleRevoked(role, account, _msgSender());
                                }
                            }
                        }
                        
                        // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                        
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                        
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                        
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                        
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        
                        // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                        
                                return c;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                return sub(a, b, "SafeMath: subtraction overflow");
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                uint256 c = a - b;
                        
                                return c;
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot 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-contracts/pull/522
                                if (a == 0) {
                                    return 0;
                                }
                        
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                        
                                return c;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                return div(a, b, "SafeMath: division by zero");
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                uint256 c = a / b;
                                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                        
                                return c;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                return mod(a, b, "SafeMath: modulo by zero");
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * Reverts with custom message when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b != 0, errorMessage);
                                return a % b;
                            }
                        }
                        
                        // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        
                        
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                        
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                        
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                        
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                        
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                        
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        
                        // File: original_contracts/routers/IRouter.sol
                        
                        pragma solidity 0.7.5;
                        
                        interface IRouter {
                        
                            /**
                            * @dev Certain routers/exchanges needs to be initialized.
                            * This method will be called from Augustus
                            */
                            function initialize(bytes calldata data) external;
                        
                            /**
                            * @dev Returns unique identifier for the router
                            */
                            function getKey() external pure returns(bytes32);
                        
                            event Swapped(
                                bytes16 uuid,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount,
                                uint256 expectedAmount
                            );
                        
                            event Bought(
                                bytes16 uuid,
                                address initiator,
                                address indexed beneficiary,
                                address indexed srcToken,
                                address indexed destToken,
                                uint256 srcAmount,
                                uint256 receivedAmount
                            );
                        
                            event FeeTaken(
                                uint256 fee,
                                uint256 partnerShare,
                                uint256 paraswapShare
                            );
                        }
                        
                        // File: original_contracts/ITokenTransferProxy.sol
                        
                        pragma solidity 0.7.5;
                        
                        
                        interface ITokenTransferProxy {
                        
                            function transferFrom(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                external;
                        }
                        
                        // File: original_contracts/lib/Utils.sol
                        
                        pragma solidity 0.7.5;
                        pragma experimental ABIEncoderV2;
                        
                        
                        
                        
                        
                        interface IERC20Permit {
                            function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                        }
                        
                        library Utils {
                            using SafeMath for uint256;
                            using SafeERC20 for IERC20;
                        
                            address constant ETH_ADDRESS = address(
                                0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
                            );
                            
                            uint256 constant MAX_UINT = type(uint256).max;
                        
                            /**
                           * @param fromToken Address of the source token
                           * @param fromAmount Amount of source tokens to be swapped
                           * @param toAmount Minimum destination token amount expected out of this swap
                           * @param expectedAmount Expected amount of destination tokens without slippage
                           * @param beneficiary Beneficiary address
                           * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
                           * @param path Route to be taken for this swap to take place
                        
                           */
                            struct SellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.Path[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                        
                            struct MegaSwapSellData {
                                address fromToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address payable beneficiary;
                                Utils.MegaSwapPath[] path;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                        
                            struct SimpleData {
                                address fromToken;
                                address toToken;
                                uint256 fromAmount;
                                uint256 toAmount;
                                uint256 expectedAmount;
                                address[] callees;
                                bytes exchangeData;
                                uint256[] startIndexes;
                                uint256[] values;
                                address payable beneficiary;
                                address payable partner;
                                uint256 feePercent;
                                bytes permit;
                                uint256 deadline;
                                bytes16 uuid;
                            }
                        
                            struct Adapter {
                                address payable adapter;
                                uint256 percent;
                                uint256 networkFee;
                                Route[] route;
                            }
                        
                            struct Route {
                                uint256 index;//Adapter at which index needs to be used
                                address targetExchange;
                                uint percent;
                                bytes payload;
                                uint256 networkFee;//Network fee is associated with 0xv3 trades
                            }
                        
                            struct MegaSwapPath {
                                uint256 fromAmountPercent;
                                Path[] path;
                            }
                        
                            struct Path {
                                address to;
                                uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
                                Adapter[] adapters;
                            }
                        
                            function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
                        
                            function maxUint() internal pure returns (uint256) {return MAX_UINT;}
                        
                            function approve(
                                address addressToApprove,
                                address token,
                                uint256 amount
                            ) internal {
                                if (token != ETH_ADDRESS) {
                                    IERC20 _token = IERC20(token);
                        
                                    uint allowance = _token.allowance(address(this), addressToApprove);
                        
                                    if (allowance < amount) {
                                        _token.safeApprove(addressToApprove, 0);
                                        _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
                                    }
                                }
                            }
                        
                            function transferTokens(
                                address token,
                                address payable destination,
                                uint256 amount
                            )
                            internal
                            {
                                if (amount > 0) {
                                    if (token == ETH_ADDRESS) {
                                        (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                        require(result, "Failed to transfer Ether");
                                    }
                                    else {
                                        IERC20(token).safeTransfer(destination, amount);
                                    }
                                }
                        
                            }
                        
                            function tokenBalance(
                                address token,
                                address account
                            )
                            internal
                            view
                            returns (uint256)
                            {
                                if (token == ETH_ADDRESS) {
                                    return account.balance;
                                } else {
                                    return IERC20(token).balanceOf(account);
                                }
                            }
                        
                            function permit(
                                address token,
                                bytes memory permit
                            )
                                internal
                            {
                                if (permit.length == 32 * 7) {
                                    (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
                                    require(success, "Permit failed");
                                }
                            }
                        
                        }
                        
                        // File: original_contracts/adapters/IAdapter.sol
                        
                        pragma solidity 0.7.5;
                        
                        
                        
                        interface IAdapter {
                        
                            /**
                            * @dev Certain adapters needs to be initialized.
                            * This method will be called from Augustus
                            */
                            function initialize(bytes calldata data) external;
                        
                            /**
                           * @dev The function which performs the swap on an exchange.
                           * @param fromToken Address of the source token
                           * @param toToken Address of the destination token
                           * @param fromAmount Amount of source tokens to be swapped
                           * @param networkFee Network fee to be used in this router
                           * @param route Route to be followed
                           */
                            function swap(
                                IERC20 fromToken,
                                IERC20 toToken,
                                uint256 fromAmount,
                                uint256 networkFee,
                                Utils.Route[] calldata route
                            )
                                external
                                payable;
                        }
                        
                        // File: openzeppelin-solidity/contracts/access/Ownable.sol
                        
                        
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @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 () internal {
                                address msgSender = _msgSender();
                                _owner = msgSender;
                                emit OwnershipTransferred(address(0), msgSender);
                            }
                        
                            /**
                             * @dev Returns the address of the current owner.
                             */
                            function owner() public view returns (address) {
                                return _owner;
                            }
                        
                            /**
                             * @dev Throws if called by any account other than the owner.
                             */
                            modifier onlyOwner() {
                                require(_owner == _msgSender(), "Ownable: caller is not the owner");
                                _;
                            }
                        
                            /**
                             * @dev Leaves the contract without owner. It will not be possible to call
                             * `onlyOwner` functions anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing any functionality that is only available to the owner.
                             */
                            function renounceOwnership() public virtual onlyOwner {
                                emit OwnershipTransferred(_owner, address(0));
                                _owner = 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");
                                emit OwnershipTransferred(_owner, newOwner);
                                _owner = newOwner;
                            }
                        }
                        
                        // File: original_contracts/TokenTransferProxy.sol
                        
                        pragma solidity 0.7.5;
                        
                        
                        
                        
                        
                        
                        
                        /**
                        * @dev Allows owner of the contract to transfer tokens on behalf of user.
                        * User will need to approve this contract to spend tokens on his/her behalf
                        * on Paraswap platform
                        */
                        contract TokenTransferProxy is Ownable, ITokenTransferProxy {
                            using SafeERC20 for IERC20;
                            using Address for address;
                        
                            /**
                            * @dev Allows owner of the contract to transfer tokens on user's behalf
                            * @dev Swapper contract will be the owner of this contract
                            * @param token Address of the token
                            * @param from Address from which tokens will be transferred
                            * @param to Receipent address of the tokens
                            * @param amount Amount of tokens to transfer
                            */
                            function transferFrom(
                                address token,
                                address from,
                                address to,
                                uint256 amount
                            )
                                external
                                override
                                onlyOwner
                            {   
                                require(
                                    from == tx.origin ||
                                    from.isContract(),
                                    "Invalid from address"
                                );
                                
                                IERC20(token).safeTransferFrom(from, to, amount);
                            }
                        }
                        
                        // File: original_contracts/AugustusStorage.sol
                        
                        pragma solidity 0.7.5;
                        
                        
                        contract AugustusStorage {
                        
                            struct FeeStructure {
                                uint256 partnerShare;
                                bool noPositiveSlippage;
                                bool positiveSlippageToUser;
                                uint16 feePercent;
                                string partnerId;
                                bytes data;
                            }
                        
                            ITokenTransferProxy internal tokenTransferProxy;
                            address payable internal feeWallet;
                            
                            mapping(address => FeeStructure) internal registeredPartners;
                        
                            mapping (bytes4 => address) internal selectorVsRouter;
                            mapping (bytes32 => bool) internal adapterInitialized;
                            mapping (bytes32 => bytes) internal adapterVsData;
                        
                            mapping (bytes32 => bytes) internal routerData;
                            mapping (bytes32 => bool) internal routerInitialized;
                        
                        
                            bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
                        
                            bytes32 public constant ROUTER_ROLE = keccak256("ROUTER_ROLE");
                        
                        }
                        
                        // File: original_contracts/AugustusSwapper.sol
                        
                        pragma solidity 0.7.5;
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        contract AugustusSwapper is AugustusStorage, AccessControl {
                            using SafeMath for uint256;
                            using SafeERC20 for IERC20;
                        
                            event AdapterInitialized(address indexed adapter);
                        
                            event RouterInitialized(address indexed router);
                        
                            /**
                             * @dev Throws if called by any account other than the admin.
                             */
                            modifier onlyAdmin() {
                                require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "caller is not the admin");
                                _;
                            }
                        
                            constructor(address payable _feeWallet) public {
                                TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy();
                                tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);
                                feeWallet = _feeWallet;
                                _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
                            }
                            
                            receive () payable external {
                        
                            }
                        
                            fallback() external payable {
                                bytes4 selector = msg.sig;
                                //Figure out the router contract for the given function
                                address implementation = getImplementation(selector);
                                if (implementation == address(0)) {
                                    _revertWithData(
                                        abi.encodeWithSelector(
                                            bytes4(keccak256("NotImplementedError(bytes4)")),
                                            selector
                                        )
                                    );
                                }
                        
                                //Delegate call to the router
                                (bool success, bytes memory resultData) = implementation.delegatecall(msg.data);
                                if (!success) {
                                    _revertWithData(resultData);
                                }
                        
                                _returnWithData(resultData);
                            }
                        
                            function initializeAdapter(address adapter, bytes calldata data) external onlyAdmin {
                        
                                require(
                                    hasRole(WHITELISTED_ROLE, adapter),
                                    "Exchange not whitelisted"
                                );
                                (bool success,) = adapter.delegatecall(abi.encodeWithSelector(IAdapter.initialize.selector, data));
                                require(success, "Failed to initialize adapter");
                                emit AdapterInitialized(adapter);
                            }
                        
                            function initializeRouter(address router, bytes calldata data) external onlyAdmin {
                        
                                require(
                                    hasRole(ROUTER_ROLE, router),
                                    "Router not whitelisted"
                                );
                                (bool success,) = router.delegatecall(abi.encodeWithSelector(IRouter.initialize.selector, data));
                                require(success, "Failed to initialize router");
                                emit RouterInitialized(router);
                            } 
                        
                            
                            function getImplementation(bytes4 selector) public view returns(address) {
                                return selectorVsRouter[selector];
                            }
                        
                            function getVersion() external pure returns(string memory) {
                                return "5.0.0";
                            }
                        
                            function getPartnerFeeStructure(address partner) public view returns (FeeStructure memory) {
                                return registeredPartners[partner];
                            }
                        
                            function getFeeWallet() external view returns(address) {
                                return feeWallet;
                            }
                        
                            function setFeeWallet(address payable _feeWallet) external onlyAdmin {
                                require(_feeWallet != address(0), "Invalid address");
                                feeWallet = _feeWallet;
                            }
                        
                            function registerPartner(
                                address partner,
                                uint256 _partnerShare,
                                bool _noPositiveSlippage,
                                bool _positiveSlippageToUser,
                                uint16 _feePercent,
                                string calldata partnerId,
                                bytes calldata _data
                            )
                                external
                                onlyAdmin
                            {   
                                require(partner != address(0), "Invalid partner");
                                FeeStructure storage feeStructure = registeredPartners[partner];
                                require(feeStructure.partnerShare == 0, "Already registered");
                                require(_partnerShare > 0 && _partnerShare < 10000, "Invalid values");
                                require(_feePercent <= 10000, "Invalid values");
                        
                                feeStructure.partnerShare = _partnerShare;
                                feeStructure.noPositiveSlippage = _noPositiveSlippage;
                                feeStructure.positiveSlippageToUser = _positiveSlippageToUser;
                                feeStructure.partnerId = partnerId;
                                feeStructure.feePercent = _feePercent;
                                feeStructure.data = _data;
                            }
                        
                            function setImplementation(bytes4 selector, address implementation) external onlyAdmin {
                                require(
                                    hasRole(ROUTER_ROLE, implementation),
                                    "Router is not whitelisted"
                                );
                                selectorVsRouter[selector] = implementation;
                            }
                        
                            /**
                            * @dev Allows admin of the contract to transfer any tokens which are assigned to the contract
                            * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake
                            * @dev token Address of the token to be transferred
                            * @dev destination Recepient of the token
                            * @dev amount Amount of tokens to be transferred
                            */
                            function transferTokens(
                                address token,
                                address payable destination,
                                uint256 amount
                            )
                                external
                                onlyAdmin
                            {
                                if (amount > 0) {
                                    if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
                                        (bool result, ) = destination.call{value: amount, gas: 10000}("");
                                        require(result, "Failed to transfer Ether");
                                    }
                                    else {
                                        IERC20(token).safeTransfer(destination, amount);
                                    }
                                }
                            }
                        
                              function isAdapterInitialized(bytes32 key) public view returns(bool) {
                                return adapterInitialized[key];
                            }
                        
                            function getAdapterData(bytes32 key) public view returns(bytes memory) {
                                return adapterVsData[key];
                            }
                        
                            function isRouterInitialized(bytes32 key) public view returns (bool) {
                                return routerInitialized[key];
                            }
                        
                            function getRouterData(bytes32 key) public view returns (bytes memory) {
                                return routerData[key];
                            }
                        
                            function getTokenTransferProxy() public view returns (address) {
                                return address(tokenTransferProxy);
                            }
                        
                            function _revertWithData(bytes memory data) private pure {
                                assembly { revert(add(data, 32), mload(data)) }
                            }
                        
                            function _returnWithData(bytes memory data) private pure {
                                assembly { return(add(data, 32), mload(data)) }
                            }
                        
                        }

                        File 14 of 18: CvxStakingProxyV2
                        // File: contracts\interfaces\ICrvDepositor.sol
                        
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.6.12;
                        
                        interface ICrvDepositor {
                            function deposit(uint256, bool) external;
                        }
                        
                        // File: @openzeppelin\contracts\utils\Address.sol
                        
                        
                        pragma solidity >=0.6.2 <0.8.0;
                        
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                        
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                        
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                        
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                        
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                require(isContract(target), "Address: delegate call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                        
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\IERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                        
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                        
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                        
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                        
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        
                        // File: @openzeppelin\contracts\math\SafeMath.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                uint256 c = a + b;
                                if (c < a) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b > a) return (false, 0);
                                return (true, a - b);
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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-contracts/pull/522
                                if (a == 0) return (true, 0);
                                uint256 c = a * b;
                                if (c / a != b) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the division of two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a / b);
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a % b);
                            }
                        
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b <= a, "SafeMath: subtraction overflow");
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot overflow.
                             */
                            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                if (a == 0) return 0;
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: division by zero");
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: modulo by zero");
                                return a % b;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {trySub}.
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryDiv}.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting with custom message when dividing by zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryMod}.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a % b;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                        
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                        
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                        
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                        
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                        
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        
                        // File: contracts\CvxStakingProxyV2.sol
                        
                        pragma solidity 0.6.12;
                        interface IConvexRewards {
                            function withdraw(uint256 _amount, bool _claim) external;
                        
                            function balanceOf(address _account) external view returns(uint256);
                        
                            function getReward(bool _stake) external;
                        
                            function stakeAll() external;
                        }
                        
                        interface ICvxLocker {
                            function notifyRewardAmount(address _rewardsToken, uint256 reward) external;
                        }
                        
                        
                        // receive tokens to stake
                        // get current staked balance
                        // withdraw staked tokens
                        // send rewards back to owner(cvx locker)
                        // register token types that can be distributed
                        
                        contract CvxStakingProxyV2 {
                            using SafeERC20
                            for IERC20;
                            using Address
                            for address;
                            using SafeMath
                            for uint256;
                        
                            //tokens
                            address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
                            address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
                            address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
                        
                            //convex addresses
                            address public constant cvxStaking = address(0xCF50b810E57Ac33B91dCF525C6ddd9881B139332);
                            address public constant cvxCrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
                            address public constant crvDeposit = address(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae);
                            uint256 public constant denominator = 10000;
                        
                            address public immutable rewards;
                        
                            address public owner;
                            address public pendingOwner;
                            uint256 public callIncentive = 100;
                        
                            mapping(address => bool) public distributors;
                            bool public UseDistributors = true;
                        
                            event AddDistributor(address indexed _distro, bool _valid);
                            event RewardsDistributed(address indexed token, uint256 amount);
                        
                            constructor(address _rewards) public {
                                rewards = _rewards;
                                owner = msg.sender;
                                distributors[msg.sender] = true;
                            }
                        
                            function setPendingOwner(address _po) external {
                                require(msg.sender == owner, "!auth");
                                pendingOwner = _po;
                            }
                        
                            function applyPendingOwner() external {
                                require(msg.sender == owner, "!auth");
                                require(pendingOwner != address(0), "invalid owner");
                        
                                owner = pendingOwner;
                                pendingOwner = address(0);
                            }
                        
                            function setCallIncentive(uint256 _incentive) external {
                                require(msg.sender == owner, "!auth");
                                require(_incentive <= 100, "too high");
                                callIncentive = _incentive;
                            }
                        
                            function setDistributor(address _distro, bool _valid) external {
                                require(msg.sender == owner, "!auth");
                                distributors[_distro] = _valid;
                                emit AddDistributor(_distro, _valid);
                            }
                        
                            function setUseDistributorList(bool _use) external {
                                require(msg.sender == owner, "!auth");
                                UseDistributors = _use;
                            }
                        
                            function setApprovals() external {
                                IERC20(cvx).safeApprove(cvxStaking, 0);
                                IERC20(cvx).safeApprove(cvxStaking, uint256(-1));
                        
                                IERC20(crv).safeApprove(crvDeposit, 0);
                                IERC20(crv).safeApprove(crvDeposit, uint256(-1));
                        
                                IERC20(cvxCrv).safeApprove(rewards, 0);
                                IERC20(cvxCrv).safeApprove(rewards, uint256(-1));
                            }
                        
                            function rescueToken(address _token, address _to) external {
                                require(msg.sender == owner, "!auth");
                                require(_token != crv && _token != cvx && _token != cvxCrv, "not allowed");
                        
                                uint256 bal = IERC20(_token).balanceOf(address(this));
                                IERC20(_token).safeTransfer(_to, bal);
                            }
                        
                            function getBalance() external view returns(uint256) {
                                return IConvexRewards(cvxStaking).balanceOf(address(this));
                            }
                        
                            function withdraw(uint256 _amount) external {
                                require(msg.sender == rewards, "!auth");
                        
                                //unstake
                                IConvexRewards(cvxStaking).withdraw(_amount, false);
                        
                                //withdraw cvx
                                IERC20(cvx).safeTransfer(msg.sender, _amount);
                            }
                        
                        
                            function stake() external {
                                require(msg.sender == rewards, "!auth");
                        
                                IConvexRewards(cvxStaking).stakeAll();
                            }
                        
                            function distribute() external {
                                if(UseDistributors){
                                    require(distributors[msg.sender], "!auth");
                                }
                        
                                //claim rewards
                                IConvexRewards(cvxStaking).getReward(false);
                        
                                //convert any crv that was directly added
                                uint256 crvBal = IERC20(crv).balanceOf(address(this));
                                if (crvBal > 0) {
                                    ICrvDepositor(crvDeposit).deposit(crvBal, true);
                                }
                        
                                //make sure nothing is in here
                                uint256 sCheck  = IConvexRewards(cvxCrvStaking).balanceOf(address(this));
                                if(sCheck > 0){
                                    IConvexRewards(cvxCrvStaking).withdraw(sCheck,false);
                                }
                        
                                //distribute cvxcrv
                                uint256 cvxCrvBal = IERC20(cvxCrv).balanceOf(address(this));
                        
                                if (cvxCrvBal > 0) {
                                    uint256 incentiveAmount = cvxCrvBal.mul(callIncentive).div(denominator);
                                    cvxCrvBal = cvxCrvBal.sub(incentiveAmount);
                                    
                                    //send incentives
                                    IERC20(cvxCrv).safeTransfer(msg.sender,incentiveAmount);
                        
                                    //update rewards
                                    ICvxLocker(rewards).notifyRewardAmount(cvxCrv, cvxCrvBal);
                        
                                    emit RewardsDistributed(cvxCrv, cvxCrvBal);
                                }
                            }
                        
                            //in case a new reward is ever added, allow generic distribution
                            function distributeOther(IERC20 _token) external {
                                require( address(_token) != crv && address(_token) != cvxCrv, "not allowed");
                        
                                uint256 bal = _token.balanceOf(address(this));
                        
                                if (bal > 0) {
                                    uint256 incentiveAmount = bal.mul(callIncentive).div(denominator);
                                    bal = bal.sub(incentiveAmount);
                                    
                                    //send incentives
                                    _token.safeTransfer(msg.sender,incentiveAmount);
                        
                                    //approve
                                    _token.safeApprove(rewards, 0);
                                    _token.safeApprove(rewards, uint256(-1));
                        
                                    //update rewards
                                    ICvxLocker(rewards).notifyRewardAmount(address(_token), bal);
                        
                                    emit RewardsDistributed(address(_token), bal);
                                }
                            }
                        }

                        File 15 of 18: cvxRewardPool
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.6.12;
                        
                        
                        /**
                         * @dev Standard math utilities missing in the Solidity language.
                         */
                        library MathUtil {
                            /**
                             * @dev Returns the smallest of two numbers.
                             */
                            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                return a < b ? a : b;
                            }
                        }
                        
                        contract ReentrancyGuard {
                            uint256 private _guardCounter;
                        
                            constructor () internal {
                                _guardCounter = 1;
                            }
                        
                            modifier nonReentrant() {
                                _guardCounter += 1;
                                uint256 localCounter = _guardCounter;
                                _;
                                require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
                            }
                        }
                        
                        interface ICurveGauge {
                            function deposit(uint256) external;
                            function balanceOf(address) external view returns (uint256);
                            function withdraw(uint256) external;
                            function claim_rewards() external;
                            function reward_tokens(uint256) external view returns(address);//v2
                            function rewarded_token() external view returns(address);//v1
                        }
                        
                        interface ICurveVoteEscrow {
                            function create_lock(uint256, uint256) external;
                            function increase_amount(uint256) external;
                            function increase_unlock_time(uint256) external;
                            function withdraw() external;
                            function smart_wallet_checker() external view returns (address);
                        }
                        
                        interface IWalletChecker {
                            function check(address) external view returns (bool);
                        }
                        
                        interface IVoting{
                            function vote(uint256, bool, bool) external; //voteId, support, executeIfDecided
                            function getVote(uint256) external view returns(bool,bool,uint64,uint64,uint64,uint64,uint256,uint256,uint256,bytes memory); 
                            function vote_for_gauge_weights(address,uint256) external;
                        }
                        
                        interface IMinter{
                            function mint(address) external;
                        }
                        
                        interface IRegistry{
                            function get_registry() external view returns(address);
                            function get_address(uint256 _id) external view returns(address);
                            function gauge_controller() external view returns(address);
                            function get_lp_token(address) external view returns(address);
                            function get_gauges(address) external view returns(address[10] memory,uint128[10] memory);
                        }
                        
                        interface IStaker{
                            function deposit(address, address) external;
                            function withdraw(address) external;
                            function withdraw(address, address, uint256) external;
                            function withdrawAll(address, address) external;
                            function createLock(uint256, uint256) external;
                            function increaseAmount(uint256) external;
                            function increaseTime(uint256) external;
                            function release() external;
                            function claimCrv(address) external returns (uint256);
                            function claimRewards(address) external;
                            function claimFees(address,address) external;
                            function setStashAccess(address, bool) external;
                            function vote(uint256,address,bool) external;
                            function voteGaugeWeight(address,uint256) external;
                            function balanceOfPool(address) external view returns (uint256);
                            function operator() external view returns (address);
                            function execute(address _to, uint256 _value, bytes calldata _data) external returns (bool, bytes memory);
                        }
                        
                        interface IRewards{
                            function stake(address, uint256) external;
                            function stakeFor(address, uint256) external;
                            function withdraw(address, uint256) external;
                            function exit(address) external;
                            function getReward(address) external;
                            function queueNewRewards(uint256) external;
                            function notifyRewardAmount(uint256) external;
                            function addExtraReward(address) external;
                            function stakingToken() external returns (address);
                        }
                        
                        interface IStash{
                            function stashRewards() external returns (bool);
                            function processStash() external returns (bool);
                            function claimRewards() external returns (bool);
                        }
                        
                        interface IFeeDistro{
                            function claim() external;
                            function token() external view returns(address);
                        }
                        
                        interface ITokenMinter{
                            function mint(address,uint256) external;
                            function burn(address,uint256) external;
                        }
                        
                        interface IDeposit{
                            function isShutdown() external view returns(bool);
                            function balanceOf(address _account) external view returns(uint256);
                            function totalSupply() external view returns(uint256);
                            function poolInfo(uint256) external view returns(address,address,address,address,address, bool);
                            function rewardClaimed(uint256,address,uint256) external;
                            function withdrawTo(uint256,uint256,address) external;
                            function claimRewards(uint256,address) external returns(bool);
                            function rewardArbitrator() external returns(address);
                        }
                        
                        interface ICrvDeposit{
                            function deposit(uint256, bool) external;
                            function lockIncentive() external view returns(uint256);
                        }
                        
                        interface IRewardFactory{
                            function setAccess(address,bool) external;
                            function CreateCrvRewards(uint256,address) external returns(address);
                            function CreateTokenRewards(address,address,address) external returns(address);
                            function activeRewardCount(address) external view returns(uint256);
                            function addActiveReward(address,uint256) external returns(bool);
                            function removeActiveReward(address,uint256) external returns(bool);
                        }
                        
                        interface IStashFactory{
                            function CreateStash(uint256,address,address,uint256) external returns(address);
                        }
                        
                        interface ITokenFactory{
                            function CreateDepositToken(address) external returns(address);
                        }
                        
                        interface IPools{
                            function addPool(address _lptoken, address _gauge, uint256 _stashVersion) external returns(bool);
                            function shutdownPool(uint256 _pid) external returns(bool);
                            function poolInfo(uint256) external view returns(address,address,address,address,address,bool);
                            function poolLength() external view returns (uint256);
                            function gaugeMap(address) external view returns(bool);
                            function setPoolManager(address _poolM) external;
                        }
                        
                        interface IVestedEscrow{
                            function fund(address[] calldata _recipient, uint256[] calldata _amount) external returns(bool);
                        }
                        
                        // File: @openzeppelin\contracts\math\SafeMath.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Wrappers over Solidity's arithmetic operations with added overflow
                         * checks.
                         *
                         * Arithmetic operations in Solidity wrap on overflow. This can easily result
                         * in bugs, because programmers usually assume that an overflow raises an
                         * error, which is the standard behavior in high level programming languages.
                         * `SafeMath` restores this intuition by reverting the transaction when an
                         * operation overflows.
                         *
                         * Using this library instead of the unchecked operations eliminates an entire
                         * class of bugs, so it's recommended to use it always.
                         */
                        library SafeMath {
                            /**
                             * @dev Returns the addition of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                uint256 c = a + b;
                                if (c < a) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b > a) return (false, 0);
                                return (true, a - b);
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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-contracts/pull/522
                                if (a == 0) return (true, 0);
                                uint256 c = a * b;
                                if (c / a != b) return (false, 0);
                                return (true, c);
                            }
                        
                            /**
                             * @dev Returns the division of two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a / b);
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                             *
                             * _Available since v3.4._
                             */
                            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                if (b == 0) return (false, 0);
                                return (true, a % b);
                            }
                        
                            /**
                             * @dev Returns the addition of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `+` operator.
                             *
                             * Requirements:
                             *
                             * - Addition cannot overflow.
                             */
                            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                uint256 c = a + b;
                                require(c >= a, "SafeMath: addition overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting on
                             * overflow (when the result is negative).
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b <= a, "SafeMath: subtraction overflow");
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the multiplication of two unsigned integers, reverting on
                             * overflow.
                             *
                             * Counterpart to Solidity's `*` operator.
                             *
                             * Requirements:
                             *
                             * - Multiplication cannot overflow.
                             */
                            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                if (a == 0) return 0;
                                uint256 c = a * b;
                                require(c / a == b, "SafeMath: multiplication overflow");
                                return c;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting on
                             * division by zero. The result is rounded towards zero.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: division by zero");
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting when dividing by zero.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                require(b > 0, "SafeMath: modulo by zero");
                                return a % b;
                            }
                        
                            /**
                             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                             * overflow (when the result is negative).
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {trySub}.
                             *
                             * Counterpart to Solidity's `-` operator.
                             *
                             * Requirements:
                             *
                             * - Subtraction cannot overflow.
                             */
                            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b <= a, errorMessage);
                                return a - b;
                            }
                        
                            /**
                             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                             * division by zero. The result is rounded towards zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryDiv}.
                             *
                             * Counterpart to Solidity's `/` operator. Note: this function uses a
                             * `revert` opcode (which leaves remaining gas untouched) while Solidity
                             * uses an invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a / b;
                            }
                        
                            /**
                             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                             * reverting with custom message when dividing by zero.
                             *
                             * CAUTION: This function is deprecated because it requires allocating memory for the error
                             * message unnecessarily. For custom revert reasons use {tryMod}.
                             *
                             * Counterpart to Solidity's `%` operator. This function uses a `revert`
                             * opcode (which leaves remaining gas untouched) while Solidity uses an
                             * invalid opcode to revert (consuming all remaining gas).
                             *
                             * Requirements:
                             *
                             * - The divisor cannot be zero.
                             */
                            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                require(b > 0, errorMessage);
                                return a % b;
                            }
                        }
                        
                        // File: @openzeppelin\contracts\token\ERC20\IERC20.sol
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        /**
                         * @dev Interface of the ERC20 standard as defined in the EIP.
                         */
                        interface IERC20 {
                            /**
                             * @dev Returns the amount of tokens in existence.
                             */
                            function totalSupply() external view returns (uint256);
                        
                            /**
                             * @dev Returns the amount of tokens owned by `account`.
                             */
                            function balanceOf(address account) external view returns (uint256);
                        
                            /**
                             * @dev Moves `amount` tokens from the caller's account to `recipient`.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transfer(address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Returns the remaining number of tokens that `spender` will be
                             * allowed to spend on behalf of `owner` through {transferFrom}. This is
                             * zero by default.
                             *
                             * This value changes when {approve} or {transferFrom} are called.
                             */
                            function allowance(address owner, address spender) external view returns (uint256);
                        
                            /**
                             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * IMPORTANT: Beware that changing an allowance with this method brings the risk
                             * that someone may use both the old and the new allowance by unfortunate
                             * transaction ordering. One possible solution to mitigate this race
                             * condition is to first reduce the spender's allowance to 0 and set the
                             * desired value afterwards:
                             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                             *
                             * Emits an {Approval} event.
                             */
                            function approve(address spender, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Moves `amount` tokens from `sender` to `recipient` using the
                             * allowance mechanism. `amount` is then deducted from the caller's
                             * allowance.
                             *
                             * Returns a boolean value indicating whether the operation succeeded.
                             *
                             * Emits a {Transfer} event.
                             */
                            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        
                            /**
                             * @dev Emitted when `value` tokens are moved from one account (`from`) to
                             * another (`to`).
                             *
                             * Note that `value` may be zero.
                             */
                            event Transfer(address indexed from, address indexed to, uint256 value);
                        
                            /**
                             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                             * a call to {approve}. `value` is the new allowance.
                             */
                            event Approval(address indexed owner, address indexed spender, uint256 value);
                        }
                        
                        // File: @openzeppelin\contracts\utils\Address.sol
                        
                        pragma solidity >=0.6.2 <0.8.0;
                        
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize, which returns 0 for contracts in
                                // construction, since the code is only stored at the end of the
                                // constructor execution.
                        
                                uint256 size;
                                // solhint-disable-next-line no-inline-assembly
                                assembly { size := extcodesize(account) }
                                return size > 0;
                            }
                        
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                        
                                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                (bool success, ) = recipient.call{ value: amount }("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                        
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain`call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                              return functionCall(target, data, "Address: low-level call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                require(isContract(target), "Address: call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                require(isContract(target), "Address: static call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                        
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                require(isContract(target), "Address: delegate call to non-contract");
                        
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return _verifyCallResult(success, returndata, errorMessage);
                            }
                        
                            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    // Look for revert reason and bubble it up if present
                                    if (returndata.length > 0) {
                                        // The easiest way to bubble the revert reason is using memory via assembly
                        
                                        // solhint-disable-next-line no-inline-assembly
                                        assembly {
                                            let returndata_size := mload(returndata)
                                            revert(add(32, returndata), returndata_size)
                                        }
                                    } else {
                                        revert(errorMessage);
                                    }
                                }
                            }
                        }
                        
                        
                        // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
                        
                        pragma solidity >=0.6.0 <0.8.0;
                        
                        
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using SafeMath for uint256;
                            using Address for address;
                        
                            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                        
                            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                        
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                // solhint-disable-next-line max-line-length
                                require((value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                        
                            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                        
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                        
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) { // Return data is optional
                                    // solhint-disable-next-line max-line-length
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        
                        // File: contracts\cvxRewardPool.sol
                        
                        pragma solidity 0.6.12;
                        /**
                         *Submitted for verification at Etherscan.io on 2020-07-17
                         */
                        
                        /*
                           ____            __   __        __   _
                          / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
                         _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
                        /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
                             /___/
                        
                        * Synthetix: cvxRewardPool.sol
                        *
                        * Docs: https://docs.synthetix.io/
                        *
                        *
                        * MIT License
                        * ===========
                        *
                        * Copyright (c) 2020 Synthetix
                        *
                        * Permission is hereby granted, free of charge, to any person obtaining a copy
                        * of this software and associated documentation files (the "Software"), to deal
                        * in the Software without restriction, including without limitation the rights
                        * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                        * copies of the Software, and to permit persons to whom the Software is
                        * furnished to do so, subject to the following conditions:
                        *
                        * The above copyright notice and this permission notice shall be included in all
                        * copies or substantial portions of the Software.
                        *
                        * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                        * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                        * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                        * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                        * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                        * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                        */
                        
                        
                        
                        contract cvxRewardPool{
                            using SafeERC20 for IERC20;
                            using SafeMath for uint256;
                        
                            IERC20 public immutable rewardToken;
                            IERC20 public immutable stakingToken;
                            uint256 public constant duration = 7 days;
                            uint256 public constant FEE_DENOMINATOR = 10000;
                        
                            address public immutable operator;
                            address public immutable crvDeposits;
                            address public immutable cvxCrvRewards;
                            IERC20 public immutable cvxCrvToken;
                            address public immutable rewardManager;
                        
                            uint256 public periodFinish = 0;
                            uint256 public rewardRate = 0;
                            uint256 public lastUpdateTime;
                            uint256 public rewardPerTokenStored;
                            uint256 public queuedRewards = 0;
                            uint256 public currentRewards = 0;
                            uint256 public historicalRewards = 0;
                            uint256 public constant newRewardRatio = 830;
                            uint256 private _totalSupply;
                            mapping(address => uint256) private _balances;
                            mapping(address => uint256) public userRewardPerTokenPaid;
                            mapping(address => uint256) public rewards;
                        
                            address[] public extraRewards;
                        
                            event RewardAdded(uint256 reward);
                            event Staked(address indexed user, uint256 amount);
                            event Withdrawn(address indexed user, uint256 amount);
                            event RewardPaid(address indexed user, uint256 reward);
                        
                            constructor(
                                address stakingToken_,
                                address rewardToken_,
                                address crvDeposits_,
                                address cvxCrvRewards_,
                                address cvxCrvToken_,
                                address operator_,
                                address rewardManager_
                            ) public {
                                stakingToken = IERC20(stakingToken_);
                                rewardToken = IERC20(rewardToken_);
                                operator = operator_;
                                rewardManager = rewardManager_;
                                crvDeposits = crvDeposits_;
                                cvxCrvRewards = cvxCrvRewards_;
                                cvxCrvToken = IERC20(cvxCrvToken_);
                            }
                        
                            function totalSupply() public view returns (uint256) {
                                return _totalSupply;
                            }
                        
                            function balanceOf(address account) public view returns (uint256) {
                                return _balances[account];
                            }
                        
                            function extraRewardsLength() external view returns (uint256) {
                                return extraRewards.length;
                            }
                        
                            function addExtraReward(address _reward) external {
                                require(msg.sender == rewardManager, "!authorized");
                                require(_reward != address(0),"!reward setting");
                        
                                extraRewards.push(_reward);
                            }
                            function clearExtraRewards() external{
                                require(msg.sender == rewardManager, "!authorized");
                                delete extraRewards;
                            }
                        
                            modifier updateReward(address account) {
                                rewardPerTokenStored = rewardPerToken();
                                lastUpdateTime = lastTimeRewardApplicable();
                                if (account != address(0)) {
                                    rewards[account] = earnedReward(account);
                                    userRewardPerTokenPaid[account] = rewardPerTokenStored;
                                }
                                _;
                            }
                        
                            function lastTimeRewardApplicable() public view returns (uint256) {
                                return MathUtil.min(block.timestamp, periodFinish);
                            }
                        
                            function rewardPerToken() public view returns (uint256) {
                                uint256 supply = totalSupply();
                                if (supply == 0) {
                                    return rewardPerTokenStored;
                                }
                                return
                                    rewardPerTokenStored.add(
                                        lastTimeRewardApplicable()
                                            .sub(lastUpdateTime)
                                            .mul(rewardRate)
                                            .mul(1e18)
                                            .div(supply)
                                    );
                            }
                        
                            function earnedReward(address account) internal view returns (uint256) {
                                return
                                    balanceOf(account)
                                        .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                                        .div(1e18)
                                        .add(rewards[account]);
                            }
                        
                            function earned(address account) external view returns (uint256) {
                                uint256 depositFeeRate = ICrvDeposit(crvDeposits).lockIncentive();
                        
                                uint256 r = earnedReward(account);
                                uint256 fees = r.mul(depositFeeRate).div(FEE_DENOMINATOR);
                                
                                //fees dont apply until whitelist+vecrv lock begins so will report
                                //slightly less value than what is actually received.
                                return r.sub(fees);
                            }
                        
                            function stake(uint256 _amount)
                                public
                                updateReward(msg.sender)
                            {
                                require(_amount > 0, 'RewardPool : Cannot stake 0');
                        
                                //also stake to linked rewards
                                uint256 length = extraRewards.length;
                                for(uint i=0; i < length; i++){
                                    IRewards(extraRewards[i]).stake(msg.sender, _amount);
                                }
                        
                                //add supply
                                _totalSupply = _totalSupply.add(_amount);
                                //add to sender balance sheet
                                _balances[msg.sender] = _balances[msg.sender].add(_amount);
                                //take tokens from sender
                                stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
                        
                                emit Staked(msg.sender, _amount);
                            }
                        
                            function stakeAll() external{
                                uint256 balance = stakingToken.balanceOf(msg.sender);
                                stake(balance);
                            }
                        
                            function stakeFor(address _for, uint256 _amount)
                                public
                                updateReward(_for)
                            {
                                require(_amount > 0, 'RewardPool : Cannot stake 0');
                        
                                //also stake to linked rewards
                                uint256 length = extraRewards.length;
                                for(uint i=0; i < length; i++){
                                    IRewards(extraRewards[i]).stake(_for, _amount);
                                }
                        
                                 //add supply
                                _totalSupply = _totalSupply.add(_amount);
                                //add to _for's balance sheet
                                _balances[_for] = _balances[_for].add(_amount);
                                //take tokens from sender
                                stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
                        
                                emit Staked(msg.sender, _amount);
                            }
                        
                            function withdraw(uint256 _amount, bool claim)
                                public
                                updateReward(msg.sender)
                            {
                                require(_amount > 0, 'RewardPool : Cannot withdraw 0');
                        
                                //also withdraw from linked rewards
                                uint256 length = extraRewards.length;
                                for(uint i=0; i < length; i++){
                                    IRewards(extraRewards[i]).withdraw(msg.sender, _amount);
                                }
                        
                                _totalSupply = _totalSupply.sub(_amount);
                                _balances[msg.sender] = _balances[msg.sender].sub(_amount);
                                stakingToken.safeTransfer(msg.sender, _amount);
                                emit Withdrawn(msg.sender, _amount);
                        
                                if(claim){
                                    getReward(msg.sender,true,false);
                                }
                            }
                        
                            function withdrawAll(bool claim) external{
                                withdraw(_balances[msg.sender],claim);
                            }
                        
                            function getReward(address _account, bool _claimExtras, bool _stake) public updateReward(_account){
                                uint256 reward = earnedReward(_account);
                                if (reward > 0) {
                                    rewards[_account] = 0;
                                    rewardToken.safeApprove(crvDeposits,0);
                                    rewardToken.safeApprove(crvDeposits,reward);
                                    ICrvDeposit(crvDeposits).deposit(reward,false);
                        
                                    uint256 cvxCrvBalance = cvxCrvToken.balanceOf(address(this));
                                    if(_stake){
                                        IERC20(cvxCrvToken).safeApprove(cvxCrvRewards,0);
                                        IERC20(cvxCrvToken).safeApprove(cvxCrvRewards,cvxCrvBalance);
                                        IRewards(cvxCrvRewards).stakeFor(_account,cvxCrvBalance);
                                    }else{
                                        cvxCrvToken.safeTransfer(_account, cvxCrvBalance);
                                    }
                                    emit RewardPaid(_account, cvxCrvBalance);
                                }
                        
                                //also get rewards from linked rewards
                                if(_claimExtras){
                                    uint256 length = extraRewards.length;
                                    for(uint i=0; i < length; i++){
                                        IRewards(extraRewards[i]).getReward(_account);
                                    }
                                }
                            }
                        
                            function getReward(bool _stake) external{
                                getReward(msg.sender,true, _stake);
                            }
                        
                            function donate(uint256 _amount) external returns(bool){
                                IERC20(rewardToken).safeTransferFrom(msg.sender, address(this), _amount);
                                queuedRewards = queuedRewards.add(_amount);
                            }
                        
                            function queueNewRewards(uint256 _rewards) external{
                                require(msg.sender == operator, "!authorized");
                        
                                _rewards = _rewards.add(queuedRewards);
                        
                                if (block.timestamp >= periodFinish) {
                                    notifyRewardAmount(_rewards);
                                    queuedRewards = 0;
                                    return;
                                }
                        
                                //et = now - (finish-duration)
                                uint256 elapsedTime = block.timestamp.sub(periodFinish.sub(duration));
                                //current at now: rewardRate * elapsedTime
                                uint256 currentAtNow = rewardRate * elapsedTime;
                                uint256 queuedRatio = currentAtNow.mul(1000).div(_rewards);
                                if(queuedRatio < newRewardRatio){
                                    notifyRewardAmount(_rewards);
                                    queuedRewards = 0;
                                }else{
                                    queuedRewards = _rewards;
                                }
                            }
                        
                            function notifyRewardAmount(uint256 reward)
                                internal
                                updateReward(address(0))
                            {
                                historicalRewards = historicalRewards.add(reward);
                                if (block.timestamp >= periodFinish) {
                                    rewardRate = reward.div(duration);
                                } else {
                                    uint256 remaining = periodFinish.sub(block.timestamp);
                                    uint256 leftover = remaining.mul(rewardRate);
                                    reward = reward.add(leftover);
                                    rewardRate = reward.div(duration);
                                }
                                currentRewards = reward;
                                lastUpdateTime = block.timestamp;
                                periodFinish = block.timestamp.add(duration);
                                emit RewardAdded(reward);
                            }
                        }

                        File 16 of 18: WarRatiosV2
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IRatios} from "interfaces/IRatios.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {Owner} from "utils/Owner.sol";
                        /**
                         * @title Warlord WAR minting ratios contract V2
                         * @author Paladin
                         * @notice Calculate the amounts of WAR to mint or burn
                         */
                        contract WarRatiosV2 is IRatios, Owner {
                          /**
                           * @notice 1e18 scale
                           */
                          uint256 private constant UNIT = 1e18;
                          /**
                           * @notice Amount of WAR to mint per token for each listed token
                           */
                          mapping(address => uint256) public warPerToken;
                          /**
                           * @notice Returns the ratio for a given token
                           * @param token Address of the token
                           */
                          function getTokenRatio(address token) external view returns (uint256) {
                            return warPerToken[token];
                          }
                          /**
                           * @notice Adds a new token and sets the ratio of WAR to mint per token
                           * @param token Address of the token
                           * @param warRatio Amount of WAR minted per token
                           */
                          function addToken(address token, uint256 warRatio) external onlyOwner {
                            if (token == address(0)) revert Errors.ZeroAddress();
                            if (warRatio == 0) revert Errors.ZeroValue();
                            if (warPerToken[token] != 0) revert Errors.RatioAlreadySet();
                            warPerToken[token] = warRatio;
                          }
                          /**
                           * @notice Returns the amount of WAR to mint for a given amount of token
                           * @param token Address of the token
                           * @param amount Amount of token received
                           * @return mintAmount (uint256) : Amount to mint
                           */
                          function getMintAmount(address token, uint256 amount) external view returns (uint256 mintAmount) {
                            if (token == address(0)) revert Errors.ZeroAddress();
                            if (amount == 0) revert Errors.ZeroValue();
                            mintAmount = amount * warPerToken[token] / UNIT;
                          }
                          /**
                           * @notice Returns the amount of token to redeem for a given amount of WAR burned
                           * @param token Address of the token
                           * @param burnAmount Amount of WAR to burn
                           * @return redeemAmount (uint256) : Redeem amount
                           */
                          function getBurnAmount(address token, uint256 burnAmount) external view returns (uint256 redeemAmount) {
                            if (token == address(0)) revert Errors.ZeroAddress();
                            if (burnAmount == 0) revert Errors.ZeroValue();
                            redeemAmount = burnAmount * UNIT / warPerToken[token];
                          }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IRatios {
                          function getTokenRatio(address token) external view returns (uint256);
                          function addToken(address token, uint256 maxSupply) external;
                          function getMintAmount(address token, uint256 amount) external view returns (uint256 mintAmount);
                          function getBurnAmount(address token, uint256 amount) external view returns (uint256 burnAmount);
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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
                        // 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;
                            }
                        }
                        

                        File 17 of 18: WarCvxCrvFarmer
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {CvxCrvStaking} from "interfaces/external/convex/CvxCrvStaking.sol";
                        import {CrvDepositor} from "interfaces/external/convex/CrvDepositor.sol";
                        import "./BaseFarmer.sol";
                        /**
                         * @title Warlord cvxCRV Farmer contract
                         * @author Paladin
                         * @notice Contract receiving cvxCRV or CRV to farm cvxCRV rewards
                         */
                        contract WarCvxCrvFarmer is WarBaseFarmer {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice Address of the CRV token
                           */
                          IERC20 private constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
                          /**
                           * @notice Address of the cvxCRV token
                           */
                          IERC20 private constant cvxCrv = IERC20(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
                          /**
                           * @notice Address of the cvxCRV staking contract
                           */
                          CvxCrvStaking private constant cvxCrvStaker = CvxCrvStaking(0xaa0C3f5F7DFD688C6E646F66CD2a6B66ACdbE434);
                          /**
                           * @notice Address of the Convex CRV depositor contract
                           */
                          CrvDepositor private constant crvDepositor = CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae);
                          // Constructor
                          constructor(address _controller, address _warStaker) WarBaseFarmer(_controller, _warStaker) {}
                          /**
                           * @notice Returns the token staked by this contract
                           * @return address : address of the token
                           */
                          function token() external pure returns (address) {
                            return address(cvxCrv);
                          }
                          /**
                           * @notice Sets the reward weight for the cvxCRV staking contract
                           * @param weight Weight parameter
                           */
                          function setRewardWeight(uint256 weight) external onlyOwner whenNotPaused {
                            cvxCrvStaker.setRewardWeight(weight);
                          }
                          /**
                           * @dev Checks if the token is supported by the Farmer
                           * @param _token Address of the token to check
                           * @return bool : True if the token is supported
                           */
                          function _isTokenSupported(address _token) internal pure override returns (bool) {
                            return _token == address(crv) || _token == address(cvxCrv);
                          }
                          /**
                           * @dev Stakes the given token (deposits beforehand if needed)
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           * @return uint256 : Amount staked
                           */
                          function _stake(address _token, uint256 _amount) internal override returns (uint256) {
                            IERC20(_token).safeTransferFrom(controller, address(this), _amount);
                            uint256 stakableAmount = _amount;
                            if (_token == address(crv)) {
                              uint256 initialBalance = cvxCrv.balanceOf(address(this));
                              if (crv.allowance(address(this), address(crvDepositor)) != 0) crv.safeApprove(address(crvDepositor), 0);
                              crv.safeIncreaseAllowance(address(crvDepositor), _amount);
                              crvDepositor.deposit(_amount, true, address(0));
                              stakableAmount = cvxCrv.balanceOf(address(this)) - initialBalance;
                            }
                            _index += stakableAmount;
                            if (cvxCrv.allowance(address(this), address(cvxCrvStaker)) != 0) cvxCrv.safeApprove(address(cvxCrvStaker), 0);
                            cvxCrv.safeIncreaseAllowance(address(cvxCrvStaker), stakableAmount);
                            cvxCrvStaker.stake(stakableAmount, address(this));
                            return stakableAmount;
                          }
                          /**
                           * @dev Harvests rewards from the staking contract & sends them to the Controller
                           */
                          function _harvest() internal override {
                            cvxCrvStaker.getReward(address(this), controller);
                          }
                          /**
                           * @dev Returns the balance of tokens staked by this contract in the staking contract
                           * @return uint256 : staked balance for this contract
                           */
                          function _stakedBalance() internal view override returns (uint256) {
                            return cvxCrvStaker.balanceOf(address(this));
                          }
                          /**
                           * @dev Withdraws tokens and sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function _sendTokens(address receiver, uint256 amount) internal override {
                            cvxCrvStaker.withdraw(amount);
                            cvxCrv.safeTransfer(receiver, amount);
                          }
                          /**
                           * @dev Withdraws & migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal override {
                            // Unstake and send cvxCrv
                            uint256 cvxCrvStakedBalance = cvxCrvStaker.balanceOf(address(this));
                            cvxCrvStaker.withdraw(cvxCrvStakedBalance);
                            cvxCrv.safeTransfer(receiver, cvxCrvStakedBalance);
                          }
                          /**
                           * @notice Recover ERC2O tokens in the contract
                           * @dev Recover ERC2O tokens in the contract
                           * @param _token Address of the ERC2O token
                           * @return bool: success
                           */
                          function recoverERC20(address _token) external onlyOwner returns (bool) {
                            if (_token == address(cvxCrvStaker)) revert Errors.RecoverForbidden();
                            if (_token == address(0)) revert Errors.ZeroAddress();
                            uint256 amount = IERC20(_token).balanceOf(address(this));
                            if (amount == 0) revert Errors.ZeroValue();
                            IERC20(_token).safeTransfer(owner(), amount);
                            return true;
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.6.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.8.0) (token/ERC20/utils/SafeERC20.sol)
                        pragma solidity ^0.8.0;
                        import "../IERC20.sol";
                        import "../extensions/draft-IERC20Permit.sol";
                        import "../../../utils/Address.sol";
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using Address for address;
                            function safeTransfer(
                                IERC20 token,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(
                                IERC20 token,
                                address from,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                require(
                                    (value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                uint256 newAllowance = token.allowance(address(this), spender) + value;
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                unchecked {
                                    uint256 oldAllowance = token.allowance(address(this), spender);
                                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                    uint256 newAllowance = oldAllowance - value;
                                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                }
                            }
                            function safePermit(
                                IERC20Permit token,
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                uint256 nonceBefore = token.nonces(owner);
                                token.permit(owner, spender, value, deadline, v, r, s);
                                uint256 nonceAfter = token.nonces(owner);
                                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) {
                                    // Return data is optional
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        pragma solidity 0.8.16;
                        interface CvxCrvStaking {
                          event Approval(address indexed owner, address indexed spender, uint256 value);
                          event Deposited(address indexed _user, address indexed _account, uint256 _amount, bool _isCrv);
                          event HookSet(address _rewardToken);
                          event IsShutdown();
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                          event RewardGroupSet(address _rewardToken, uint256 _rewardGroup);
                          event RewardInvalidated(address _rewardToken);
                          event RewardPaid(address indexed _user, address indexed _token, uint256 _amount, address _receiver);
                          event Transfer(address indexed from, address indexed to, uint256 value);
                          event Withdrawn(address indexed _user, uint256 _amount);
                          struct EarnedData {
                            address token;
                            uint256 amount;
                          }
                          function addTokenReward(address _token, uint256 _rewardGroup) external;
                          function allowance(address owner, address spender) external view returns (uint256);
                          function approve(address spender, uint256 amount) external returns (bool);
                          function balanceOf(address account) external view returns (uint256);
                          function crv() external view returns (address);
                          function crvDepositor() external view returns (address);
                          function cvx() external view returns (address);
                          function cvxCrv() external view returns (address);
                          function cvxCrvStaking() external view returns (address);
                          function decimals() external view returns (uint8);
                          function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
                          function deposit(uint256 _amount, address _to) external;
                          function depositAndSetWeight(uint256 _amount, uint256 _weight) external;
                          function earned(address _account) external returns (CvxCrvStaking.EarnedData[] memory claimable);
                          function getReward(address _account, address _forwardTo) external;
                          function getReward(address _account) external;
                          function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
                          function invalidateReward(address _token) external;
                          function isShutdown() external view returns (bool);
                          function name() external view returns (string memory);
                          function owner() external view returns (address);
                          function reclaim() external;
                          function registeredRewards(address) external view returns (uint256);
                          function renounceOwnership() external;
                          function rewardHook() external view returns (address);
                          function rewardLength() external view returns (uint256);
                          function rewardSupply(uint256 _rewardGroup) external view returns (uint256);
                          function rewards(uint256)
                            external
                            view
                            returns (address reward_token, uint8 reward_group, uint128 reward_integral, uint128 reward_remaining);
                          function setApprovals() external;
                          function setHook(address _hook) external;
                          function setRewardGroup(address _token, uint256 _rewardGroup) external;
                          function setRewardWeight(uint256 _weight) external;
                          function shutdown() external;
                          function stake(uint256 _amount, address _to) external;
                          function stakeAndSetWeight(uint256 _amount, uint256 _weight) external;
                          function stakeFor(address _to, uint256 _amount) external;
                          function supplyWeight() external view returns (uint256);
                          function symbol() external view returns (string memory);
                          function threeCrv() external view returns (address);
                          function totalSupply() external view returns (uint256);
                          function transfer(address recipient, uint256 amount) external returns (bool);
                          function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                          function transferOwnership(address newOwner) external;
                          function treasury() external view returns (address);
                          function userRewardBalance(address _address, uint256 _rewardGroup) external view returns (uint256);
                          function userRewardWeight(address) external view returns (uint256);
                          function user_checkpoint(address _account) external returns (bool);
                          function withdraw(uint256 _amount) external;
                        }
                        pragma solidity ^0.8.10;
                        interface CrvDepositor {
                          function FEE_DENOMINATOR() external view returns (uint256);
                          function crv() external view returns (address);
                          function deposit(uint256 _amount, bool _lock, address _stakeAddress) external;
                          function deposit(uint256 _amount, bool _lock) external;
                          function depositAll(bool _lock, address _stakeAddress) external;
                          function escrow() external view returns (address);
                          function feeManager() external view returns (address);
                          function incentiveCrv() external view returns (uint256);
                          function initialLock() external;
                          function lockCurve() external;
                          function lockIncentive() external view returns (uint256);
                          function minter() external view returns (address);
                          function setFeeManager(address _feeManager) external;
                          function setFees(uint256 _lockIncentive) external;
                          function staker() external view returns (address);
                          function unlockTime() external view returns (uint256);
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {Harvestable} from "./Harvestable.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {Pausable} from "openzeppelin/security/Pausable.sol";
                        import {IFarmer} from "interfaces/IFarmer.sol";
                        import {ReentrancyGuard} from "solmate/utils/ReentrancyGuard.sol";
                        /**
                         * @title Warlord Base Farmer contract
                         * @author Paladin
                         * @notice Base implementation for Farmer contracts
                         */
                        abstract contract WarBaseFarmer is IFarmer, Owner, Pausable, ReentrancyGuard, Harvestable {
                          /**
                           * @notice Address of the Controller contract
                           */
                          address public controller;
                          /**
                           * @notice Address of the Staker contract
                           */
                          address public warStaker;
                          /**
                           * @notice Current index for the token
                           */
                          uint256 internal _index;
                          /**
                           * @notice Event emitted when the Controller is set
                           */
                          event SetController(address controller);
                          /**
                           * @notice Event emitted when the Staker is set
                           */
                          event SetWarStaker(address warStaker);
                          /**
                           * @notice Event emitted when tokens are staked
                           */
                          event Staked(uint256 amount);
                          // Modifiers
                          /**
                           * @notice Checks the caller is the Controller
                           */
                          modifier onlyController() {
                            if (controller != msg.sender) revert Errors.CallerNotAllowed();
                            _;
                          }
                          /**
                           * @notice Checks the caller is the Staker
                           */
                          modifier onlyWarStaker() {
                            if (warStaker != msg.sender) revert Errors.CallerNotAllowed();
                            _;
                          }
                          // Constructor
                          constructor(address _controller, address _warStaker) {
                            if (_controller == address(0) || _warStaker == address(0)) revert Errors.ZeroAddress();
                            controller = _controller;
                            warStaker = _warStaker;
                          }
                          /**
                           * @dev Checks if the token is supported by the Farmer
                           * @param _token Address of the token to check
                           * @return bool : True if the token is supported
                           */
                          function _isTokenSupported(address _token) internal virtual returns (bool);
                          /**
                           * @dev Stakes the given token (deposits beforehand if needed)
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           * @return uint256 : Amount staked
                           */
                          function _stake(address _token, uint256 _amount) internal virtual returns (uint256);
                          /**
                           * @notice Stakes the given token
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           */
                          function stake(address _token, uint256 _amount) external nonReentrant onlyController whenNotPaused {
                            if (!_isTokenSupported(_token)) revert Errors.IncorrectToken();
                            if (_amount == 0) revert Errors.ZeroValue();
                            // Staked amount may change from initial argument when wrapping BAL into auraBAL
                            uint256 amountStaked = _stake(_token, _amount);
                            emit Staked(amountStaked);
                          }
                          /**
                           * @dev Harvests rewards from the staking contract & sends them to the Controller
                           */
                          function _harvest() internal virtual;
                          /**
                           * @notice Harvests rewards from the staking contract
                           */
                          function harvest() external nonReentrant whenNotPaused {
                            _harvest();
                          }
                          /**
                           * @notice Returns the current reward index for the Staker distribution
                           * @return uint256 : current index
                           */
                          function getCurrentIndex() external view returns (uint256) {
                            return _index;
                          }
                          /**
                           * @dev Returns the balance of tokens staked by this contract in the staking contract
                           * @return uint256 : staked balance for this contract
                           */
                          function _stakedBalance() internal virtual returns (uint256);
                          /**
                           * @dev Withdraws tokens and sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function _sendTokens(address receiver, uint256 amount) internal virtual;
                          /**
                           * @notice Sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function sendTokens(address receiver, uint256 amount) external nonReentrant onlyWarStaker whenNotPaused {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            if (amount == 0) revert Errors.ZeroValue();
                            if (_stakedBalance() < amount) revert Errors.UnstakingMoreThanBalance();
                            _sendTokens(receiver, amount);
                          }
                          /**
                           * @dev Withdraws & migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal virtual;
                          /**
                           * @notice Migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function migrate(address receiver) external nonReentrant onlyOwner whenPaused {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            _migrate(receiver);
                            // Harvest and send rewards to the controller
                            _harvest();
                          }
                          /**
                           * @notice Updates the Controller contract
                           * @param _controller Address of the Controller contract
                           */
                          function setController(address _controller) external onlyOwner {
                            if (_controller == address(0)) revert Errors.ZeroAddress();
                            if (_controller == controller) revert Errors.AlreadySet();
                            controller = _controller;
                            emit SetController(_controller);
                          }
                          /**
                           * @notice Updates the Staked contract
                           * @param _warStaker Address of the Staked contract
                           */
                          function setWarStaker(address _warStaker) external onlyOwner {
                            if (_warStaker == address(0)) revert Errors.ZeroAddress();
                            if (_warStaker == warStaker) revert Errors.AlreadySet();
                            warStaker = _warStaker;
                            emit SetWarStaker(_warStaker);
                          }
                          /**
                           * @notice Pause the contract
                           */
                          function pause() external onlyOwner {
                            _pause();
                          }
                          /**
                           * @notice Unpause the contract
                           */
                          function unpause() external onlyOwner {
                            _unpause();
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @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 IERC20Permit {
                            /**
                             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                             * given ``owner``'s signed approval.
                             *
                             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                             * ordering also apply here.
                             *
                             * 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}).
                             *
                             * For more information on the signature format, see the
                             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                             * section].
                             */
                            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);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
                        pragma solidity ^0.8.1;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             *
                             * [IMPORTANT]
                             * ====
                             * You shouldn't rely on `isContract` to protect against flash loan attacks!
                             *
                             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                             * constructor.
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize/address.code.length, which returns 0
                                // for contracts in construction, since the code is only stored at the end
                                // of the constructor execution.
                                return account.code.length > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                (bool success, ) = recipient.call{value: amount}("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain `call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                (bool success, bytes memory returndata) = target.call{value: value}(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                             *
                             * _Available since v4.8._
                             */
                            function verifyCallResultFromTarget(
                                address target,
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                if (success) {
                                    if (returndata.length == 0) {
                                        // only check isContract if the call was successful and the return data is empty
                                        // otherwise we already know that it was a contract
                                        require(isContract(target), "Address: call to non-contract");
                                    }
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            /**
                             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                             * revert reason or using the provided one.
                             *
                             * _Available since v4.3._
                             */
                            function verifyCallResult(
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal pure returns (bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IHarvestable} from "interfaces/IHarvestable.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Harvestable contract
                         * @author Paladin
                         * @notice Contract harvesting reward tokens to send to the Controller
                         */
                        abstract contract Harvestable is IHarvestable, Owner {
                          /**
                           * @notice List of harvestable reward tokens
                           */
                          address[] private _rewardTokens;
                          /**
                           * @notice Set to true when a reward token is listed
                           */
                          mapping(address => bool) private _rewardAssigned;
                          /**
                           * @notice Returns the list of rewards token that can be harvested for this contract
                           * @return address[] : List of tokens
                           */
                          function rewardTokens() external view returns (address[] memory) {
                            return _rewardTokens;
                          }
                          /**
                           * @notice Adds a token to the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function addReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (_rewardAssigned[reward]) revert Errors.AlreadySet();
                            _rewardTokens.push(reward);
                            _rewardAssigned[reward] = true;
                          }
                          /**
                           * @notice Removes a token from the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function removeReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (!_rewardAssigned[reward]) revert Errors.NotRewardToken();
                            // remove the reward without leaving holes in the array
                            address[] memory rewardTokens_ = _rewardTokens;
                            uint256 length = rewardTokens_.length;
                            uint256 lastIndex = length - 1;
                            for (uint256 i; i < length;) {
                              if (rewardTokens_[i] == reward) {
                                if (i != lastIndex) {
                                  _rewardTokens[i] = rewardTokens_[lastIndex];
                                }
                                _rewardTokens.pop();
                                break;
                              }
                              unchecked {
                                ++i;
                              }
                            }
                            // rewardToken is no longer part of the list
                            _rewardAssigned[reward] = false;
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
                        pragma solidity ^0.8.0;
                        import "../utils/Context.sol";
                        /**
                         * @dev Contract module which allows children to implement an emergency stop
                         * mechanism that can be triggered by an authorized account.
                         *
                         * This module is used through inheritance. It will make available the
                         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                         * the functions of your contract. Note that they will not be pausable by
                         * simply including this module, only once the modifiers are put in place.
                         */
                        abstract contract Pausable is Context {
                            /**
                             * @dev Emitted when the pause is triggered by `account`.
                             */
                            event Paused(address account);
                            /**
                             * @dev Emitted when the pause is lifted by `account`.
                             */
                            event Unpaused(address account);
                            bool private _paused;
                            /**
                             * @dev Initializes the contract in unpaused state.
                             */
                            constructor() {
                                _paused = false;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is not paused.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            modifier whenNotPaused() {
                                _requireNotPaused();
                                _;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is paused.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            modifier whenPaused() {
                                _requirePaused();
                                _;
                            }
                            /**
                             * @dev Returns true if the contract is paused, and false otherwise.
                             */
                            function paused() public view virtual returns (bool) {
                                return _paused;
                            }
                            /**
                             * @dev Throws if the contract is paused.
                             */
                            function _requireNotPaused() internal view virtual {
                                require(!paused(), "Pausable: paused");
                            }
                            /**
                             * @dev Throws if the contract is not paused.
                             */
                            function _requirePaused() internal view virtual {
                                require(paused(), "Pausable: not paused");
                            }
                            /**
                             * @dev Triggers stopped state.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            function _pause() internal virtual whenNotPaused {
                                _paused = true;
                                emit Paused(_msgSender());
                            }
                            /**
                             * @dev Returns to normal state.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            function _unpause() internal virtual whenPaused {
                                _paused = false;
                                emit Unpaused(_msgSender());
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IFarmer {
                          // the index stored by the farmer represents all the recevied tokens
                          function getCurrentIndex() external view returns (uint256);
                          function sendTokens(address receiver, uint256 amount) external;
                          function stake(address token, uint256 amount) external;
                          function token() external view returns (address);
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Gas optimized reentrancy protection for smart contracts.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
                        abstract contract ReentrancyGuard {
                            uint256 private locked = 1;
                            modifier nonReentrant() virtual {
                                require(locked == 1, "REENTRANCY");
                                locked = 2;
                                _;
                                locked = 1;
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IHarvestable {
                          function harvest() external;
                          function rewardTokens() external view returns (address[] memory);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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
                        // 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;
                            }
                        }
                        

                        File 18 of 18: WarAuraBalFarmer
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
                        import {SafeERC20} from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
                        import {BaseRewardPool} from "interfaces/external/aura/AuraBalStaker.sol";
                        import {CrvDepositorWrapper} from "interfaces/external/aura/AuraDepositor.sol";
                        import {IRewards} from "interfaces/external/aura/IRewards.sol";
                        import "./BaseFarmer.sol";
                        /**
                         * @title Warlord auraBAL Farmer contract
                         * @author Paladin
                         * @notice Contract receiving auraBAL or BAL to farm auraBAL rewards
                         */
                        contract WarAuraBalFarmer is WarBaseFarmer {
                          using SafeERC20 for IERC20;
                          /**
                           * @notice Address of the BAL token
                           */
                          IERC20 private constant bal = IERC20(0xba100000625a3754423978a60c9317c58a424e3D);
                          /**
                           * @notice Address of the AURA token
                           */
                          IERC20 private constant aura = IERC20(0xC0c293ce456fF0ED870ADd98a0828Dd4d2903DBF);
                          /**
                           * @notice Address of the auraBAL token
                           */
                          IERC20 private constant auraBal = IERC20(0x616e8BfA43F920657B3497DBf40D6b1A02D4608d);
                          /**
                           * @notice Address of the auraBAL staking contract
                           */
                          BaseRewardPool private constant auraBalStaker = BaseRewardPool(0x00A7BA8Ae7bca0B10A32Ea1f8e2a1Da980c6CAd2);
                          /**
                           * @notice Address of the Aura BAL Depositor contract
                           */
                          CrvDepositorWrapper private constant balDepositor = CrvDepositorWrapper(0x68655AD9852a99C87C0934c7290BB62CFa5D4123);
                          /**
                           * @notice Allowed BPS slippage for BAL deposits
                           */
                          uint256 public slippageBps;
                          /**
                           * @notice Event emitted when the allowed slippage is updated
                           */
                          event SetSlippage(uint256 oldSlippage, uint256 newSlippage);
                          // Constructor
                          constructor(address _controller, address _warStaker) WarBaseFarmer(_controller, _warStaker) {
                            // Slippage initial set at 0.5%
                            slippageBps = 9950;
                          }
                          /**
                           * @notice Returns the token staked by this contract
                           * @return address : address of the token
                           */
                          function token() external pure returns (address) {
                            return address(auraBal);
                          }
                          /**
                           * @notice Sets the slippage allowed for BAL deposits
                           * @param _slippageBps Slippage parameter
                           */
                          function setSlippage(uint256 _slippageBps) external onlyOwner {
                            if (_slippageBps > 500) revert Errors.SlippageTooHigh();
                            uint256 oldSlippage = slippageBps;
                            slippageBps = 10_000 - _slippageBps;
                            emit SetSlippage(oldSlippage, slippageBps);
                          }
                          /**
                           * @dev Checks if the token is supported by the Farmer
                           * @param _token Address of the token to check
                           * @return bool : True if the token is supported
                           */
                          function _isTokenSupported(address _token) internal pure override returns (bool) {
                            return _token == address(bal) || _token == address(auraBal);
                          }
                          /**
                           * @dev Stakes the given token (deposits beforehand if needed)
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           * @return uint256 : Amount staked
                           */
                          function _stake(address _token, uint256 _amount) internal override returns (uint256) {
                            IERC20(_token).safeTransferFrom(controller, address(this), _amount);
                            // Variable used to store the amount of BPT created if token is bal
                            uint256 stakableAmount = _amount;
                            if (_token == address(bal)) {
                              uint256 initialBalance = auraBal.balanceOf(address(this));
                              if (bal.allowance(address(this), address(balDepositor)) != 0) bal.safeApprove(address(balDepositor), 0);
                              bal.safeIncreaseAllowance(address(balDepositor), _amount);
                              uint256 minOut = balDepositor.getMinOut(_amount, slippageBps);
                              balDepositor.deposit(_amount, minOut, true, address(0));
                              stakableAmount = auraBal.balanceOf(address(this)) - initialBalance;
                            }
                            _index += stakableAmount;
                            if (auraBal.allowance(address(this), address(auraBalStaker)) != 0) auraBal.safeApprove(address(auraBalStaker), 0);
                            auraBal.safeIncreaseAllowance(address(auraBalStaker), stakableAmount);
                            auraBalStaker.stake(stakableAmount);
                            return stakableAmount;
                          }
                          /**
                           * @dev Harvests rewards from the staking contract & sends them to the Controller
                           */
                          function _harvest() internal override {
                            auraBalStaker.getReward(address(this), true);
                            bal.safeTransfer(controller, bal.balanceOf(address(this)));
                            aura.safeTransfer(controller, aura.balanceOf(address(this)));
                            uint256 extraRewardsLength = auraBalStaker.extraRewardsLength();
                            for (uint256 i; i < extraRewardsLength;) {
                              IRewards rewarder = IRewards(auraBalStaker.extraRewards(i));
                              IERC20 _token = IERC20(rewarder.rewardToken());
                              uint256 balance = _token.balanceOf(address(this));
                              if (balance != 0) {
                                _token.safeTransfer(controller, balance);
                              }
                              unchecked {
                                ++i;
                              }
                            }
                          }
                          /**
                           * @dev Returns the balance of tokens staked by this contract in the staking contract
                           * @return uint256 : staked balance for this contract
                           */
                          function _stakedBalance() internal view override returns (uint256) {
                            return auraBalStaker.balanceOf(address(this));
                          }
                          /**
                           * @dev Withdraws tokens and sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function _sendTokens(address receiver, uint256 amount) internal override {
                            auraBalStaker.withdraw(amount, false);
                            auraBal.safeTransfer(receiver, amount);
                          }
                          /**
                           * @dev Withdraws & migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal override {
                            // Unstake and send auraBal
                            uint256 auraBalStakedBalance = auraBalStaker.balanceOf(address(this));
                            auraBalStaker.withdraw(auraBalStakedBalance, false);
                            auraBal.safeTransfer(receiver, auraBalStakedBalance);
                          }
                          /**
                           * @notice Recover ERC2O tokens in the contract
                           * @dev Recover ERC2O tokens in the contract
                           * @param _token Address of the ERC2O token
                           * @return bool: success
                           */
                          function recoverERC20(address _token) external onlyOwner returns (bool) {
                            if (_token == address(0)) revert Errors.ZeroAddress();
                            uint256 amount = IERC20(_token).balanceOf(address(this));
                            if (amount == 0) revert Errors.ZeroValue();
                            IERC20(_token).safeTransfer(owner(), amount);
                            return true;
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.6.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.8.0) (token/ERC20/utils/SafeERC20.sol)
                        pragma solidity ^0.8.0;
                        import "../IERC20.sol";
                        import "../extensions/draft-IERC20Permit.sol";
                        import "../../../utils/Address.sol";
                        /**
                         * @title SafeERC20
                         * @dev Wrappers around ERC20 operations that throw on failure (when the token
                         * contract returns false). Tokens that return no value (and instead revert or
                         * throw on failure) are also supported, non-reverting calls are assumed to be
                         * successful.
                         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                         */
                        library SafeERC20 {
                            using Address for address;
                            function safeTransfer(
                                IERC20 token,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                            }
                            function safeTransferFrom(
                                IERC20 token,
                                address from,
                                address to,
                                uint256 value
                            ) internal {
                                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                            }
                            /**
                             * @dev Deprecated. This function has issues similar to the ones found in
                             * {IERC20-approve}, and its usage is discouraged.
                             *
                             * Whenever possible, use {safeIncreaseAllowance} and
                             * {safeDecreaseAllowance} instead.
                             */
                            function safeApprove(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                // safeApprove should only be called when setting an initial allowance,
                                // or when resetting it to zero. To increase and decrease it, use
                                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                require(
                                    (value == 0) || (token.allowance(address(this), spender) == 0),
                                    "SafeERC20: approve from non-zero to non-zero allowance"
                                );
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                            }
                            function safeIncreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                uint256 newAllowance = token.allowance(address(this), spender) + value;
                                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                            }
                            function safeDecreaseAllowance(
                                IERC20 token,
                                address spender,
                                uint256 value
                            ) internal {
                                unchecked {
                                    uint256 oldAllowance = token.allowance(address(this), spender);
                                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                    uint256 newAllowance = oldAllowance - value;
                                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                }
                            }
                            function safePermit(
                                IERC20Permit token,
                                address owner,
                                address spender,
                                uint256 value,
                                uint256 deadline,
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            ) internal {
                                uint256 nonceBefore = token.nonces(owner);
                                token.permit(owner, spender, value, deadline, v, r, s);
                                uint256 nonceAfter = token.nonces(owner);
                                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                            }
                            /**
                             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                             * on the return value: the return value is optional (but if data is returned, it must not be false).
                             * @param token The token targeted by the call.
                             * @param data The call data (encoded using abi.encode or one of its variants).
                             */
                            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                // the target address contains contract code and also asserts for success in the low-level call.
                                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                if (returndata.length > 0) {
                                    // Return data is optional
                                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                }
                            }
                        }
                        pragma solidity ^0.8.10;
                        interface BaseRewardPool {
                          event RewardAdded(uint256 reward);
                          event RewardPaid(address indexed user, uint256 reward);
                          event Staked(address indexed user, uint256 amount);
                          event Transfer(address indexed from, address indexed to, uint256 value);
                          event Withdrawn(address indexed user, uint256 amount);
                          function addExtraReward(address _reward) external returns (bool);
                          function balanceOf(address account) external view returns (uint256);
                          function clearExtraRewards() external;
                          function currentRewards() external view returns (uint256);
                          function duration() external view returns (uint256);
                          function earned(address account) external view returns (uint256);
                          function extraRewards(uint256) external view returns (address);
                          function extraRewardsLength() external view returns (uint256);
                          function getReward() external returns (bool);
                          function getReward(address _account, bool _claimExtras) external returns (bool);
                          function historicalRewards() external view returns (uint256);
                          function lastTimeRewardApplicable() external view returns (uint256);
                          function lastUpdateTime() external view returns (uint256);
                          function newRewardRatio() external view returns (uint256);
                          function operator() external view returns (address);
                          function periodFinish() external view returns (uint256);
                          function pid() external view returns (uint256);
                          function processIdleRewards() external;
                          function queueNewRewards(uint256 _rewards) external returns (bool);
                          function queuedRewards() external view returns (uint256);
                          function rewardManager() external view returns (address);
                          function rewardPerToken() external view returns (uint256);
                          function rewardPerTokenStored() external view returns (uint256);
                          function rewardRate() external view returns (uint256);
                          function rewardToken() external view returns (address);
                          function rewards(address) external view returns (uint256);
                          function stake(uint256 _amount) external returns (bool);
                          function stakeAll() external returns (bool);
                          function stakeFor(address _for, uint256 _amount) external returns (bool);
                          function stakingToken() external view returns (address);
                          function totalSupply() external view returns (uint256);
                          function userRewardPerTokenPaid(address) external view returns (uint256);
                          function withdraw(uint256 amount, bool claim) external returns (bool);
                          function withdrawAll(bool claim) external;
                          function withdrawAllAndUnwrap(bool claim) external;
                          function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
                        }
                        pragma solidity ^0.8.10;
                        interface CrvDepositorWrapper {
                          function BAL() external view returns (address);
                          function BALANCER_POOL_TOKEN() external view returns (address);
                          function BALANCER_VAULT() external view returns (address);
                          function BAL_ETH_POOL_ID() external view returns (bytes32);
                          function WETH() external view returns (address);
                          function crvDeposit() external view returns (address);
                          function deposit(uint256 _amount, uint256 _minOut, bool _lock, address _stakeAddress) external;
                          function getMinOut(uint256 _amount, uint256 _outputBps) external view returns (uint256);
                          function setApprovals() external;
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IRewards {
                          function stake(address, uint256) external;
                          function stakeFor(address, uint256) external;
                          function withdraw(address, uint256) external;
                          function exit(address) external;
                          function getReward(address) external;
                          function queueNewRewards(uint256) external;
                          function notifyRewardAmount(uint256) external;
                          function addExtraReward(address) external;
                          function extraRewardsLength() external view returns (uint256);
                          function stakingToken() external view returns (address);
                          function rewardToken() external view returns (address);
                          function earned(address account) external view returns (uint256);
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {Harvestable} from "./Harvestable.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        import {Pausable} from "openzeppelin/security/Pausable.sol";
                        import {IFarmer} from "interfaces/IFarmer.sol";
                        import {ReentrancyGuard} from "solmate/utils/ReentrancyGuard.sol";
                        /**
                         * @title Warlord Base Farmer contract
                         * @author Paladin
                         * @notice Base implementation for Farmer contracts
                         */
                        abstract contract WarBaseFarmer is IFarmer, Owner, Pausable, ReentrancyGuard, Harvestable {
                          /**
                           * @notice Address of the Controller contract
                           */
                          address public controller;
                          /**
                           * @notice Address of the Staker contract
                           */
                          address public warStaker;
                          /**
                           * @notice Current index for the token
                           */
                          uint256 internal _index;
                          /**
                           * @notice Event emitted when the Controller is set
                           */
                          event SetController(address controller);
                          /**
                           * @notice Event emitted when the Staker is set
                           */
                          event SetWarStaker(address warStaker);
                          /**
                           * @notice Event emitted when tokens are staked
                           */
                          event Staked(uint256 amount);
                          // Modifiers
                          /**
                           * @notice Checks the caller is the Controller
                           */
                          modifier onlyController() {
                            if (controller != msg.sender) revert Errors.CallerNotAllowed();
                            _;
                          }
                          /**
                           * @notice Checks the caller is the Staker
                           */
                          modifier onlyWarStaker() {
                            if (warStaker != msg.sender) revert Errors.CallerNotAllowed();
                            _;
                          }
                          // Constructor
                          constructor(address _controller, address _warStaker) {
                            if (_controller == address(0) || _warStaker == address(0)) revert Errors.ZeroAddress();
                            controller = _controller;
                            warStaker = _warStaker;
                          }
                          /**
                           * @dev Checks if the token is supported by the Farmer
                           * @param _token Address of the token to check
                           * @return bool : True if the token is supported
                           */
                          function _isTokenSupported(address _token) internal virtual returns (bool);
                          /**
                           * @dev Stakes the given token (deposits beforehand if needed)
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           * @return uint256 : Amount staked
                           */
                          function _stake(address _token, uint256 _amount) internal virtual returns (uint256);
                          /**
                           * @notice Stakes the given token
                           * @param _token Address of the token to stake
                           * @param _amount Amount to stake
                           */
                          function stake(address _token, uint256 _amount) external nonReentrant onlyController whenNotPaused {
                            if (!_isTokenSupported(_token)) revert Errors.IncorrectToken();
                            if (_amount == 0) revert Errors.ZeroValue();
                            // Staked amount may change from initial argument when wrapping BAL into auraBAL
                            uint256 amountStaked = _stake(_token, _amount);
                            emit Staked(amountStaked);
                          }
                          /**
                           * @dev Harvests rewards from the staking contract & sends them to the Controller
                           */
                          function _harvest() internal virtual;
                          /**
                           * @notice Harvests rewards from the staking contract
                           */
                          function harvest() external nonReentrant whenNotPaused {
                            _harvest();
                          }
                          /**
                           * @notice Returns the current reward index for the Staker distribution
                           * @return uint256 : current index
                           */
                          function getCurrentIndex() external view returns (uint256) {
                            return _index;
                          }
                          /**
                           * @dev Returns the balance of tokens staked by this contract in the staking contract
                           * @return uint256 : staked balance for this contract
                           */
                          function _stakedBalance() internal virtual returns (uint256);
                          /**
                           * @dev Withdraws tokens and sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function _sendTokens(address receiver, uint256 amount) internal virtual;
                          /**
                           * @notice Sends them to the receiver
                           * @param receiver Address to receive the tokens
                           * @param amount Amount to send
                           */
                          function sendTokens(address receiver, uint256 amount) external nonReentrant onlyWarStaker whenNotPaused {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            if (amount == 0) revert Errors.ZeroValue();
                            if (_stakedBalance() < amount) revert Errors.UnstakingMoreThanBalance();
                            _sendTokens(receiver, amount);
                          }
                          /**
                           * @dev Withdraws & migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function _migrate(address receiver) internal virtual;
                          /**
                           * @notice Migrates the tokens hold by this contract to another address
                           * @param receiver Address to receive the migrated tokens
                           */
                          function migrate(address receiver) external nonReentrant onlyOwner whenPaused {
                            if (receiver == address(0)) revert Errors.ZeroAddress();
                            _migrate(receiver);
                            // Harvest and send rewards to the controller
                            _harvest();
                          }
                          /**
                           * @notice Updates the Controller contract
                           * @param _controller Address of the Controller contract
                           */
                          function setController(address _controller) external onlyOwner {
                            if (_controller == address(0)) revert Errors.ZeroAddress();
                            if (_controller == controller) revert Errors.AlreadySet();
                            controller = _controller;
                            emit SetController(_controller);
                          }
                          /**
                           * @notice Updates the Staked contract
                           * @param _warStaker Address of the Staked contract
                           */
                          function setWarStaker(address _warStaker) external onlyOwner {
                            if (_warStaker == address(0)) revert Errors.ZeroAddress();
                            if (_warStaker == warStaker) revert Errors.AlreadySet();
                            warStaker = _warStaker;
                            emit SetWarStaker(_warStaker);
                          }
                          /**
                           * @notice Pause the contract
                           */
                          function pause() external onlyOwner {
                            _pause();
                          }
                          /**
                           * @notice Unpause the contract
                           */
                          function unpause() external onlyOwner {
                            _unpause();
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                        pragma solidity ^0.8.0;
                        /**
                         * @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 IERC20Permit {
                            /**
                             * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                             * given ``owner``'s signed approval.
                             *
                             * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                             * ordering also apply here.
                             *
                             * 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}).
                             *
                             * For more information on the signature format, see the
                             * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                             * section].
                             */
                            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);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
                        pragma solidity ^0.8.1;
                        /**
                         * @dev Collection of functions related to the address type
                         */
                        library Address {
                            /**
                             * @dev Returns true if `account` is a contract.
                             *
                             * [IMPORTANT]
                             * ====
                             * It is unsafe to assume that an address for which this function returns
                             * false is an externally-owned account (EOA) and not a contract.
                             *
                             * Among others, `isContract` will return false for the following
                             * types of addresses:
                             *
                             *  - an externally-owned account
                             *  - a contract in construction
                             *  - an address where a contract will be created
                             *  - an address where a contract lived, but was destroyed
                             * ====
                             *
                             * [IMPORTANT]
                             * ====
                             * You shouldn't rely on `isContract` to protect against flash loan attacks!
                             *
                             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                             * constructor.
                             * ====
                             */
                            function isContract(address account) internal view returns (bool) {
                                // This method relies on extcodesize/address.code.length, which returns 0
                                // for contracts in construction, since the code is only stored at the end
                                // of the constructor execution.
                                return account.code.length > 0;
                            }
                            /**
                             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                             * `recipient`, forwarding all available gas and reverting on errors.
                             *
                             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                             * of certain opcodes, possibly making contracts go over the 2300 gas limit
                             * imposed by `transfer`, making them unable to receive funds via
                             * `transfer`. {sendValue} removes this limitation.
                             *
                             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                             *
                             * IMPORTANT: because control is transferred to `recipient`, care must be
                             * taken to not create reentrancy vulnerabilities. Consider using
                             * {ReentrancyGuard} or the
                             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                             */
                            function sendValue(address payable recipient, uint256 amount) internal {
                                require(address(this).balance >= amount, "Address: insufficient balance");
                                (bool success, ) = recipient.call{value: amount}("");
                                require(success, "Address: unable to send value, recipient may have reverted");
                            }
                            /**
                             * @dev Performs a Solidity function call using a low level `call`. A
                             * plain `call` is an unsafe replacement for a function call: use this
                             * function instead.
                             *
                             * If `target` reverts with a revert reason, it is bubbled up by this
                             * function (like regular Solidity function calls).
                             *
                             * Returns the raw returned data. To convert to the expected return value,
                             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                             *
                             * Requirements:
                             *
                             * - `target` must be a contract.
                             * - calling `target` with `data` must not revert.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                             * `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, 0, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but also transferring `value` wei to `target`.
                             *
                             * Requirements:
                             *
                             * - the calling contract must have an ETH balance of at least `value`.
                             * - the called Solidity function must be `payable`.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value
                            ) internal returns (bytes memory) {
                                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                             * with `errorMessage` as a fallback revert reason when `target` reverts.
                             *
                             * _Available since v3.1._
                             */
                            function functionCallWithValue(
                                address target,
                                bytes memory data,
                                uint256 value,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                require(address(this).balance >= value, "Address: insufficient balance for call");
                                (bool success, bytes memory returndata) = target.call{value: value}(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                return functionStaticCall(target, data, "Address: low-level static call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a static call.
                             *
                             * _Available since v3.3._
                             */
                            function functionStaticCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.staticcall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                            }
                            /**
                             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                             * but performing a delegate call.
                             *
                             * _Available since v3.4._
                             */
                            function functionDelegateCall(
                                address target,
                                bytes memory data,
                                string memory errorMessage
                            ) internal returns (bytes memory) {
                                (bool success, bytes memory returndata) = target.delegatecall(data);
                                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                            }
                            /**
                             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                             *
                             * _Available since v4.8._
                             */
                            function verifyCallResultFromTarget(
                                address target,
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal view returns (bytes memory) {
                                if (success) {
                                    if (returndata.length == 0) {
                                        // only check isContract if the call was successful and the return data is empty
                                        // otherwise we already know that it was a contract
                                        require(isContract(target), "Address: call to non-contract");
                                    }
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            /**
                             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                             * revert reason or using the provided one.
                             *
                             * _Available since v4.3._
                             */
                            function verifyCallResult(
                                bool success,
                                bytes memory returndata,
                                string memory errorMessage
                            ) internal pure returns (bytes memory) {
                                if (success) {
                                    return returndata;
                                } else {
                                    _revert(returndata, errorMessage);
                                }
                            }
                            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                        //██████╗  █████╗ ██╗      █████╗ ██████╗ ██╗███╗   ██╗
                        //██╔══██╗██╔══██╗██║     ██╔══██╗██╔══██╗██║████╗  ██║
                        //██████╔╝███████║██║     ███████║██║  ██║██║██╔██╗ ██║
                        //██╔═══╝ ██╔══██║██║     ██╔══██║██║  ██║██║██║╚██╗██║
                        //██║     ██║  ██║███████╗██║  ██║██████╔╝██║██║ ╚████║
                        //╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚═╝╚═╝  ╚═══╝
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: BUSL-1.1
                        import {IHarvestable} from "interfaces/IHarvestable.sol";
                        import {Owner} from "utils/Owner.sol";
                        import {Errors} from "utils/Errors.sol";
                        /**
                         * @title Harvestable contract
                         * @author Paladin
                         * @notice Contract harvesting reward tokens to send to the Controller
                         */
                        abstract contract Harvestable is IHarvestable, Owner {
                          /**
                           * @notice List of harvestable reward tokens
                           */
                          address[] private _rewardTokens;
                          /**
                           * @notice Set to true when a reward token is listed
                           */
                          mapping(address => bool) private _rewardAssigned;
                          /**
                           * @notice Returns the list of rewards token that can be harvested for this contract
                           * @return address[] : List of tokens
                           */
                          function rewardTokens() external view returns (address[] memory) {
                            return _rewardTokens;
                          }
                          /**
                           * @notice Adds a token to the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function addReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (_rewardAssigned[reward]) revert Errors.AlreadySet();
                            _rewardTokens.push(reward);
                            _rewardAssigned[reward] = true;
                          }
                          /**
                           * @notice Removes a token from the list of harvestable tokens
                           * @param reward Address of the token
                           */
                          function removeReward(address reward) external onlyOwner {
                            if (reward == address(0)) revert Errors.ZeroAddress();
                            if (!_rewardAssigned[reward]) revert Errors.NotRewardToken();
                            // remove the reward without leaving holes in the array
                            address[] memory rewardTokens_ = _rewardTokens;
                            uint256 length = rewardTokens_.length;
                            uint256 lastIndex = length - 1;
                            for (uint256 i; i < length;) {
                              if (rewardTokens_[i] == reward) {
                                if (i != lastIndex) {
                                  _rewardTokens[i] = rewardTokens_[lastIndex];
                                }
                                _rewardTokens.pop();
                                break;
                              }
                              unchecked {
                                ++i;
                              }
                            }
                            // rewardToken is no longer part of the list
                            _rewardAssigned[reward] = false;
                          }
                        }
                        // SPDX-License-Identifier: MIT
                        pragma solidity 0.8.16;
                        import "openzeppelin/access/Ownable.sol";
                        /**
                         * @title Extend OZ Ownable contract
                         */
                        /// @author Paladin
                        contract Owner is Ownable {
                          address public pendingOwner;
                          event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error OwnerAddressZero();
                          function transferOwnership(address newOwner) public virtual override onlyOwner {
                            if (newOwner == address(0)) revert OwnerAddressZero();
                            if (newOwner == owner()) revert CannotBeOwner();
                            address oldPendingOwner = pendingOwner;
                            pendingOwner = newOwner;
                            emit NewPendingOwner(oldPendingOwner, newOwner);
                          }
                          function acceptOwnership() public virtual {
                            if (msg.sender != pendingOwner) revert CallerNotPendingOwner();
                            address newOwner = pendingOwner;
                            _transferOwnership(pendingOwner);
                            pendingOwner = address(0);
                            emit NewPendingOwner(newOwner, address(0));
                          }
                        }
                        pragma solidity 0.8.16;
                        //SPDX-License-Identifier: Unlicensed
                        library Errors {
                          // Argument validation
                          error ZeroAddress();
                          error ZeroValue();
                          error DifferentSizeArrays(uint256 size1, uint256 size2);
                          error EmptyArray();
                          error AlreadySet();
                          error SameAddress();
                          error InvalidParameter();
                          // Ownership
                          error CannotBeOwner();
                          error CallerNotPendingOwner();
                          error CallerNotAllowed();
                          // Token
                          error AllowanceUnderflow();
                          // Controller
                          error ListedLocker();
                          error ListedFarmer();
                          error InvalidFeeRatio();
                          error HarvestNotAllowed();
                          // Locker
                          error NoWarLocker(); // _locker[token] == 0x0
                          error LockerShutdown();
                          error MismatchingLocker(address expected, address actual);
                          // Minter
                          error MintAmountBiggerThanSupply();
                          // Redeemer
                          error NotListedLocker();
                          error InvalidIndex();
                          error CannotRedeemYet();
                          error AlreadyRedeemed();
                          error InvalidWeightSum();
                          // Staker
                          error AlreadyListedDepositor();
                          error NotListedDepositor();
                          error MismatchingFarmer();
                          // MintRatio
                          error ZeroMintAmount();
                          error SupplyAlreadySet();
                          error RatioAlreadySet();
                          // Harvestable
                          error NotRewardToken();
                          // IFarmer
                          error IncorrectToken();
                          error UnstakingMoreThanBalance();
                          // Maths
                          error NumberExceed128Bits();
                          // AuraBalFarmer
                          error SlippageTooHigh();
                          // Admin
                          error RecoverForbidden();
                          // AuraLocker
                          error DelegationRequiresLock();
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
                        pragma solidity ^0.8.0;
                        import "../utils/Context.sol";
                        /**
                         * @dev Contract module which allows children to implement an emergency stop
                         * mechanism that can be triggered by an authorized account.
                         *
                         * This module is used through inheritance. It will make available the
                         * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
                         * the functions of your contract. Note that they will not be pausable by
                         * simply including this module, only once the modifiers are put in place.
                         */
                        abstract contract Pausable is Context {
                            /**
                             * @dev Emitted when the pause is triggered by `account`.
                             */
                            event Paused(address account);
                            /**
                             * @dev Emitted when the pause is lifted by `account`.
                             */
                            event Unpaused(address account);
                            bool private _paused;
                            /**
                             * @dev Initializes the contract in unpaused state.
                             */
                            constructor() {
                                _paused = false;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is not paused.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            modifier whenNotPaused() {
                                _requireNotPaused();
                                _;
                            }
                            /**
                             * @dev Modifier to make a function callable only when the contract is paused.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            modifier whenPaused() {
                                _requirePaused();
                                _;
                            }
                            /**
                             * @dev Returns true if the contract is paused, and false otherwise.
                             */
                            function paused() public view virtual returns (bool) {
                                return _paused;
                            }
                            /**
                             * @dev Throws if the contract is paused.
                             */
                            function _requireNotPaused() internal view virtual {
                                require(!paused(), "Pausable: paused");
                            }
                            /**
                             * @dev Throws if the contract is not paused.
                             */
                            function _requirePaused() internal view virtual {
                                require(paused(), "Pausable: not paused");
                            }
                            /**
                             * @dev Triggers stopped state.
                             *
                             * Requirements:
                             *
                             * - The contract must not be paused.
                             */
                            function _pause() internal virtual whenNotPaused {
                                _paused = true;
                                emit Paused(_msgSender());
                            }
                            /**
                             * @dev Returns to normal state.
                             *
                             * Requirements:
                             *
                             * - The contract must be paused.
                             */
                            function _unpause() internal virtual whenPaused {
                                _paused = false;
                                emit Unpaused(_msgSender());
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IFarmer {
                          // the index stored by the farmer represents all the recevied tokens
                          function getCurrentIndex() external view returns (uint256);
                          function sendTokens(address receiver, uint256 amount) external;
                          function stake(address token, uint256 amount) external;
                          function token() external view returns (address);
                        }
                        // SPDX-License-Identifier: AGPL-3.0-only
                        pragma solidity >=0.8.0;
                        /// @notice Gas optimized reentrancy protection for smart contracts.
                        /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
                        /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
                        abstract contract ReentrancyGuard {
                            uint256 private locked = 1;
                            modifier nonReentrant() virtual {
                                require(locked == 1, "REENTRANCY");
                                locked = 2;
                                _;
                                locked = 1;
                            }
                        }
                        // SPDX-License-Identifier: Unlicensed
                        pragma solidity 0.8.16;
                        interface IHarvestable {
                          function harvest() external;
                          function rewardTokens() external view returns (address[] memory);
                        }
                        // SPDX-License-Identifier: MIT
                        // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
                             *
                             * NOTE: Renouncing ownership will leave the contract without an owner,
                             * thereby removing 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
                        // 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;
                            }
                        }