ETH Price: $2,658.13 (+6.15%)

Transaction Decoder

Block:
21542968 at Jan-03-2025 09:09:59 AM +UTC
Transaction Fee:
0.001931806971506152 ETH $5.13
Gas Used:
202,168 Gas / 9.555453739 Gwei

Emitted Events:

173 TransparentUpgradeableProxy.0xd0ed88a3f042c6bbb1e3ea406079b5f2b4b198afccaa535d837f4c63abbc4de6( 0xd0ed88a3f042c6bbb1e3ea406079b5f2b4b198afccaa535d837f4c63abbc4de6, 0000000000000000000000007d8f07b6a09c501ad5e9ba990eaf7fb279258579, 00000000000000000000000005767d9ef41dc40689678ffca0608878fb3de906, 0000000000000000000000000000000000000000000000000038d25abfa5cb00 )
174 UniswapV2Pair.Transfer( from=[Sender] 0x7d8f07b6a09c501ad5e9ba990eaf7fb279258579, to=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, value=15993885900000000 )
175 UniswapV2Pair.Approval( owner=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, spender=MasterChefV2, value=0 )
176 UniswapV2Pair.Approval( owner=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, spender=MasterChefV2, value=15993885900000000 )
177 MasterChefV2.LogUpdatePool( pid=1, lastRewardBlock=21542968, lpSupply=434980151999197293557, accSushiPerShare=12404338397582 )
178 UniswapV2Pair.Transfer( from=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, to=MasterChefV2, value=15993885900000000 )
179 MasterChefV2.Deposit( user=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, pid=1, amount=15993885900000000, to=[Sender] 0x7d8f07b6a09c501ad5e9ba990eaf7fb279258579 )
180 0x7bf8b4b9a74d5e55f022f3f311eda6142426e783.0xebedb8b3c678666e7f36970bc8f57abf6d8fa2e828c0da91ea5b75bf68ed101a( 0xebedb8b3c678666e7f36970bc8f57abf6d8fa2e828c0da91ea5b75bf68ed101a, 00000000000000000000000005767d9ef41dc40689678ffca0608878fb3de906, 0000000000000000000000000000000000000000000000000038d25abfa5cb00 )

Account State Difference:

  Address   Before After State Difference Code
0x05767d9E...8fb3dE906
(Titan Builder)
14.810887919193137294 Eth14.811139929081916438 Eth0.000252009888779144
0x7d8f07b6...279258579
0.011010024727401876 Eth
Nonce: 6
0.009078217755895724 Eth
Nonce: 7
0.001931806971506152
0x9e01aaC4...2Af77B362
0xEF0881eC...752B4Ec5d
(SushiSwap: MasterChef V2)

Execution Trace

TransparentUpgradeableProxy.016cba5f( )
  • 0xa43182027b6aca4f5470f4e23274698f8e015248.016cba5f( )
    • OKX: Dex Aggregator.0a5ea466( )
      • TokenApprove.claimTokens( _token=0x05767d9EF41dC40689678fFca0608878fb3dE906, _who=0x7d8f07b6A09c501AD5E9ba990EAF7Fb279258579, _dest=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, _amount=15993885900000000 )
        • UniswapV2Pair.transferFrom( from=0x7d8f07b6A09c501AD5E9ba990EAF7Fb279258579, to=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, value=15993885900000000 ) => ( True )
        • 0x7bf8b4b9a74d5e55f022f3f311eda6142426e783.365fa1b1( )
          • UniswapV2Pair.balanceOf( 0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783 ) => ( 15993885900000000 )
          • UniswapV2Pair.approve( spender=0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d, value=0 ) => ( True )
          • UniswapV2Pair.allowance( 0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, 0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d ) => ( 0 )
          • UniswapV2Pair.approve( spender=0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d, value=15993885900000000 ) => ( True )
          • TransparentUpgradeableProxy.STATICCALL( )
            • 0xa43182027b6aca4f5470f4e23274698f8e015248.DELEGATECALL( )
            • MasterChefV2.deposit( pid=1, amount=15993885900000000, to=0x7d8f07b6A09c501AD5E9ba990EAF7Fb279258579 )
              • UniswapV2Pair.balanceOf( 0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d ) => ( 434980151999197293557 )
              • MasterChef.STATICCALL( )
              • MasterChef.poolInfo( 250 ) => ( lpToken=0xa5e3142b7a5D59F778483A7E0FD3Fe4e263388e9, allocPoint=0, lastRewardBlock=19048834, accSushiPerShare=710954587987280795 )
              • ConvexRewarder.onSushiReward( pid=1, user=0x7d8f07b6A09c501AD5E9ba990EAF7Fb279258579, recipient=0x7d8f07b6A09c501AD5E9ba990EAF7Fb279258579, sushiAmount=0, newLpAmount=63975543687762397 )
              • UniswapV2Pair.transferFrom( from=0x7BF8b4B9a74d5e55F022F3f311EDa6142426e783, to=0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d, value=15993885900000000 ) => ( True )
                File 1 of 6: TransparentUpgradeableProxy
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
                import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
                import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
                // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
                contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
                    constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../Proxy.sol";
                import "./ERC1967Upgrade.sol";
                /**
                 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
                 * implementation address that can be changed. This address is stored in storage in the location specified by
                 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
                 * implementation behind the proxy.
                 */
                contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                    /**
                     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                     *
                     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                     * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                     */
                    constructor(address _logic, bytes memory _data) payable {
                        assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                        _upgradeToAndCall(_logic, _data, false);
                    }
                    /**
                     * @dev Returns the current implementation address.
                     */
                    function _implementation() internal view virtual override returns (address impl) {
                        return ERC1967Upgrade._getImplementation();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../ERC1967/ERC1967Proxy.sol";
                /**
                 * @dev This contract implements a proxy that is upgradeable by an admin.
                 *
                 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
                 * clashing], which can potentially be used in an attack, this contract uses the
                 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
                 * things that go hand in hand:
                 *
                 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
                 * that call matches one of the admin functions exposed by the proxy itself.
                 * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
                 * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
                 * "admin cannot fallback to proxy target".
                 *
                 * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
                 * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
                 * to sudden errors when trying to call a function from the proxy implementation.
                 *
                 * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
                 * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
                 */
                contract TransparentUpgradeableProxy is ERC1967Proxy {
                    /**
                     * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                     * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
                     */
                    constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
                        assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                        _changeAdmin(admin_);
                    }
                    /**
                     * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                     */
                    modifier ifAdmin() {
                        if (msg.sender == _getAdmin()) {
                            _;
                        } else {
                            _fallback();
                        }
                    }
                    /**
                     * @dev Returns the current admin.
                     *
                     * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
                     *
                     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                     */
                    function admin() external ifAdmin returns (address admin_) {
                        admin_ = _getAdmin();
                    }
                    /**
                     * @dev Returns the current implementation.
                     *
                     * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
                     *
                     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                     * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                     */
                    function implementation() external ifAdmin returns (address implementation_) {
                        implementation_ = _implementation();
                    }
                    /**
                     * @dev Changes the admin of the proxy.
                     *
                     * Emits an {AdminChanged} event.
                     *
                     * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
                     */
                    function changeAdmin(address newAdmin) external virtual ifAdmin {
                        _changeAdmin(newAdmin);
                    }
                    /**
                     * @dev Upgrade the implementation of the proxy.
                     *
                     * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                     */
                    function upgradeTo(address newImplementation) external ifAdmin {
                        _upgradeToAndCall(newImplementation, bytes(""), false);
                    }
                    /**
                     * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
                     * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
                     * proxied contract.
                     *
                     * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
                     */
                    function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                        _upgradeToAndCall(newImplementation, data, true);
                    }
                    /**
                     * @dev Returns the current admin.
                     */
                    function _admin() internal view virtual returns (address) {
                        return _getAdmin();
                    }
                    /**
                     * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                     */
                    function _beforeFallback() internal virtual override {
                        require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                        super._beforeFallback();
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "./TransparentUpgradeableProxy.sol";
                import "../../access/Ownable.sol";
                /**
                 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
                 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
                 */
                contract ProxyAdmin is Ownable {
                    /**
                     * @dev Returns the current implementation of `proxy`.
                     *
                     * Requirements:
                     *
                     * - This contract must be the admin of `proxy`.
                     */
                    function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                        // We need to manually run the static call since the getter cannot be flagged as view
                        // bytes4(keccak256("implementation()")) == 0x5c60da1b
                        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                        require(success);
                        return abi.decode(returndata, (address));
                    }
                    /**
                     * @dev Returns the current admin of `proxy`.
                     *
                     * Requirements:
                     *
                     * - This contract must be the admin of `proxy`.
                     */
                    function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                        // We need to manually run the static call since the getter cannot be flagged as view
                        // bytes4(keccak256("admin()")) == 0xf851a440
                        (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                        require(success);
                        return abi.decode(returndata, (address));
                    }
                    /**
                     * @dev Changes the admin of `proxy` to `newAdmin`.
                     *
                     * Requirements:
                     *
                     * - This contract must be the current admin of `proxy`.
                     */
                    function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                        proxy.changeAdmin(newAdmin);
                    }
                    /**
                     * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
                     *
                     * Requirements:
                     *
                     * - This contract must be the admin of `proxy`.
                     */
                    function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                        proxy.upgradeTo(implementation);
                    }
                    /**
                     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
                     * {TransparentUpgradeableProxy-upgradeToAndCall}.
                     *
                     * Requirements:
                     *
                     * - This contract must be the admin of `proxy`.
                     */
                    function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
                        proxy.upgradeToAndCall{value: msg.value}(implementation, data);
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
                 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
                 * be specified by overriding the virtual {_implementation} function.
                 *
                 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
                 * different contract through the {_delegate} function.
                 *
                 * The success and return data of the delegated call will be returned back to the caller of the proxy.
                 */
                abstract contract Proxy {
                    /**
                     * @dev Delegates the current call to `implementation`.
                     *
                     * This function does not return to its internall call site, it will return directly to the external caller.
                     */
                    function _delegate(address implementation) internal virtual {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            // Copy msg.data. We take full control of memory in this inline assembly
                            // block because it will not return to Solidity code. We overwrite the
                            // Solidity scratch pad at memory position 0.
                            calldatacopy(0, 0, calldatasize())
                            // Call the implementation.
                            // out and outsize are 0 because we don't know the size yet.
                            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                            // Copy the returned data.
                            returndatacopy(0, 0, returndatasize())
                            switch result
                            // delegatecall returns 0 on error.
                            case 0 { revert(0, returndatasize()) }
                            default { return(0, returndatasize()) }
                        }
                    }
                    /**
                     * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                     * and {_fallback} should delegate.
                     */
                    function _implementation() internal view virtual returns (address);
                    /**
                     * @dev Delegates the current call to the address returned by `_implementation()`.
                     *
                     * This function does not return to its internall call site, it will return directly to the external caller.
                     */
                    function _fallback() internal virtual {
                        _beforeFallback();
                        _delegate(_implementation());
                    }
                    /**
                     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                     * function in the contract matches the call data.
                     */
                    fallback () external payable virtual {
                        _fallback();
                    }
                    /**
                     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                     * is empty.
                     */
                    receive () external payable virtual {
                        _fallback();
                    }
                    /**
                     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                     * call, or as part of the Solidity `fallback` or `receive` functions.
                     *
                     * If overriden should call `super._beforeFallback()`.
                     */
                    function _beforeFallback() internal virtual {
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.2;
                import "../beacon/IBeacon.sol";
                import "../../utils/Address.sol";
                import "../../utils/StorageSlot.sol";
                /**
                 * @dev This abstract contract provides getters and event emitting update functions for
                 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
                 *
                 * _Available since v4.1._
                 *
                 * @custom:oz-upgrades-unsafe-allow delegatecall
                 */
                abstract contract ERC1967Upgrade {
                    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                    /**
                     * @dev Storage slot with the address of the current implementation.
                     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                     * validated in the constructor.
                     */
                    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                    /**
                     * @dev Emitted when the implementation is upgraded.
                     */
                    event Upgraded(address indexed implementation);
                    /**
                     * @dev Returns the current implementation address.
                     */
                    function _getImplementation() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                    }
                    /**
                     * @dev Stores a new address in the EIP1967 implementation slot.
                     */
                    function _setImplementation(address newImplementation) private {
                        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                    }
                    /**
                     * @dev Perform implementation upgrade
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeTo(address newImplementation) internal {
                        _setImplementation(newImplementation);
                        emit Upgraded(newImplementation);
                    }
                    /**
                     * @dev Perform implementation upgrade with additional setup call.
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                        _setImplementation(newImplementation);
                        emit Upgraded(newImplementation);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(newImplementation, data);
                        }
                    }
                    /**
                     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                     *
                     * Emits an {Upgraded} event.
                     */
                    function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
                        address oldImplementation = _getImplementation();
                        // Initial upgrade and setup call
                        _setImplementation(newImplementation);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(newImplementation, data);
                        }
                        // Perform rollback test if not already in progress
                        StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                        if (!rollbackTesting.value) {
                            // Trigger rollback using upgradeTo from the new implementation
                            rollbackTesting.value = true;
                            Address.functionDelegateCall(
                                newImplementation,
                                abi.encodeWithSignature(
                                    "upgradeTo(address)",
                                    oldImplementation
                                )
                            );
                            rollbackTesting.value = false;
                            // Check rollback was effective
                            require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                            // Finally reset to the new implementation and log the upgrade
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                        }
                    }
                    /**
                     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                     *
                     * Emits a {BeaconUpgraded} event.
                     */
                    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                        _setBeacon(newBeacon);
                        emit BeaconUpgraded(newBeacon);
                        if (data.length > 0 || forceCall) {
                            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                        }
                    }
                    /**
                     * @dev Storage slot with the admin of the contract.
                     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                     * validated in the constructor.
                     */
                    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                    /**
                     * @dev Emitted when the admin account has changed.
                     */
                    event AdminChanged(address previousAdmin, address newAdmin);
                    /**
                     * @dev Returns the current admin.
                     */
                    function _getAdmin() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                    }
                    /**
                     * @dev Stores a new address in the EIP1967 admin slot.
                     */
                    function _setAdmin(address newAdmin) private {
                        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                    }
                    /**
                     * @dev Changes the admin of the proxy.
                     *
                     * Emits an {AdminChanged} event.
                     */
                    function _changeAdmin(address newAdmin) internal {
                        emit AdminChanged(_getAdmin(), newAdmin);
                        _setAdmin(newAdmin);
                    }
                    /**
                     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                     */
                    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                    /**
                     * @dev Emitted when the beacon is upgraded.
                     */
                    event BeaconUpgraded(address indexed beacon);
                    /**
                     * @dev Returns the current beacon.
                     */
                    function _getBeacon() internal view returns (address) {
                        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                    }
                    /**
                     * @dev Stores a new beacon in the EIP1967 beacon slot.
                     */
                    function _setBeacon(address newBeacon) private {
                        require(
                            Address.isContract(newBeacon),
                            "ERC1967: new beacon is not a contract"
                        );
                        require(
                            Address.isContract(IBeacon(newBeacon).implementation()),
                            "ERC1967: beacon implementation is not a contract"
                        );
                        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev This is the interface that {BeaconProxy} expects of its beacon.
                 */
                interface IBeacon {
                    /**
                     * @dev Must return an address that can be used as a delegate call target.
                     *
                     * {BeaconProxy} will check that this address is a contract.
                     */
                    function implementation() external view returns (address);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^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);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                /**
                 * @dev Library for reading and writing primitive types to specific storage slots.
                 *
                 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                 * This library helps with reading and writing to such slots without the need for inline assembly.
                 *
                 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                 *
                 * Example usage to set ERC1967 implementation slot:
                 * ```
                 * contract ERC1967 {
                 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                 *
                 *     function _getImplementation() internal view returns (address) {
                 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                 *     }
                 *
                 *     function _setImplementation(address newImplementation) internal {
                 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                 *     }
                 * }
                 * ```
                 *
                 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
                 */
                library StorageSlot {
                    struct AddressSlot {
                        address value;
                    }
                    struct BooleanSlot {
                        bool value;
                    }
                    struct Bytes32Slot {
                        bytes32 value;
                    }
                    struct Uint256Slot {
                        uint256 value;
                    }
                    /**
                     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                     */
                    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                     */
                    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                     */
                    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                    /**
                     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                     */
                    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                        assembly {
                            r.slot := slot
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                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 () {
                        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;
                    }
                }
                // SPDX-License-Identifier: MIT
                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) {
                        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                        return msg.data;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                import "../ERC1967/ERC1967Upgrade.sol";
                /**
                 * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
                 * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
                 * continuation of the upgradability.
                 *
                 * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
                 *
                 * _Available since v4.1._
                 */
                abstract contract UUPSUpgradeable is ERC1967Upgrade {
                    function upgradeTo(address newImplementation) external virtual {
                        _authorizeUpgrade(newImplementation);
                        _upgradeToAndCallSecure(newImplementation, bytes(""), false);
                    }
                    function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
                        _authorizeUpgrade(newImplementation);
                        _upgradeToAndCallSecure(newImplementation, data, true);
                    }
                    function _authorizeUpgrade(address newImplementation) internal virtual;
                }
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.2;
                import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
                abstract contract Proxiable is UUPSUpgradeable {
                    function _authorizeUpgrade(address newImplementation) internal override {
                        _beforeUpgrade(newImplementation);
                    }
                    function _beforeUpgrade(address newImplementation) internal virtual;
                }
                contract ChildOfProxiable is Proxiable {
                    function _beforeUpgrade(address newImplementation) internal virtual override {}
                }
                

                File 2 of 6: 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 3 of 6: MasterChefV2
                // SPDX-License-Identifier: MIT
                
                // Special Thanks to @BoringCrypto for his ideas and patience
                
                pragma solidity 0.6.12;
                pragma experimental ABIEncoderV2;
                
                // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SignedSafeMath.sol
                library SignedSafeMath {
                    int256 constant private _INT256_MIN = -2**255;
                
                    /**
                     * @dev Returns the multiplication of two signed integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `*` operator.
                     *
                     * Requirements:
                     *
                     * - Multiplication cannot overflow.
                     */
                    function mul(int256 a, int256 b) internal pure returns (int256) {
                        // 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;
                        }
                
                        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
                
                        int256 c = a * b;
                        require(c / a == b, "SignedSafeMath: multiplication overflow");
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
                        require(b != 0, "SignedSafeMath: division by zero");
                        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
                
                        int256 c = a / b;
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the subtraction of two signed integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(int256 a, int256 b) internal pure returns (int256) {
                        int256 c = a - b;
                        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the addition of two signed integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `+` operator.
                     *
                     * Requirements:
                     *
                     * - Addition cannot overflow.
                     */
                    function add(int256 a, int256 b) internal pure returns (int256) {
                        int256 c = a + b;
                        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
                
                        return c;
                    }
                
                    function toUInt256(int256 a) internal pure returns (uint256) {
                        require(a >= 0, "Integer < 0");
                        return uint256(a);
                    }
                }
                
                /// @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 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);
                    }
                }
                
                /// @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");
                    }
                }
                
                
                contract BoringOwnableData {
                    address public owner;
                    address public pendingOwner;
                }
                
                contract BoringOwnable is BoringOwnableData {
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                
                    /// @notice `owner` defaults to msg.sender on construction.
                    constructor() public {
                        owner = msg.sender;
                        emit OwnershipTransferred(address(0), msg.sender);
                    }
                
                    /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
                    /// Can only be invoked by the current `owner`.
                    /// @param newOwner Address of the new owner.
                    /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
                    /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
                    function transferOwnership(
                        address newOwner,
                        bool direct,
                        bool renounce
                    ) public onlyOwner {
                        if (direct) {
                            // Checks
                            require(newOwner != address(0) || renounce, "Ownable: zero address");
                
                            // Effects
                            emit OwnershipTransferred(owner, newOwner);
                            owner = newOwner;
                            pendingOwner = address(0);
                        } else {
                            // Effects
                            pendingOwner = newOwner;
                        }
                    }
                
                    /// @notice Needs to be called by `pendingOwner` to claim ownership.
                    function claimOwnership() public {
                        address _pendingOwner = pendingOwner;
                
                        // Checks
                        require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
                
                        // Effects
                        emit OwnershipTransferred(owner, _pendingOwner);
                        owner = _pendingOwner;
                        pendingOwner = address(0);
                    }
                
                    /// @notice Only allows the `owner` to execute the function.
                    modifier onlyOwner() {
                        require(msg.sender == owner, "Ownable: caller is not the owner");
                        _;
                    }
                }
                
                interface IERC20 {
                    function totalSupply() external view returns (uint256);
                
                    function balanceOf(address account) external view returns (uint256);
                
                    function allowance(address owner, address spender) external view returns (uint256);
                
                    function approve(address spender, uint256 amount) external returns (bool);
                
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                
                    /// @notice EIP 2612
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external;
                }
                
                
                library BoringERC20 {
                    bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
                    bytes4 private constant SIG_NAME = 0x06fdde03; // name()
                    bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
                    bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
                    bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
                
                    function returnDataToString(bytes memory data) internal pure returns (string memory) {
                        if (data.length >= 64) {
                            return abi.decode(data, (string));
                        } else if (data.length == 32) {
                            uint8 i = 0;
                            while(i < 32 && data[i] != 0) {
                                i++;
                            }
                            bytes memory bytesArray = new bytes(i);
                            for (i = 0; i < 32 && data[i] != 0; i++) {
                                bytesArray[i] = data[i];
                            }
                            return string(bytesArray);
                        } else {
                            return "???";
                        }
                    }
                
                    /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
                    /// @param token The address of the ERC-20 token contract.
                    /// @return (string) Token symbol.
                    function safeSymbol(IERC20 token) internal view returns (string memory) {
                        (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
                        return success ? returnDataToString(data) : "???";
                    }
                
                    /// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
                    /// @param token The address of the ERC-20 token contract.
                    /// @return (string) Token name.
                    function safeName(IERC20 token) internal view returns (string memory) {
                        (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
                        return success ? returnDataToString(data) : "???";
                    }
                
                    /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
                    /// @param token The address of the ERC-20 token contract.
                    /// @return (uint8) Token decimals.
                    function safeDecimals(IERC20 token) internal view returns (uint8) {
                        (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
                        return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
                    }
                
                    /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
                    /// Reverts on a failed transfer.
                    /// @param token The address of the ERC-20 token.
                    /// @param to Transfer tokens to.
                    /// @param amount The token amount.
                    function safeTransfer(
                        IERC20 token,
                        address to,
                        uint256 amount
                    ) internal {
                        (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
                    }
                
                    /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
                    /// Reverts on a failed transfer.
                    /// @param token The address of the ERC-20 token.
                    /// @param from Transfer tokens from.
                    /// @param to Transfer tokens to.
                    /// @param amount The token amount.
                    function safeTransferFrom(
                        IERC20 token,
                        address from,
                        address to,
                        uint256 amount
                    ) internal {
                        (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
                    }
                }
                
                contract BaseBoringBatchable {
                    /// @dev Helper function to extract a useful revert message from a failed call.
                    /// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
                    function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
                        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
                        if (_returnData.length < 68) return "Transaction reverted silently";
                
                        assembly {
                            // Slice the sighash.
                            _returnData := add(_returnData, 0x04)
                        }
                        return abi.decode(_returnData, (string)); // All that remains is the revert string
                    }
                
                    /// @notice Allows batched call to self (this contract).
                    /// @param calls An array of inputs for each call.
                    /// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
                    /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
                    /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
                    // F1: External is ok here because this is the batch function, adding it to a batch makes no sense
                    // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
                    // C3: The length of the loop is fully under user control, so can't be exploited
                    // C7: Delegatecall is only used on the same contract, so it's safe
                    function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
                        successes = new bool[](calls.length);
                        results = new bytes[](calls.length);
                        for (uint256 i = 0; i < calls.length; i++) {
                            (bool success, bytes memory result) = address(this).delegatecall(calls[i]);
                            require(success || !revertOnFail, _getRevertMsg(result));
                            successes[i] = success;
                            results[i] = result;
                        }
                    }
                }
                
                contract BoringBatchable is BaseBoringBatchable {
                    /// @notice Call wrapper that performs `ERC20.permit` on `token`.
                    /// Lookup `IERC20.permit`.
                    // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
                    //     if part of a batch this could be used to grief once as the second call would not need the permit
                    function permitToken(
                        IERC20 token,
                        address from,
                        address to,
                        uint256 amount,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public {
                        token.permit(from, to, amount, deadline, v, r, s);
                    }
                }
                
                interface IRewarder {
                    using BoringERC20 for IERC20;
                    function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external;
                    function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory);
                }
                
                interface IMigratorChef {
                    // Take the current LP token address and return the new LP token address.
                    // Migrator should have full access to the caller's LP token.
                    function migrate(IERC20 token) external returns (IERC20);
                }
                
                interface IMasterChef {
                    using BoringERC20 for IERC20;
                    struct UserInfo {
                        uint256 amount;     // How many LP tokens the user has provided.
                        uint256 rewardDebt; // Reward debt. See explanation below.
                    }
                
                    struct PoolInfo {
                        IERC20 lpToken;           // Address of LP token contract.
                        uint256 allocPoint;       // How many allocation points assigned to this pool. SUSHI to distribute per block.
                        uint256 lastRewardBlock;  // Last block number that SUSHI distribution occurs.
                        uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below.
                    }
                
                    function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory);
                    function totalAllocPoint() external view returns (uint256);
                    function deposit(uint256 _pid, uint256 _amount) external;
                }
                
                /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
                /// It is the only address with minting rights for SUSHI.
                /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
                /// that is deposited into the MasterChef V1 (MCV1) contract.
                /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives.
                contract MasterChefV2 is BoringOwnable, BoringBatchable {
                    using BoringMath for uint256;
                    using BoringMath128 for uint128;
                    using BoringERC20 for IERC20;
                    using SignedSafeMath for int256;
                
                    /// @notice Info of each MCV2 user.
                    /// `amount` LP token amount the user has provided.
                    /// `rewardDebt` The amount of SUSHI entitled to the user.
                    struct UserInfo {
                        uint256 amount;
                        int256 rewardDebt;
                    }
                
                    /// @notice Info of each MCV2 pool.
                    /// `allocPoint` The amount of allocation points assigned to the pool.
                    /// Also known as the amount of SUSHI to distribute per block.
                    struct PoolInfo {
                        uint128 accSushiPerShare;
                        uint64 lastRewardBlock;
                        uint64 allocPoint;
                    }
                
                    /// @notice Address of MCV1 contract.
                    IMasterChef public immutable MASTER_CHEF;
                    /// @notice Address of SUSHI contract.
                    IERC20 public immutable SUSHI;
                    /// @notice The index of MCV2 master pool in MCV1.
                    uint256 public immutable MASTER_PID;
                    // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
                    IMigratorChef public migrator;
                
                    /// @notice Info of each MCV2 pool.
                    PoolInfo[] public poolInfo;
                    /// @notice Address of the LP token for each MCV2 pool.
                    IERC20[] public lpToken;
                    /// @notice Address of each `IRewarder` contract in MCV2.
                    IRewarder[] public rewarder;
                
                    /// @notice Info of each user that stakes LP tokens.
                    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
                    /// @dev Total allocation points. Must be the sum of all allocation points in all pools.
                    uint256 public totalAllocPoint;
                
                    uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
                    uint256 private constant ACC_SUSHI_PRECISION = 1e12;
                
                    event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
                    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
                    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
                    event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
                    event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
                    event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
                    event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
                    event LogInit();
                
                    /// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
                    /// @param _sushi The SUSHI token contract address.
                    /// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
                    constructor(IMasterChef _MASTER_CHEF, IERC20 _sushi, uint256 _MASTER_PID) public {
                        MASTER_CHEF = _MASTER_CHEF;
                        SUSHI = _sushi;
                        MASTER_PID = _MASTER_PID;
                    }
                
                    /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
                    /// Any balance of transaction sender in `dummyToken` is transferred.
                    /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
                    /// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
                    function init(IERC20 dummyToken) external {
                        uint256 balance = dummyToken.balanceOf(msg.sender);
                        require(balance != 0, "MasterChefV2: Balance must exceed 0");
                        dummyToken.safeTransferFrom(msg.sender, address(this), balance);
                        dummyToken.approve(address(MASTER_CHEF), balance);
                        MASTER_CHEF.deposit(MASTER_PID, balance);
                        emit LogInit();
                    }
                
                    /// @notice Returns the number of MCV2 pools.
                    function poolLength() public view returns (uint256 pools) {
                        pools = poolInfo.length;
                    }
                
                    /// @notice Add a new LP to the pool. Can only be called by the owner.
                    /// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
                    /// @param allocPoint AP of the new pool.
                    /// @param _lpToken Address of the LP ERC-20 token.
                    /// @param _rewarder Address of the rewarder delegate.
                    function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner {
                        uint256 lastRewardBlock = block.number;
                        totalAllocPoint = totalAllocPoint.add(allocPoint);
                        lpToken.push(_lpToken);
                        rewarder.push(_rewarder);
                
                        poolInfo.push(PoolInfo({
                            allocPoint: allocPoint.to64(),
                            lastRewardBlock: lastRewardBlock.to64(),
                            accSushiPerShare: 0
                        }));
                        emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
                    }
                
                    /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
                    /// @param _pid The index of the pool. See `poolInfo`.
                    /// @param _allocPoint New AP of the pool.
                    /// @param _rewarder Address of the rewarder delegate.
                    /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
                    function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner {
                        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
                        poolInfo[_pid].allocPoint = _allocPoint.to64();
                        if (overwrite) { rewarder[_pid] = _rewarder; }
                        emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
                    }
                
                    /// @notice Set the `migrator` contract. Can only be called by the owner.
                    /// @param _migrator The contract address to set.
                    function setMigrator(IMigratorChef _migrator) public onlyOwner {
                        migrator = _migrator;
                    }
                
                    /// @notice Migrate LP token to another LP contract through the `migrator` contract.
                    /// @param _pid The index of the pool. See `poolInfo`.
                    function migrate(uint256 _pid) public {
                        require(address(migrator) != address(0), "MasterChefV2: no migrator set");
                        IERC20 _lpToken = lpToken[_pid];
                        uint256 bal = _lpToken.balanceOf(address(this));
                        _lpToken.approve(address(migrator), bal);
                        IERC20 newLpToken = migrator.migrate(_lpToken);
                        require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
                        lpToken[_pid] = newLpToken;
                    }
                
                    /// @notice View function to see pending SUSHI on frontend.
                    /// @param _pid The index of the pool. See `poolInfo`.
                    /// @param _user Address of user.
                    /// @return pending SUSHI reward for a given user.
                    function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
                        PoolInfo memory pool = poolInfo[_pid];
                        UserInfo storage user = userInfo[_pid][_user];
                        uint256 accSushiPerShare = pool.accSushiPerShare;
                        uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
                        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
                            uint256 blocks = block.number.sub(pool.lastRewardBlock);
                            uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
                            accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
                        }
                        pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
                    }
                
                    /// @notice Update reward variables for all pools. Be careful of gas spending!
                    /// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
                    function massUpdatePools(uint256[] calldata pids) external {
                        uint256 len = pids.length;
                        for (uint256 i = 0; i < len; ++i) {
                            updatePool(pids[i]);
                        }
                    }
                
                    /// @notice Calculates and returns the `amount` of SUSHI per block.
                    function sushiPerBlock() public view returns (uint256 amount) {
                        amount = uint256(MASTERCHEF_SUSHI_PER_BLOCK)
                            .mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint();
                    }
                
                    /// @notice Update reward variables of the given pool.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @return pool Returns the pool that was updated.
                    function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
                        pool = poolInfo[pid];
                        if (block.number > pool.lastRewardBlock) {
                            uint256 lpSupply = lpToken[pid].balanceOf(address(this));
                            if (lpSupply > 0) {
                                uint256 blocks = block.number.sub(pool.lastRewardBlock);
                                uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
                                pool.accSushiPerShare = pool.accSushiPerShare.add((sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128());
                            }
                            pool.lastRewardBlock = block.number.to64();
                            poolInfo[pid] = pool;
                            emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
                        }
                    }
                
                    /// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @param amount LP token amount to deposit.
                    /// @param to The receiver of `amount` deposit benefit.
                    function deposit(uint256 pid, uint256 amount, address to) public {
                        PoolInfo memory pool = updatePool(pid);
                        UserInfo storage user = userInfo[pid][to];
                
                        // Effects
                        user.amount = user.amount.add(amount);
                        user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
                
                        // Interactions
                        IRewarder _rewarder = rewarder[pid];
                        if (address(_rewarder) != address(0)) {
                            _rewarder.onSushiReward(pid, to, to, 0, user.amount);
                        }
                
                        lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
                
                        emit Deposit(msg.sender, pid, amount, to);
                    }
                
                    /// @notice Withdraw LP tokens from MCV2.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @param amount LP token amount to withdraw.
                    /// @param to Receiver of the LP tokens.
                    function withdraw(uint256 pid, uint256 amount, address to) public {
                        PoolInfo memory pool = updatePool(pid);
                        UserInfo storage user = userInfo[pid][msg.sender];
                
                        // Effects
                        user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
                        user.amount = user.amount.sub(amount);
                
                        // Interactions
                        IRewarder _rewarder = rewarder[pid];
                        if (address(_rewarder) != address(0)) {
                            _rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
                        }
                        
                        lpToken[pid].safeTransfer(to, amount);
                
                        emit Withdraw(msg.sender, pid, amount, to);
                    }
                
                    /// @notice Harvest proceeds for transaction sender to `to`.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @param to Receiver of SUSHI rewards.
                    function harvest(uint256 pid, address to) public {
                        PoolInfo memory pool = updatePool(pid);
                        UserInfo storage user = userInfo[pid][msg.sender];
                        int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
                        uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
                
                        // Effects
                        user.rewardDebt = accumulatedSushi;
                
                        // Interactions
                        if (_pendingSushi != 0) {
                            SUSHI.safeTransfer(to, _pendingSushi);
                        }
                        
                        IRewarder _rewarder = rewarder[pid];
                        if (address(_rewarder) != address(0)) {
                            _rewarder.onSushiReward( pid, msg.sender, to, _pendingSushi, user.amount);
                        }
                
                        emit Harvest(msg.sender, pid, _pendingSushi);
                    }
                    
                    /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @param amount LP token amount to withdraw.
                    /// @param to Receiver of the LP tokens and SUSHI rewards.
                    function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public {
                        PoolInfo memory pool = updatePool(pid);
                        UserInfo storage user = userInfo[pid][msg.sender];
                        int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
                        uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
                
                        // Effects
                        user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
                        user.amount = user.amount.sub(amount);
                        
                        // Interactions
                        SUSHI.safeTransfer(to, _pendingSushi);
                
                        IRewarder _rewarder = rewarder[pid];
                        if (address(_rewarder) != address(0)) {
                            _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
                        }
                
                        lpToken[pid].safeTransfer(to, amount);
                
                        emit Withdraw(msg.sender, pid, amount, to);
                        emit Harvest(msg.sender, pid, _pendingSushi);
                    }
                
                    /// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
                    function harvestFromMasterChef() public {
                        MASTER_CHEF.deposit(MASTER_PID, 0);
                    }
                
                    /// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
                    /// @param pid The index of the pool. See `poolInfo`.
                    /// @param to Receiver of the LP tokens.
                    function emergencyWithdraw(uint256 pid, address to) public {
                        UserInfo storage user = userInfo[pid][msg.sender];
                        uint256 amount = user.amount;
                        user.amount = 0;
                        user.rewardDebt = 0;
                
                        IRewarder _rewarder = rewarder[pid];
                        if (address(_rewarder) != address(0)) {
                            _rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
                        }
                
                        // Note: transfer can fail or succeed if `amount` is zero.
                        lpToken[pid].safeTransfer(to, amount);
                        emit EmergencyWithdraw(msg.sender, pid, amount, to);
                    }
                }

                File 4 of 6: TokenApprove
                /**
                 *Submitted for verification at BscScan.com on 2023-06-26
                */
                
                // SPDX-License-Identifier: MIT
                pragma solidity ^0.8.0;
                
                // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
                
                // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                
                // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
                
                // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
                
                /**
                 * @dev Collection of functions related to the address type
                 */
                library AddressUpgradeable {
                    /**
                     * @dev Returns true if `account` is a contract.
                     *
                     * [IMPORTANT]
                     * ====
                     * It is unsafe to assume that an address for which this function returns
                     * false is an externally-owned account (EOA) and not a contract.
                     *
                     * Among others, `isContract` will return false for the following
                     * types of addresses:
                     *
                     *  - an externally-owned account
                     *  - a contract in construction
                     *  - an address where a contract will be created
                     *  - an address where a contract lived, but was destroyed
                     * ====
                     */
                    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;
                        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");
                
                        (bool success, ) = recipient.call{value: amount}("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                
                    /**
                     * @dev Performs a Solidity function call using a low level `call`. A
                     * plain `call` is an unsafe replacement for a function call: use this
                     * function instead.
                     *
                     * If `target` reverts with a revert reason, it is bubbled up by this
                     * function (like regular Solidity function calls).
                     *
                     * Returns the raw returned data. To convert to the expected return value,
                     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                     *
                     * Requirements:
                     *
                     * - `target` must be a contract.
                     * - calling `target` with `data` must not revert.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionCall(target, data, "Address: low-level call failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                     * `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, errorMessage);
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but also transferring `value` wei to `target`.
                     *
                     * Requirements:
                     *
                     * - the calling contract must have an ETH balance of at least `value`.
                     * - the called Solidity function must be `payable`.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(
                        address target,
                        bytes memory data,
                        uint256 value
                    ) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                     * with `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(
                        address target,
                        bytes memory data,
                        uint256 value,
                        string memory errorMessage
                    ) internal returns (bytes memory) {
                        require(address(this).balance >= value, "Address: insufficient balance for call");
                        require(isContract(target), "Address: call to non-contract");
                
                        (bool success, bytes memory returndata) = target.call{value: value}(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                        return functionStaticCall(target, data, "Address: low-level static call failed");
                    }
                
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(
                        address target,
                        bytes memory data,
                        string memory errorMessage
                    ) internal view returns (bytes memory) {
                        require(isContract(target), "Address: static call to non-contract");
                
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return verifyCallResult(success, returndata, errorMessage);
                    }
                
                    /**
                     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                     * revert reason using the provided one.
                     *
                     * _Available since v4.3._
                     */
                    function verifyCallResult(
                        bool success,
                        bytes memory returndata,
                        string memory errorMessage
                    ) internal pure returns (bytes memory) {
                        if (success) {
                            return returndata;
                        } else {
                            // Look for revert reason and bubble it up if present
                            if (returndata.length > 0) {
                                // The easiest way to bubble the revert reason is using memory via assembly
                
                                assembly {
                                    let returndata_size := mload(returndata)
                                    revert(add(32, returndata), returndata_size)
                                }
                            } else {
                                revert(errorMessage);
                            }
                        }
                    }
                }
                
                /**
                 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
                 * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
                 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
                 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
                 *
                 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
                 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
                 *
                 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
                 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
                 *
                 * [CAUTION]
                 * ====
                 * Avoid leaving a contract uninitialized.
                 *
                 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
                 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
                 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
                 *
                 * [.hljs-theme-light.nopadding]
                 * ```
                 * /// @custom:oz-upgrades-unsafe-allow constructor
                 * constructor() initializer {}
                 * ```
                 * ====
                 */
                abstract contract Initializable {
                    /**
                     * @dev Indicates that the contract has been initialized.
                     */
                    bool private _initialized;
                
                    /**
                     * @dev Indicates that the contract is in the process of being initialized.
                     */
                    bool private _initializing;
                
                    /**
                     * @dev Modifier to protect an initializer function from being invoked twice.
                     */
                    modifier initializer() {
                        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                        // contract may have been reentered.
                        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
                
                        bool isTopLevelCall = !_initializing;
                        if (isTopLevelCall) {
                            _initializing = true;
                            _initialized = true;
                        }
                
                        _;
                
                        if (isTopLevelCall) {
                            _initializing = false;
                        }
                    }
                
                    /**
                     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                     * {initializer} modifier, directly or indirectly.
                     */
                    modifier onlyInitializing() {
                        require(_initializing, "Initializable: contract is not initializing");
                        _;
                    }
                
                    function _isConstructor() private view returns (bool) {
                        return !AddressUpgradeable.isContract(address(this));
                    }
                }
                
                /**
                 * @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 ContextUpgradeable is Initializable {
                    function __Context_init() internal onlyInitializing {
                        __Context_init_unchained();
                    }
                
                    function __Context_init_unchained() internal onlyInitializing {
                    }
                    function _msgSender() internal view virtual returns (address) {
                        return msg.sender;
                    }
                
                    function _msgData() internal view virtual returns (bytes calldata) {
                        return msg.data;
                    }
                    uint256[50] private __gap;
                }
                
                /**
                 * @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 OwnableUpgradeable is Initializable, ContextUpgradeable {
                    address private _owner;
                
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                
                    /**
                     * @dev Initializes the contract setting the deployer as the initial owner.
                     */
                    function __Ownable_init() internal onlyInitializing {
                        __Context_init_unchained();
                        __Ownable_init_unchained();
                    }
                
                    function __Ownable_init_unchained() internal onlyInitializing {
                        _transferOwnership(_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 {
                        _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);
                    }
                    uint256[49] private __gap;
                }
                
                interface IERC20 {
                    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);
                }
                
                library SafeMath {
                    uint256 constant WAD = 10 ** 18;
                    uint256 constant RAY = 10 ** 27;
                
                    function wad() public pure returns (uint256) {
                        return WAD;
                    }
                
                    function ray() public pure returns (uint256) {
                        return RAY;
                    }
                
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                
                        return c;
                    }
                
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        return sub(a, b, "SafeMath: subtraction overflow");
                    }
                
                    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b <= a, errorMessage);
                        uint256 c = a - b;
                
                        return c;
                    }
                
                    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;
                    }
                
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        return div(a, b, "SafeMath: division by zero");
                    }
                
                    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        // Solidity only automatically asserts when dividing by 0
                        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;
                    }
                
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        return mod(a, b, "SafeMath: modulo by zero");
                    }
                
                    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b != 0, errorMessage);
                        return a % b;
                    }
                
                    function min(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a <= b ? a : b;
                    }
                
                    function max(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a >= b ? a : b;
                    }
                
                    function sqrt(uint256 a) internal pure returns (uint256 b) {
                        if (a > 3) {
                            b = a;
                            uint256 x = a / 2 + 1;
                            while (x < b) {
                                b = x;
                                x = (a / x + x) / 2;
                            }
                        } else if (a != 0) {
                            b = 1;
                        }
                    }
                
                    function wmul(uint256 a, uint256 b) internal pure returns (uint256) {
                        return mul(a, b) / WAD;
                    }
                
                    function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) {
                        return add(mul(a, b), WAD / 2) / WAD;
                    }
                
                    function rmul(uint256 a, uint256 b) internal pure returns (uint256) {
                        return mul(a, b) / RAY;
                    }
                
                    function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) {
                        return add(mul(a, b), RAY / 2) / RAY;
                    }
                
                    function wdiv(uint256 a, uint256 b) internal pure returns (uint256) {
                        return div(mul(a, WAD), b);
                    }
                
                    function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) {
                        return add(mul(a, WAD), b / 2) / b;
                    }
                
                    function rdiv(uint256 a, uint256 b) internal pure returns (uint256) {
                        return div(mul(a, RAY), b);
                    }
                
                    function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) {
                        return add(mul(a, RAY), b / 2) / b;
                    }
                
                    function wpow(uint256 x, uint256 n) internal pure returns (uint256) {
                        uint256 result = WAD;
                        while (n > 0) {
                            if (n % 2 != 0) {
                                result = wmul(result, x);
                            }
                            x = wmul(x, x);
                            n /= 2;
                        }
                        return result;
                    }
                
                    function rpow(uint256 x, uint256 n) internal pure returns (uint256) {
                        uint256 result = RAY;
                        while (n > 0) {
                            if (n % 2 != 0) {
                                result = rmul(result, x);
                            }
                            x = rmul(x, x);
                            n /= 2;
                        }
                        return result;
                    }
                
                    function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 quotient = div(a, b);
                        uint256 remainder = a - quotient * b;
                        if (remainder > 0) {
                            return quotient + 1;
                        } else {
                            return quotient;
                        }
                    }
                }
                
                /**
                 * @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) {
                        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                        // for accounts without code, i.e. `keccak256('')`
                        bytes32 codehash;
                        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                        // solhint-disable-next-line no-inline-assembly
                        assembly { codehash := extcodehash(account) }
                        return (codehash != accountHash && codehash != 0x0);
                    }
                
                    /**
                     * @dev Converts an `address` into `address payable`. Note that this is
                     * simply a type cast: the actual underlying value is not changed.
                     *
                     * _Available since v2.4.0._
                     */
                    function toPayable(address account) internal pure returns (address payable) {
                        return payable(account);
                    }
                
                    /**
                     * @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].
                     *
                     * _Available since v2.4.0._
                     */
                    function sendValue(address recipient, uint256 amount) internal {
                        require(address(this).balance >= amount, "Address: insufficient balance");
                
                        // solhint-disable-next-line avoid-call-value
                        (bool success, ) = recipient.call{ value: amount }("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                }
                
                /**
                 * @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 ERC20;` 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));
                    }
                
                    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.
                
                        // A Solidity high level call has three parts:
                        //  1. The target address is checked to verify it contains contract code
                        //  2. The call itself is made, and success asserted
                        //  3. The return value is decoded, which in turn checks the size of the returned data.
                        // solhint-disable-next-line max-line-length
                        require(address(token).isContract(), "SafeERC20: call to non-contract");
                
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = address(token).call(data);
                        require(success, "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");
                        }
                    }
                }
                
                /// @title Handle authorizations in dex platform
                /// @notice Explain to an end user what this does
                /// @dev Explain to a developer any extra details
                contract TokenApprove is OwnableUpgradeable {
                  using SafeERC20 for IERC20;
                
                  address public tokenApproveProxy;
                
                  function initialize(address _tokenApproveProxy) public initializer {
                    __Ownable_init();
                    tokenApproveProxy = _tokenApproveProxy;
                  }
                
                  //-------------------------------
                  //------- Events ----------------
                  //-------------------------------
                
                  event ProxyUpdate(address indexed oldProxy, address indexed newProxy);
                
                  //-------------------------------
                  //------- Modifier --------------
                  //-------------------------------
                
                  //--------------------------------
                  //------- Internal Functions -----
                  //--------------------------------
                
                  //---------------------------------
                  //------- Admin functions ---------
                  //---------------------------------
                
                  function setApproveProxy(address _newTokenApproveProxy) external onlyOwner {
                    tokenApproveProxy = _newTokenApproveProxy;
                    emit ProxyUpdate(tokenApproveProxy, _newTokenApproveProxy);
                  }
                
                  //---------------------------------
                  //-------  Users Functions --------
                  //---------------------------------
                
                  function claimTokens(
                    address _token,
                    address _who,
                    address _dest,
                    uint256 _amount
                  ) external {
                    require(msg.sender == tokenApproveProxy, "TokenApprove: Access restricted");
                    if (_amount > 0) {
                      IERC20(_token).safeTransferFrom(_who, _dest, _amount);
                    }
                  }
                }

                File 5 of 6: MasterChef
                // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                
                
                
                pragma solidity ^0.6.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;
                
                /**
                 * @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/contracts/utils/Address.sol
                
                
                
                pragma solidity ^0.6.2;
                
                /**
                 * @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) {
                        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                        // for accounts without code, i.e. `keccak256('')`
                        bytes32 codehash;
                        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                        // solhint-disable-next-line no-inline-assembly
                        assembly { codehash := extcodehash(account) }
                        return (codehash != accountHash && codehash != 0x0);
                    }
                
                    /**
                     * @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");
                        return _functionCallWithValue(target, data, value, errorMessage);
                    }
                
                    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
                        require(isContract(target), "Address: call to non-contract");
                
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
                        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;
                
                
                
                
                /**
                 * @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/utils/EnumerableSet.sol
                
                
                
                pragma solidity ^0.6.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.0.0, only sets of type `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];
                    }
                
                    // 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/contracts/GSN/Context.sol
                
                
                
                pragma solidity ^0.6.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;
                
                /**
                 * @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.
                 */
                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: @openzeppelin/contracts/token/ERC20/ERC20.sol
                
                
                
                pragma solidity ^0.6.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;
                    using Address for address;
                
                    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 returns (string memory) {
                        return _name;
                    }
                
                    /**
                     * @dev Returns the symbol of the token, usually a shorter version of the
                     * name.
                     */
                    function symbol() public view 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 returns (uint8) {
                        return _decimals;
                    }
                
                    /**
                     * @dev See {IERC20-totalSupply}.
                     */
                    function totalSupply() public view override returns (uint256) {
                        return _totalSupply;
                    }
                
                    /**
                     * @dev See {IERC20-balanceOf}.
                     */
                    function balanceOf(address account) public view 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 is 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 {
                        _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/SushiToken.sol
                
                pragma solidity 0.6.12;
                
                
                
                
                // SushiToken with Governance.
                contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable {
                    /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
                    function mint(address _to, uint256 _amount) public onlyOwner {
                        _mint(_to, _amount);
                        _moveDelegates(address(0), _delegates[_to], _amount);
                    }
                
                    // Copied and modified from YAM code:
                    // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
                    // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
                    // Which is copied and modified from COMPOUND:
                    // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
                
                    /// @notice A record of each accounts delegate
                    mapping (address => address) internal _delegates;
                
                    /// @notice A checkpoint for marking number of votes from a given block
                    struct Checkpoint {
                        uint32 fromBlock;
                        uint256 votes;
                    }
                
                    /// @notice A record of votes checkpoints for each account, by index
                    mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
                
                    /// @notice The number of checkpoints for each account
                    mapping (address => uint32) public numCheckpoints;
                
                    /// @notice The EIP-712 typehash for the contract's domain
                    bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
                
                    /// @notice The EIP-712 typehash for the delegation struct used by the contract
                    bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
                
                    /// @notice A record of states for signing / validating signatures
                    mapping (address => uint) public nonces;
                
                      /// @notice An event thats emitted when an account changes its delegate
                    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
                
                    /// @notice An event thats emitted when a delegate account's vote balance changes
                    event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
                
                    /**
                     * @notice Delegate votes from `msg.sender` to `delegatee`
                     * @param delegator The address to get delegatee for
                     */
                    function delegates(address delegator)
                        external
                        view
                        returns (address)
                    {
                        return _delegates[delegator];
                    }
                
                   /**
                    * @notice Delegate votes from `msg.sender` to `delegatee`
                    * @param delegatee The address to delegate votes to
                    */
                    function delegate(address delegatee) external {
                        return _delegate(msg.sender, delegatee);
                    }
                
                    /**
                     * @notice Delegates votes from signatory to `delegatee`
                     * @param delegatee The address to delegate votes to
                     * @param nonce The contract state required to match the signature
                     * @param expiry The time at which to expire the signature
                     * @param v The recovery byte of the signature
                     * @param r Half of the ECDSA signature pair
                     * @param s Half of the ECDSA signature pair
                     */
                    function delegateBySig(
                        address delegatee,
                        uint nonce,
                        uint expiry,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    )
                        external
                    {
                        bytes32 domainSeparator = keccak256(
                            abi.encode(
                                DOMAIN_TYPEHASH,
                                keccak256(bytes(name())),
                                getChainId(),
                                address(this)
                            )
                        );
                
                        bytes32 structHash = keccak256(
                            abi.encode(
                                DELEGATION_TYPEHASH,
                                delegatee,
                                nonce,
                                expiry
                            )
                        );
                
                        bytes32 digest = keccak256(
                            abi.encodePacked(
                                "\x19\x01",
                                domainSeparator,
                                structHash
                            )
                        );
                
                        address signatory = ecrecover(digest, v, r, s);
                        require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
                        require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
                        require(now <= expiry, "SUSHI::delegateBySig: signature expired");
                        return _delegate(signatory, delegatee);
                    }
                
                    /**
                     * @notice Gets the current votes balance for `account`
                     * @param account The address to get votes balance
                     * @return The number of current votes for `account`
                     */
                    function getCurrentVotes(address account)
                        external
                        view
                        returns (uint256)
                    {
                        uint32 nCheckpoints = numCheckpoints[account];
                        return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
                    }
                
                    /**
                     * @notice Determine the prior number of votes for an account as of a block number
                     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
                     * @param account The address of the account to check
                     * @param blockNumber The block number to get the vote balance at
                     * @return The number of votes the account had as of the given block
                     */
                    function getPriorVotes(address account, uint blockNumber)
                        external
                        view
                        returns (uint256)
                    {
                        require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
                
                        uint32 nCheckpoints = numCheckpoints[account];
                        if (nCheckpoints == 0) {
                            return 0;
                        }
                
                        // First check most recent balance
                        if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
                            return checkpoints[account][nCheckpoints - 1].votes;
                        }
                
                        // Next check implicit zero balance
                        if (checkpoints[account][0].fromBlock > blockNumber) {
                            return 0;
                        }
                
                        uint32 lower = 0;
                        uint32 upper = nCheckpoints - 1;
                        while (upper > lower) {
                            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                            Checkpoint memory cp = checkpoints[account][center];
                            if (cp.fromBlock == blockNumber) {
                                return cp.votes;
                            } else if (cp.fromBlock < blockNumber) {
                                lower = center;
                            } else {
                                upper = center - 1;
                            }
                        }
                        return checkpoints[account][lower].votes;
                    }
                
                    function _delegate(address delegator, address delegatee)
                        internal
                    {
                        address currentDelegate = _delegates[delegator];
                        uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
                        _delegates[delegator] = delegatee;
                
                        emit DelegateChanged(delegator, currentDelegate, delegatee);
                
                        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
                    }
                
                    function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
                        if (srcRep != dstRep && amount > 0) {
                            if (srcRep != address(0)) {
                                // decrease old representative
                                uint32 srcRepNum = numCheckpoints[srcRep];
                                uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                                uint256 srcRepNew = srcRepOld.sub(amount);
                                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
                            }
                
                            if (dstRep != address(0)) {
                                // increase new representative
                                uint32 dstRepNum = numCheckpoints[dstRep];
                                uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                                uint256 dstRepNew = dstRepOld.add(amount);
                                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
                            }
                        }
                    }
                
                    function _writeCheckpoint(
                        address delegatee,
                        uint32 nCheckpoints,
                        uint256 oldVotes,
                        uint256 newVotes
                    )
                        internal
                    {
                        uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
                
                        if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
                            checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
                        } else {
                            checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
                            numCheckpoints[delegatee] = nCheckpoints + 1;
                        }
                
                        emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
                    }
                
                    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
                        require(n < 2**32, errorMessage);
                        return uint32(n);
                    }
                
                    function getChainId() internal pure returns (uint) {
                        uint256 chainId;
                        assembly { chainId := chainid() }
                        return chainId;
                    }
                }
                
                // File: contracts/MasterChef.sol
                
                pragma solidity 0.6.12;
                
                
                
                
                
                
                
                
                interface IMigratorChef {
                    // Perform LP token migration from legacy UniswapV2 to SushiSwap.
                    // Take the current LP token address and return the new LP token address.
                    // Migrator should have full access to the caller's LP token.
                    // Return the new LP token address.
                    //
                    // XXX Migrator must have allowance access to UniswapV2 LP tokens.
                    // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
                    // else something bad will happen. Traditional UniswapV2 does not
                    // do that so be careful!
                    function migrate(IERC20 token) external returns (IERC20);
                }
                
                // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
                //
                // Note that it's ownable and the owner wields tremendous power. The ownership
                // will be transferred to a governance smart contract once SUSHI is sufficiently
                // distributed and the community can show to govern itself.
                //
                // Have fun reading it. Hopefully it's bug-free. God bless.
                contract MasterChef is Ownable {
                    using SafeMath for uint256;
                    using SafeERC20 for IERC20;
                
                    // Info of each user.
                    struct UserInfo {
                        uint256 amount;     // How many LP tokens the user has provided.
                        uint256 rewardDebt; // Reward debt. See explanation below.
                        //
                        // We do some fancy math here. Basically, any point in time, the amount of SUSHIs
                        // entitled to a user but is pending to be distributed is:
                        //
                        //   pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
                        //
                        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
                        //   1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
                        //   2. User receives the pending reward sent to his/her address.
                        //   3. User's `amount` gets updated.
                        //   4. User's `rewardDebt` gets updated.
                    }
                
                    // Info of each pool.
                    struct PoolInfo {
                        IERC20 lpToken;           // Address of LP token contract.
                        uint256 allocPoint;       // How many allocation points assigned to this pool. SUSHIs to distribute per block.
                        uint256 lastRewardBlock;  // Last block number that SUSHIs distribution occurs.
                        uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
                    }
                
                    // The SUSHI TOKEN!
                    SushiToken public sushi;
                    // Dev address.
                    address public devaddr;
                    // Block number when bonus SUSHI period ends.
                    uint256 public bonusEndBlock;
                    // SUSHI tokens created per block.
                    uint256 public sushiPerBlock;
                    // Bonus muliplier for early sushi makers.
                    uint256 public constant BONUS_MULTIPLIER = 10;
                    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
                    IMigratorChef public migrator;
                
                    // Info of each pool.
                    PoolInfo[] public poolInfo;
                    // Info of each user that stakes LP tokens.
                    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
                    // Total allocation poitns. Must be the sum of all allocation points in all pools.
                    uint256 public totalAllocPoint = 0;
                    // The block number when SUSHI mining starts.
                    uint256 public startBlock;
                
                    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
                    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
                    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
                
                    constructor(
                        SushiToken _sushi,
                        address _devaddr,
                        uint256 _sushiPerBlock,
                        uint256 _startBlock,
                        uint256 _bonusEndBlock
                    ) public {
                        sushi = _sushi;
                        devaddr = _devaddr;
                        sushiPerBlock = _sushiPerBlock;
                        bonusEndBlock = _bonusEndBlock;
                        startBlock = _startBlock;
                    }
                
                    function poolLength() external view returns (uint256) {
                        return poolInfo.length;
                    }
                
                    // Add a new lp to the pool. Can only be called by the owner.
                    // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
                    function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
                        if (_withUpdate) {
                            massUpdatePools();
                        }
                        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
                        totalAllocPoint = totalAllocPoint.add(_allocPoint);
                        poolInfo.push(PoolInfo({
                            lpToken: _lpToken,
                            allocPoint: _allocPoint,
                            lastRewardBlock: lastRewardBlock,
                            accSushiPerShare: 0
                        }));
                    }
                
                    // Update the given pool's SUSHI allocation point. Can only be called by the owner.
                    function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
                        if (_withUpdate) {
                            massUpdatePools();
                        }
                        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
                        poolInfo[_pid].allocPoint = _allocPoint;
                    }
                
                    // Set the migrator contract. Can only be called by the owner.
                    function setMigrator(IMigratorChef _migrator) public onlyOwner {
                        migrator = _migrator;
                    }
                
                    // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
                    function migrate(uint256 _pid) public {
                        require(address(migrator) != address(0), "migrate: no migrator");
                        PoolInfo storage pool = poolInfo[_pid];
                        IERC20 lpToken = pool.lpToken;
                        uint256 bal = lpToken.balanceOf(address(this));
                        lpToken.safeApprove(address(migrator), bal);
                        IERC20 newLpToken = migrator.migrate(lpToken);
                        require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
                        pool.lpToken = newLpToken;
                    }
                
                    // Return reward multiplier over the given _from to _to block.
                    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
                        if (_to <= bonusEndBlock) {
                            return _to.sub(_from).mul(BONUS_MULTIPLIER);
                        } else if (_from >= bonusEndBlock) {
                            return _to.sub(_from);
                        } else {
                            return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
                                _to.sub(bonusEndBlock)
                            );
                        }
                    }
                
                    // View function to see pending SUSHIs on frontend.
                    function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
                        PoolInfo storage pool = poolInfo[_pid];
                        UserInfo storage user = userInfo[_pid][_user];
                        uint256 accSushiPerShare = pool.accSushiPerShare;
                        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
                        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
                            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
                            uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
                            accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
                        }
                        return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
                    }
                
                    // Update reward vairables for all pools. Be careful of gas spending!
                    function massUpdatePools() public {
                        uint256 length = poolInfo.length;
                        for (uint256 pid = 0; pid < length; ++pid) {
                            updatePool(pid);
                        }
                    }
                
                    // Update reward variables of the given pool to be up-to-date.
                    function updatePool(uint256 _pid) public {
                        PoolInfo storage pool = poolInfo[_pid];
                        if (block.number <= pool.lastRewardBlock) {
                            return;
                        }
                        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
                        if (lpSupply == 0) {
                            pool.lastRewardBlock = block.number;
                            return;
                        }
                        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
                        uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
                        sushi.mint(devaddr, sushiReward.div(10));
                        sushi.mint(address(this), sushiReward);
                        pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
                        pool.lastRewardBlock = block.number;
                    }
                
                    // Deposit LP tokens to MasterChef for SUSHI allocation.
                    function deposit(uint256 _pid, uint256 _amount) public {
                        PoolInfo storage pool = poolInfo[_pid];
                        UserInfo storage user = userInfo[_pid][msg.sender];
                        updatePool(_pid);
                        if (user.amount > 0) {
                            uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
                            safeSushiTransfer(msg.sender, pending);
                        }
                        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
                        user.amount = user.amount.add(_amount);
                        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
                        emit Deposit(msg.sender, _pid, _amount);
                    }
                
                    // Withdraw LP tokens from MasterChef.
                    function withdraw(uint256 _pid, uint256 _amount) public {
                        PoolInfo storage pool = poolInfo[_pid];
                        UserInfo storage user = userInfo[_pid][msg.sender];
                        require(user.amount >= _amount, "withdraw: not good");
                        updatePool(_pid);
                        uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
                        safeSushiTransfer(msg.sender, pending);
                        user.amount = user.amount.sub(_amount);
                        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
                        pool.lpToken.safeTransfer(address(msg.sender), _amount);
                        emit Withdraw(msg.sender, _pid, _amount);
                    }
                
                    // Withdraw without caring about rewards. EMERGENCY ONLY.
                    function emergencyWithdraw(uint256 _pid) public {
                        PoolInfo storage pool = poolInfo[_pid];
                        UserInfo storage user = userInfo[_pid][msg.sender];
                        pool.lpToken.safeTransfer(address(msg.sender), user.amount);
                        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
                        user.amount = 0;
                        user.rewardDebt = 0;
                    }
                
                    // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
                    function safeSushiTransfer(address _to, uint256 _amount) internal {
                        uint256 sushiBal = sushi.balanceOf(address(this));
                        if (_amount > sushiBal) {
                            sushi.transfer(_to, sushiBal);
                        } else {
                            sushi.transfer(_to, _amount);
                        }
                    }
                
                    // Update dev address by the previous dev.
                    function dev(address _devaddr) public {
                        require(msg.sender == devaddr, "dev: wut?");
                        devaddr = _devaddr;
                    }
                }

                File 6 of 6: ConvexRewarder
                // 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 view returns (address);
                    function rewardToken() external view returns(address);
                    function earned(address account) external view returns (uint256);
                }
                
                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);
                    function setGaugeRedirect(uint256 _pid) external returns(bool);
                }
                
                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\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: node_modules\@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: node_modules\@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\interfaces\ISushiRewarder.sol
                
                pragma solidity 0.6.12;
                
                interface ISushiRewarder {
                    using SafeERC20 for IERC20;
                    function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external;
                    function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory);
                }
                
                
                // File: contracts\ConvexRewarder.sol
                
                pragma solidity 0.6.12;
                /**
                 *Submitted for verification at Etherscan.io on 2020-07-17
                 */
                
                /*
                   ____            __   __        __   _
                  / __/__ __ ___  / /_ / /  ___  / /_ (_)__ __
                 _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
                /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
                     /___/
                
                * 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
                */
                
                
                
                interface IMasterChefV2 {
                    function lpToken(uint i) external view returns (IERC20);
                }
                
                interface IConvexChef{
                    function userInfo(uint256 _pid, address _account) external view returns(uint256,uint256);
                    function claim(uint256 _pid, address _account) external;
                    function deposit(uint256 _pid, uint256 _amount) external;
                }
                
                
                contract ConvexRewarder is ISushiRewarder{
                    using SafeERC20 for IERC20;
                    using SafeMath for uint256;
                
                    IERC20 public immutable rewardToken;
                    IERC20 public immutable stakingToken;
                    uint256 public constant duration = 5 days;
                
                    address public immutable rewardManager;
                    address public immutable sushiMasterChef;
                    address public immutable convexMasterChef;
                    uint256 public immutable chefPid;
                
                    uint256 public periodFinish = 0;
                    uint256 public rewardRate = 0;
                    uint256 public lastUpdateTime;
                    uint256 public rewardPerTokenStored;
                    uint256 public currentRewards = 0;
                    uint256 private _totalSupply;
                    uint256 public sushiPid;
                    uint256 public previousRewardDebt = 0;
                    bool public isInit = false;
                
                    mapping(address => uint256) private _balances;
                    mapping(address => uint256) private _sushiBalances;
                    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 rewardManager_,
                        address sushiMasterChef_,
                        address convexMasterChef_,
                        uint256 chefPid_
                    ) public {
                        stakingToken = IERC20(stakingToken_);
                        rewardToken = IERC20(rewardToken_);
                        rewardManager = rewardManager_;
                        sushiMasterChef = sushiMasterChef_;
                        convexMasterChef = convexMasterChef_;
                        chefPid = chefPid_;
                    }
                
                    //stake a dummy token into convex chef to start earning rewards
                    //initiate a week's worth of awards
                    function init(IERC20 dummyToken) external {
                        require(!isInit,"already init");
                        isInit = true;
                        uint256 balance = dummyToken.balanceOf(msg.sender);
                        require(balance != 0, "Balance must exceed 0");
                        dummyToken.safeTransferFrom(msg.sender, address(this), balance);
                        dummyToken.approve(convexMasterChef, balance);
                        IConvexChef(convexMasterChef).deposit(chefPid, balance);
                        initRewards();
                    }
                
                    //claim from convex master chef and add to rewards
                    function harvestFromMasterChef() public {
                        IConvexChef(convexMasterChef).claim(chefPid, address(this));
                        notifyRewardAmount();
                    }
                
                    function totalSupply() public view returns (uint256) {
                        return _totalSupply;
                    }
                
                    function balanceOf(address account) public view returns (uint256) {
                        return _balances[account].add(_sushiBalances[account]);
                    }
                
                    function localBalanceOf(address account) public view returns (uint256) {
                        return _balances[account];
                    }
                
                    function sushiBalanceOf(address account) public view returns (uint256) {
                        return _sushiBalances[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] = earned(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 earned(address account) public view returns (uint256) {
                        return
                            _balances[account].add(_sushiBalances[account])
                                .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                                .div(1e18)
                                .add(rewards[account]);
                    }
                
                    function stake(uint256 _amount)
                        public
                        updateReward(msg.sender)
                    {
                        require(_amount > 0, 'RewardPool : Cannot stake 0');
                
                        //check if new rewards should be pulled from convex chef
                        checkHarvest();
                
                        //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');
                
                        //check if new rewards should be pulled from convex chef
                        checkHarvest();
                
                        //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);
                        }
                    }
                
                    function withdrawAll(bool claim) external{
                        withdraw(_balances[msg.sender],claim);
                    }
                
                    function getReward(address _account, bool _claimExtras) public updateReward(_account){
                
                        uint256 reward = earned(_account);
                        if (reward > 0) {
                            rewards[_account] = 0;
                            rewardToken.safeTransfer(_account, reward);
                            emit RewardPaid(_account, reward);
                        }
                
                        //also get rewards from linked rewards
                        if(_claimExtras){
                            uint256 length = extraRewards.length;
                            for(uint i=0; i < length; i++){
                                IRewards(extraRewards[i]).getReward(_account);
                            }
                        }
                
                        //check if new rewards should be pulled from convex chef
                        checkHarvest();
                    }
                
                    function getReward() external{
                        getReward(msg.sender,true);
                    }
                
                    function checkHarvest() internal{
                        //if getting close to the end of the period
                        //claim and extend
                        if (periodFinish > 0 && block.timestamp >= periodFinish.sub(1 days)  ) {
                            harvestFromMasterChef();
                        }
                    }
                
                    //initialize the period of rewards
                    //since the reward rate should be same as speed as rewards coming in from the chef
                    // it will never catch up unless there is a seed
                    // (or if it mines for a week with 0 distribution)
                    function initRewards() internal updateReward(address(0)){
                        uint256 reward = rewardToken.balanceOf(address(this));
                        
                        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);
                    }
                
                    function notifyRewardAmount()
                        internal
                        updateReward(address(0))
                    {
                        if(!isInit){
                            //return smoothly if not init yet.
                            //allow stakers to join but dont start distribution
                            return;
                        }
                        //convex chef allows anyone to claim, so we have to look at reward debt difference
                        //so that we know how much we have claimed since previous notifyRewardAmount()
                        (,uint256 rewardDebt) = IConvexChef(convexMasterChef).userInfo(chefPid, address(this));
                        uint256 reward = rewardDebt.sub(previousRewardDebt);
                        previousRewardDebt = rewardDebt;
                        if(reward == 0) return;
                        
                        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);
                    }
                
                    function onSushiReward(
                        uint256 pid,
                        address user,
                        address recipient,
                        uint256 sushiAmount,
                        uint256 newLpAmount
                    )
                        override
                        external
                        updateReward(user)
                    {
                        require(msg.sender == sushiMasterChef);
                      
                        // On the first call, validate that the pid correctly maps to our stakingToken
                        // Sushi MasterChef does not allow modifying a pid after it has been set, so we can trust
                        // this to be safe in the future. If we did not validate the pid going forward, there
                        // could be an attack vector by setting this contract as rewardContract on a 2nd pid
                        uint256 _sushiPid = sushiPid;
                        if (_sushiPid == 0) {
                            require(IMasterChefV2(msg.sender).lpToken(pid) == stakingToken);
                            sushiPid = pid;
                        } else {
                            require(pid == _sushiPid);
                        }
                
                        if (sushiAmount > 0) {
                            // if sushiAmount > 0 the call is claiming sushi and should also claim other rewards
                
                            //sushi allows claiming for user and transferring to recipient, but we do not.
                            //just claim to original account
                            getReward(user,true);
                        }
                
                        uint256 userBalance = _sushiBalances[user];
                        if (newLpAmount > userBalance) {
                            // reported balance in sushi > internal accounting, user has deposited
                            uint256 amount = newLpAmount.sub(userBalance);
                            uint256 length = extraRewards.length;
                            for(uint i=0; i < length; i++){
                                IRewards(extraRewards[i]).stake(user, amount);
                            }
                            _totalSupply = _totalSupply.add(amount);
                            _sushiBalances[user] = newLpAmount;
                
                        } else if (newLpAmount < userBalance) {
                            // reported balance in sushi < internal accounting, user has withdrawn
                            uint256 amount = userBalance.sub(newLpAmount);
                            uint256 length = extraRewards.length;
                            for(uint i=0; i < length; i++){
                                IRewards(extraRewards[i]).withdraw(msg.sender, amount);
                            }
                            _totalSupply = _totalSupply.sub(amount);
                            _sushiBalances[user] = newLpAmount;
                        }
                    }
                
                    function pendingTokens(
                        uint256 pid,
                        address user,
                        uint256 sushiAmount
                    )
                        override
                        external
                        view
                        returns (IERC20[] memory, uint256[] memory)
                    {
                        //extra rewards length
                        uint256 length = extraRewards.length;
                
                        //combine base and extras
                        IERC20[] memory rewardTokens = new IERC20[](1+length);
                        rewardTokens[0] = rewardToken;
                        for(uint i=0; i < length; i++){
                           rewardTokens[1+i] = IERC20(IRewards(extraRewards[i]).rewardToken());
                        }
                        uint256[] memory earnedAmounts = new uint256[](1+length);
                        earnedAmounts[0] = earned(user);
                        for(uint i=0; i < length; i++){
                            earnedAmounts[1+i] = IRewards(extraRewards[i]).earned(user);
                        }
                        return (rewardTokens,earnedAmounts);
                    }
                }