Contract 0x6a894bd1a5476bdc52b709623b8751e244e6e975 1

 
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x6e8701014822b15631cf1f86ed60355560783792af891b87f4a68f83cba393c3Claim Vested Rew...155344942022-06-23 16:06:1210 days 11 hrs ago0xbfd1ee260ce1163a3e3b55cc8ba3b6f937ad0c37 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000252221894 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907Unstake ERC20And...145139872022-06-13 14:55:1120 days 12 hrs ago0x2e08188f39c946b4a9d0b6c91a6a89d6fbc52949 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.001052791172 ETH
0x260be51bc95a74fb3e5565aca9e0a4a33ca59ccad0d699d33b5bdd1fee38b8d5Claim Vested Rew...135453322022-06-02 17:15:2131 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000237284428 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470Unstake ERC20And...135453162022-06-02 17:14:3331 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000461810477 ETH
0x80c5f511710bf07d952af05af03bdd87a827d21fd657bcab2b7fb49709cc0ccaClaim Vested Rew...135452832022-06-02 17:14:3331 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000237634481 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9Unstake ERC20And...135452542022-06-02 17:14:3331 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000459674596 ETH
0x8ffb0e61b747f169eb637ecd705d4e45e80767cf3f3896b641ba7fd23d331d56Claim Vested Rew...135452412022-06-02 17:14:0331 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000236195149 ETH
0x12a4416e7523c3976213604e81dc04e21d87a251347054a398da0f0615964356Unstake ERC20And...135448472022-06-02 17:08:1431 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000461760179 ETH
0x861c8050249753a0bf059d0538da4bee9be6f7b6e21ab4e7796f940669c5dd79Claim Vested Rew...135448262022-06-02 17:08:1431 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000237968276 ETH
0x54f1afd20cf6d3735c970aa294e7126e64e355fbc3583b84c7c3c9fa5176ce76Unstake ERC20And...135447872022-06-02 17:08:0731 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.0004591579 ETH
0x7134811f8ff1c27b01bb70bf917c3a02327918cd62759d66a35c88a1559789a3Claim Vested Rew...135442872022-06-02 17:00:5131 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000237978437 ETH
0x84eeb5145f827300ab1c56709e09a20e9298e7a5d84dbe431b51069c2fcbd4e3Unstake ERC20And...135442652022-06-02 16:59:4231 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000458980587 ETH
0xb2578aa7023b2b37f65c6f6ce6edabf3375f32d8027559f822539afe68ed30caUnstake ERC20And...135441462022-06-02 16:58:5131 days 10 hrs ago0x37da9f53bb706b0ce36b623c50f4d21895c48d80 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000539000911 ETH
0xe776bbe0779a1ba2962eddccb0cd08d5e0b8f81f58002ead2bfbddb353215cb8Fund135439792022-06-02 16:56:5031 days 10 hrs ago0x1d427f8f08cd8b40bf07f58f11acf39cf45504b0 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000248054265 ETH
0xf6ac5616466b1f1b2acb903dfa3e6052fbab06982ecdb979e01b6890e7e23234Unstake ERC20And...132221732022-05-29 18:30:5535 days 8 hrs ago0x41d0fb81f19f67b15cf71f4a3997f08321a614f6 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000233575218 ETH
0x04afb38806f1fdeb14c993a9350c5c82a40af0c1049309736891dcf23352a94eClaim Vested Rew...129975432022-05-26 13:59:2438 days 13 hrs ago0xefeb0b9ef8e5732bf8a6cfadf86dc7e90e15b98c IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000236121749 ETH
0x15aed5e2296ccdb3cdd84bf110ee16ab449fff21aa6aa9670ea1727c1b90f07dUnstake ERC20And...129974882022-05-26 13:57:5638 days 13 hrs ago0xefeb0b9ef8e5732bf8a6cfadf86dc7e90e15b98c IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000456972347 ETH
0x9261f44e47ebae38c1d911298c840fe86f50d7263f646125a8eb8ef1e965067cStake ERC20126405332022-05-21 14:03:5643 days 13 hrs ago0xa823844fc39e38c634a53ac587993ee0335ce536 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000282065304 ETH
0xaa7f152e38a2204a4b03df2911234f3e25315ccc6057ac5d736f490448ac0ddfUnstake ERC20And...126202282022-05-21 8:26:4643 days 18 hrs ago0xa823844fc39e38c634a53ac587993ee0335ce536 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000299037959 ETH
0x1b54513f74f4f4723f762008688df38d6b92feb9c839023fb4ac60738b79440cClaim Vested Rew...126198662022-05-21 8:20:1143 days 19 hrs ago0xa823844fc39e38c634a53ac587993ee0335ce536 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000125517115 ETH
0x649f6d7ea5d963aebadf076d43db7fb39d41e7b9ef0167b49b8db38879f142a4Unstake ERC20And...119405982022-05-12 23:02:1552 days 4 hrs ago0xd9d83edb33c8847e12b81496d0e573ab9cff4f6b IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.002137723441 ETH
0xa4665b9b104bfb02d5d6091222049c2c7d4d0b22a8712991b7cd92b97cb8f791Claim Vested Rew...112398402022-05-05 9:50:2759 days 17 hrs ago0xbfd1ee260ce1163a3e3b55cc8ba3b6f937ad0c37 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000249909362 ETH
0xea127a5e44d99b42a75ca7f1a189cc718b2e765cb9c13afdf1497e5972ee6b0eClaim Vested Rew...112398052022-05-05 9:50:2759 days 17 hrs ago0xbfd1ee260ce1163a3e3b55cc8ba3b6f937ad0c37 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000250613811 ETH
0x930cc57625bb3841222f666f054107747633b4797db99e7d6590aa826baf99dfUnstake ERC20And...112397492022-05-05 9:49:4259 days 17 hrs ago0xbfd1ee260ce1163a3e3b55cc8ba3b6f937ad0c37 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000484656848 ETH
0xd374731d2e8eb8fafb55c7e25023747ef1acacda79dfb716b3d296c20ad2d657Unstake ERC20And...112396322022-05-05 9:47:1259 days 17 hrs ago0xbfd1ee260ce1163a3e3b55cc8ba3b6f937ad0c37 IN  0x6a894bd1a5476bdc52b709623b8751e244e6e9750 ETH0.000481709858 ETH
[ Download CSV Export 
Latest 25 internal transaction
Parent Txn Hash Block From To Value
0x6e8701014822b15631cf1f86ed60355560783792af891b87f4a68f83cba393c3155344942022-06-23 16:06:1210 days 11 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x6e8701014822b15631cf1f86ed60355560783792af891b87f4a68f83cba393c3155344942022-06-23 16:06:1210 days 11 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x6e8701014822b15631cf1f86ed60355560783792af891b87f4a68f83cba393c3155344942022-06-23 16:06:1210 days 11 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907145139872022-06-13 14:55:1120 days 12 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907145139872022-06-13 14:55:1120 days 12 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0xe41def472125bf5b8385a3fff90c01bd3d02eb260 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907145139872022-06-13 14:55:1120 days 12 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xd5f10f8cc737f99bf08f51829a4c2c454469f22d0 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907145139872022-06-13 14:55:1120 days 12 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x0174fec1d27c01ad81388425b39b53e45e591ea70 ETH
0x128cc390e72aea3a6b3549de6a8244a8f77635e5b345696c86451fd603192907145139872022-06-13 14:55:1120 days 12 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x260be51bc95a74fb3e5565aca9e0a4a33ca59ccad0d699d33b5bdd1fee38b8d5135453322022-06-02 17:15:2131 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x260be51bc95a74fb3e5565aca9e0a4a33ca59ccad0d699d33b5bdd1fee38b8d5135453322022-06-02 17:15:2131 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x260be51bc95a74fb3e5565aca9e0a4a33ca59ccad0d699d33b5bdd1fee38b8d5135453322022-06-02 17:15:2131 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470135453162022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470135453162022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0xe41def472125bf5b8385a3fff90c01bd3d02eb260 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470135453162022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xa342c2fae267a558b0c713c769397ccfa321cddd0 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470135453162022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x1500de211bde10d466726812b4e667b8b92607b80 ETH
0x569c151b0859317b7bc1c78a40182014c7c1621eabf944db80f0918710057470135453162022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x80c5f511710bf07d952af05af03bdd87a827d21fd657bcab2b7fb49709cc0cca135452832022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x80c5f511710bf07d952af05af03bdd87a827d21fd657bcab2b7fb49709cc0cca135452832022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x80c5f511710bf07d952af05af03bdd87a827d21fd657bcab2b7fb49709cc0cca135452832022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9135452542022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9135452542022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0xe41def472125bf5b8385a3fff90c01bd3d02eb260 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9135452542022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xa342c2fae267a558b0c713c769397ccfa321cddd0 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9135452542022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x83f57e83e6a4cd049835685b281088324b1dd09e0 ETH
0x806e06b838a49ea790f10c36607e2fd5a6df217220bdea39c6a95ddf2ab22af9135452542022-06-02 17:14:3331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e9750xf3ae17201ae42233540a966cd7631f2dceb95ca70 ETH
0x8ffb0e61b747f169eb637ecd705d4e45e80767cf3f3896b641ba7fd23d331d56135452412022-06-02 17:14:0331 days 10 hrs ago 0x6a894bd1a5476bdc52b709623b8751e244e6e975 0x09fc6e37633dd9dac7da1002c34b063ebaa62c070 ETH
[ Download CSV Export 
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
ArbiStakerERC20

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 1000 runs

Other Settings:
default evmVersion
File 1 of 33 : ArbiStakerERC20.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";

import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVault} from "../arbiVault/ArbiVault.sol";
import {ArbiVaultFactory} from "../arbiVault/ArbiVaultFactory.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
import {IERC2917} from "./IERC2917.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";

interface IRageQuit {
    function rageQuit() external;
}

interface IArbiStaker is IRageQuit {
    /* admin events */

    event ArbiStakerERC20Created(address rewardPool, address powerSwitch);
    event ArbiStakerERC20Funded(address token, uint256 amount);
    event BonusTokenRegistered(address token);
    event BonusTokenRemoved(address token);
    event VaultFactoryRegistered(address factory);
    event VaultFactoryRemoved(address factory);
    event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin);

    /* user events */

    event Staked(address vault, uint256 amount);
    event Unstaked(address vault, uint256 amount);
    event RageQuit(address vault);
    event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount);
    event VestedRewardClaimed(address recipient, address token, uint256 amount);

    /* data types */

    struct VaultData {
        // token address to total token stake mapping
        mapping(address => uint256) tokenStake;
        EnumerableSet.AddressSet tokens;
    }

    struct LMRewardData {
        uint256 amount;
        uint256 duration;
        uint256 startedAt;
        address rewardCalcInstance;
        EnumerableSet.AddressSet bonusTokens;
        mapping(address => uint256) bonusTokenAmounts;
    }

    struct LMRewardVestingData {
        uint256 amount;
        uint256 startedAt;
    }

    /* getter functions */
    function getBonusTokenSetLength() external view returns (uint256 length);

    function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);

    function getVaultFactorySetLength() external view returns (uint256 length);

    function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);

    function getNumVaults() external view returns (uint256 num);

    function getVaultAt(uint256 index) external view returns (address vault);

    function getNumTokensStaked() external view returns (uint256 num);

    function getTokenStakedAt(uint256 index) external view returns (address token);

    function getNumTokensStakedInVault(address vault) external view returns (uint256 num);

    function getVaultTokenAtIndex(address vault, uint256 index)
        external
        view
        returns (address vaultToken);

    function getVaultTokenStake(address vault, address token)
        external
        view
        returns (uint256 tokenStake);

    function getLMRewardData(address token)
        external
        view
        returns (
            uint256 amount,
            uint256 duration,
            uint256 startedAt,
            address rewardCalcInstance
        );

    function getLMRewardBonusTokensLength(address token) external view returns (uint256 length);

    function getLMRewardBonusTokenAt(address token, uint256 index)
        external
        view
        returns (address bonusToken, uint256 bonusTokenAmount);

    function getNumVestingLMTokenRewards(address user) external view returns (uint256 num);

    function getVestingLMTokenAt(address user, uint256 index) external view returns (address token);

    function getNumVests(address user, address token) external view returns (uint256 num);

    function getNumRewardCalcTemplates() external view returns (uint256 num);

    function getLMRewardVestingData(
        address user,
        address token,
        uint256 index
    ) external view returns (uint256 amount, uint256 startedAt);

    function isValidAddress(address target) external view returns (bool validity);

    function isValidVault(address vault, address factory) external view returns (bool validity);

    /* user functions */

    function stakeERC20(
        address vault,
        address vaultFactory,
        address token,
        uint256 amount,
        bytes calldata permission
    ) external;

    function unstakeERC20AndClaim(
        address vault,
        address vaultFactory,
        address recipient,
        address token,
        uint256 amount,
        bool claimBonusReward,
        bytes calldata permission
    ) external;

    function claimVestedRewardAll() external;

    function claimVestedRewardToken(address token) external;
}

/// @title ArbiStaker
/// @notice Reward distribution contract that handles ERC20 Tokens with Tiers
/// Access Control
/// - Power controller:
///     Can power off / shutdown the ArbiStaker
///     Can withdraw rewards from reward pool once shutdown
/// - Owner:
///     Is unable to operate on user funds due to UniversalVault
///     Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - ArbiStaker admin:
///     Can add funds to the ArbiStaker, register bonus tokens, and whitelist new vault factories
///     Is a subset of owner permissions
/// - User:
///     Can stake / unstake / ragequit / claim vested rewards
/// ArbiStaker State Machine
/// - Online:
///     ArbiStaker is operating normally, all functions are enabled
/// - Offline:
///     ArbiStaker is temporarely disabled for maintenance
///     User staking and unstaking is disabled, ragequit remains enabled
///     Users can delete their stake through rageQuit() but forego their pending reward
///     Should only be used when downtime required for an upgrade
/// - Shutdown:
///     ArbiStaker is permanently disabled
///     All functions are disabled with the exception of ragequit
///     Users can delete their stake through rageQuit()
///     Power controller can withdraw from the reward pool
///     Should only be used if Owner role is compromised
contract ArbiStakerERC20 is IArbiStaker, Powered {
    using SafeMath for uint256;
    using EnumerableSet for EnumerableSet.AddressSet;

    /* constants */
    string public constant PIONNER = "PIONNER";
    string public constant PRECURSOR = "PRECURSOR";
    string public constant INNOVATOR = "INNOVATOR";
    string public constant EARLY_ADOPTER = "EARLY_ADOPTER";
    string public constant STANDARD = "STANDARD";
    uint256 public PIONNER_LM_REWARD_MULTIPLIER_NUM = 6;
    uint256 public PIONNER_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public PRECURSOR_LM_REWARD_MULTIPLIER_NUM = 5;
    uint256 public PRECURSOR_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public INNOVATOR_LM_REWARD_MULTIPLIER_NUM = 2;
    uint256 public INNOVATOR_LM_REWARD_MULTIPLIER_DENOM = 1;
    uint256 public EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM = 3;
    uint256 public EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public STANDARD_LM_REWARD_MULTIPLIER_NUM = 1;
    uint256 public STANDARD_LM_REWARD_MULTIPLIER_DENOM = 1;
    uint256 public LM_REWARD_VESTING_PERIOD = 2592000; // 30 days
    uint256 public LM_REWARD_VESTING_PORTION_NUM = 1;
    uint256 public LM_REWARD_VESTING_PORTION_DENOM = 2;

    // An upper bound on the number of active tokens staked per vault is required to prevent
    // calls to rageQuit() from reverting.
    // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
    // than the hardcoded limit of 500k gas on the vault.
    // This limit is configurable and could be increased in a future deployment.
    // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
    // an error code that allows for reliably catching out-of-gas errors on remote calls.
    uint256 public MAX_TOKENS_STAKED_PER_VAULT = 10;
    uint256 public MAX_BONUS_TOKENS = 10;

    /* storage */
    address public admin;
    address public rewardToken;
    address public rewardPool;

    EnumerableSet.AddressSet private _vaultSet;
    mapping(address => VaultData) private _vaults;

    EnumerableSet.AddressSet private _bonusTokenSet;
    EnumerableSet.AddressSet private _vaultFactorySet;

    EnumerableSet.AddressSet private _allStakedTokens;
    mapping(address => uint256) public stakedTokenTotal;

    mapping(address => LMRewardData) private lmRewards;

    // user to token to earned reward mapping
    mapping(address => mapping(address => uint256)) public earnedLMRewards;
    // user to token to vesting data mapping
    mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
    // user to vesting lm token rewards set
    mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;

    // erc2917 template names
    string[] public rewardCalcTemplateNames;
    // erc2917 template names to erc 2917 templates
    mapping(string => address) public rewardCalcTemplates;
    string public activeRewardCalcTemplate;
    event RewardCalcTemplateAdded(string indexed name, address indexed template);
    event RewardCalcTemplateActive(string indexed name, address indexed template);

    /* initializer */

    /// @notice Initizalize ArbiStaker
    /// access control: only proxy constructor
    /// state machine: can only be called once
    /// state scope: set initialization variables
    /// token transfer: none
    /// @param adminAddress address The admin address
    /// @param rewardPoolFactory address The factory to use for deploying the RewardPool
    /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
    /// @param rewardTokenAddress address The address of the reward token for this ArbiStaker
    constructor(
        address adminAddress,
        address rewardPoolFactory,
        address powerSwitchFactory,
        address rewardTokenAddress
    ) {
        // deploy power switch
        address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));

        // deploy reward pool
        rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));

        // set internal config
        admin = adminAddress;
        rewardToken = rewardTokenAddress;
        Powered._setPowerSwitch(powerSwitch);

        // emit event
        emit ArbiStakerERC20Created(rewardPool, powerSwitch);
    }

    /* admin functions */

    function _admin() private {
        require(msg.sender == admin, "not allowed");
    }

    /**
     * @dev Leaves the contract without admin. It will not be possible to call
     * `admin` functions anymore. Can only be called by the current admin.
     *
     * NOTE: Renouncing adminship will leave the contract without an admin,
     * thereby removing any functionality that is only available to the admin.
     */
    function renounceAdminship() public {
        _admin();
        emit AdminshipTransferred(admin, address(0));
        admin = address(0);
    }

    /**
     * @dev Transfers adminship of the contract to a new account (`newAdmin`).
     * Can only be called by the current admin.
     */
    function transferAdminship(address newAdmin) public {
        _admin();
        require(newAdmin != address(0), "new admin can't the zero address");
        emit AdminshipTransferred(admin, newAdmin);
        admin = newAdmin;
    }

    /// @notice Add funds to ArbiStaker
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    /// state scope:
    ///   - none
    /// token transfer: transfer staking tokens from msg.sender to reward pool
    /// @param amount uint256 Amount of reward tokens to deposit
    function fund(address token, uint256 amount) external {
        _admin();
        require(
            _bonusTokenSet.contains(token) || token == rewardToken,
            "cannot fund with unrecognized token"
        );
        // transfer reward tokens to reward pool
        TransferHelper.safeTransferFrom(token, msg.sender, rewardPool, amount);

        // emit event
        emit ArbiStakerERC20Funded(token, amount);
    }

    /// @notice Rescue tokens from RewardPool
    /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope: none
    /// token transfer: transfer requested token from RewardPool to recipient
    /// @param token address The address of the token to rescue
    /// @param recipient address The address of the recipient
    /// @param amount uint256 The amount of tokens to rescue
    function rescueTokensFromRewardPool(
        address token,
        address recipient,
        uint256 amount
    ) external {
        _admin();
        // verify recipient
        require(isValidAddress(recipient), "invalid recipient");
        // transfer tokens to recipient
        IRewardPool(rewardPool).sendERC20(token, recipient, amount);
    }

    /// @notice Add vault factory to whitelist
    /// @dev use this function to enable stakes to vaults coming from the specified factory contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - append to _vaultFactorySet
    /// token transfer: none
    /// @param factory address The address of the vault factory
    function registerVaultFactory(address factory) external {
        _admin();
        // add factory to set
        require(_vaultFactorySet.add(factory), "ArbiStaker: vault factory already registered");

        // emit event
        emit VaultFactoryRegistered(factory);
    }

    /// @notice Remove vault factory from whitelist
    /// @dev use this function to disable new stakes to vaults coming from the specified factory contract.
    ///      note: vaults with existing stakes from this factory are sill able to unstake
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - remove from _vaultFactorySet
    /// token transfer: none
    /// @param factory address The address of the vault factory
    function removeVaultFactory(address factory) external {
        _admin();
        // remove factory from set
        require(_vaultFactorySet.remove(factory), "ArbiStaker: vault factory not registered");

        // emit event
        emit VaultFactoryRemoved(factory);
    }

    /// @notice Register bonus token for distribution
    /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    /// state scope:
    ///   - append to _bonusTokenSet
    /// token transfer: none
    /// @param bonusToken address The address of the bonus token
    function registerBonusToken(address bonusToken) external {
        _admin();
        // verify valid bonus token
        require(isValidAddress(bonusToken), "invalid bonus token address or is already present");

        // verify bonus token count
        require(
            _bonusTokenSet.length() < MAX_BONUS_TOKENS,
            "ArbiStaker: max bonus tokens reached "
        );

        // add token to set
        _bonusTokenSet.add(bonusToken);

        // emit event
        emit BonusTokenRegistered(bonusToken);
    }

    /// @notice Remove bonus token
    /// @dev use this function to disable distribution of a token held by the RewardPool contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - remove from _bonusTokenSet
    /// token transfer: none
    /// @param bonusToken address The address of the bonus token
    function removeBonusToken(address bonusToken) external {
        _admin();
        require(_bonusTokenSet.remove(bonusToken), "ArbiStaker: bonus token not present ");

        // emit event
        emit BonusTokenRemoved(bonusToken);
    }

    function addRewardCalcTemplate(string calldata name, address template) external {
        _admin();
        require(rewardCalcTemplates[name] == address(0), "Template already exists");
        rewardCalcTemplates[name] = template;
        if (rewardCalcTemplateNames.length == 0) {
            activeRewardCalcTemplate = name;
            emit RewardCalcTemplateActive(name, template);
        }
        rewardCalcTemplateNames.push(name);
        emit RewardCalcTemplateAdded(name, template);
    }

    function setRewardCalcActiveTemplate(string calldata name) external {
        _admin();
        require(rewardCalcTemplates[name] != address(0), "Template does not exist");
        activeRewardCalcTemplate = name;
        emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]);
    }

    function startLMRewards(
        address token,
        uint256 amount,
        uint256 duration
    ) external {
        startLMRewardsToken(token, amount, duration, activeRewardCalcTemplate);
    }

    function startLMRewardsToken(
        address token,
        uint256 amount,
        uint256 duration,
        string memory rewardCalcTemplateName
    ) public {
        _admin();
        require(lmRewards[token].startedAt == 0, "A reward program already live for this token");
        require(
            rewardCalcTemplates[rewardCalcTemplateName] != address(0),
            "Reward Calculator Template does not exist"
        );
        // create reward calc clone from template
        address rewardCalcInstance =
            ProxyFactory._create(
                rewardCalcTemplates[rewardCalcTemplateName],
                abi.encodeWithSelector(IERC2917.initialize.selector)
            );
        LMRewardData storage lmrd = lmRewards[token];
        lmrd.amount = amount;
        lmrd.duration = duration;
        lmrd.startedAt = block.timestamp;
        lmrd.rewardCalcInstance = rewardCalcInstance;
    }

    function setImplementorForRewardsCalculator(address token, address newImplementor) public {
        _admin();
        require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
        address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
        IERC2917(rewardCalcInstance).setImplementor(newImplementor);
    }

    function setLMRewardsPerBlock(address token, uint256 value) public onlyOnline {
        _admin();
        require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
        address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
        IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value);
    }

    function addBonusTokenToLMRewards(
        address lmToken,
        address bonusToken,
        uint256 bonusTokenAmount
    ) public {
        _admin();
        require(
            lmRewards[lmToken].startedAt != 0,
            "No reward program currently live for this LM token"
        );
        require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered");
        lmRewards[lmToken].bonusTokens.add(bonusToken);
        lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[
            bonusToken
        ]
            .add(bonusTokenAmount);
    }

    function endLMRewards(address token, bool removeBonusTokenData) public {
        _admin();
        lmRewards[token].amount = 0;
        lmRewards[token].duration = 0;
        lmRewards[token].startedAt = 0;
        lmRewards[token].rewardCalcInstance = address(0);
        if (removeBonusTokenData) {
            for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
                address bonusToken = lmRewards[token].bonusTokens.at(index);
                lmRewards[token].bonusTokens.remove(bonusToken);
                delete lmRewards[token].bonusTokenAmounts[bonusToken];
            }
        }
    }

    function setMaxStakesPerVault(uint256 amount) external {
        _admin();
        MAX_TOKENS_STAKED_PER_VAULT = amount;
    }

    function setMaxBonusTokens(uint256 amount) external {
        _admin();
        MAX_BONUS_TOKENS = amount;
    }

    function setPionnerLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        PIONNER_LM_REWARD_MULTIPLIER_NUM = numerator;
        PIONNER_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setEarlyAdopterLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        PRECURSOR_LM_REWARD_MULTIPLIER_NUM = numerator;
        PRECURSOR_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setPrecursorLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        INNOVATOR_LM_REWARD_MULTIPLIER_NUM = numerator;
        INNOVATOR_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setInnovatorLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM = numerator;
        EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setStandardLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        STANDARD_LM_REWARD_MULTIPLIER_NUM = numerator;
        STANDARD_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setLMRewardVestingPeriod(uint256 amount) external {
        _admin();
        LM_REWARD_VESTING_PERIOD = amount;
    }

    function setLMRewardVestingPortion(uint256 numerator, uint256 denominator) external {
        _admin();
        LM_REWARD_VESTING_PORTION_NUM = numerator;
        LM_REWARD_VESTING_PORTION_DENOM = denominator;
    }

    /* getter functions */

    function getBonusTokenSetLength() external view override returns (uint256 length) {
        return _bonusTokenSet.length();
    }

    function getBonusTokenAtIndex(uint256 index)
        external
        view
        override
        returns (address bonusToken)
    {
        return _bonusTokenSet.at(index);
    }

    function getVaultFactorySetLength() external view override returns (uint256 length) {
        return _vaultFactorySet.length();
    }

    function getVaultFactoryAtIndex(uint256 index)
        external
        view
        override
        returns (address factory)
    {
        return _vaultFactorySet.at(index);
    }

    function getNumVaults() external view override returns (uint256 num) {
        return _vaultSet.length();
    }

    function getVaultAt(uint256 index) external view override returns (address vault) {
        return _vaultSet.at(index);
    }

    function getNumTokensStaked() external view override returns (uint256 num) {
        return _allStakedTokens.length();
    }

    function getTokenStakedAt(uint256 index) external view override returns (address token) {
        return _allStakedTokens.at(index);
    }

    function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) {
        return _vaults[vault].tokens.length();
    }

    function getVaultTokenAtIndex(address vault, uint256 index)
        external
        view
        override
        returns (address vaultToken)
    {
        return _vaults[vault].tokens.at(index);
    }

    function getVaultTokenStake(address vault, address token)
        external
        view
        override
        returns (uint256 tokenStake)
    {
        return _vaults[vault].tokenStake[token];
    }

    function getNftTier(uint256 nftId, address nftFactory)
        public
        view
        returns (string memory tier)
    {
        uint256 serialNumber = ArbiVaultFactory(nftFactory).tokenIdToSerialNumber(nftId);
        if (serialNumber >= 1 && serialNumber <= 10) {
            tier = PIONNER;
        } else if (serialNumber >= 11 && serialNumber <= 100) {
            tier = PRECURSOR;
        } else if (serialNumber >= 101 && serialNumber <= 500) {
            tier = INNOVATOR;
        } else if (serialNumber >= 501 && serialNumber <= 1000) {
            tier = EARLY_ADOPTER;
        } else if (serialNumber >= 1001) {
            tier = STANDARD;
        }
    }

    function getNftsOfOwner(address owner, address nftFactory)
        public
        view
        returns (uint256[] memory nftIds)
    {
        uint256 balance = ArbiVaultFactory(nftFactory).balanceOf(owner);
        nftIds = new uint256[](balance);
        for (uint256 index = 0; index < balance; index++) {
            uint256 nftId = ArbiVaultFactory(nftFactory).tokenOfOwnerByIndex(owner, index);
            nftIds[index] = nftId;
        }
    }

    function getLMRewardData(address token)
        external
        view
        override
        returns (
            uint256 amount,
            uint256 duration,
            uint256 startedAt,
            address rewardCalcInstance
        )
    {
        return (
            lmRewards[token].amount,
            lmRewards[token].duration,
            lmRewards[token].startedAt,
            lmRewards[token].rewardCalcInstance
        );
    }

    function getLMRewardBonusTokensLength(address token)
        external
        view
        override
        returns (uint256 length)
    {
        return lmRewards[token].bonusTokens.length();
    }

    function getLMRewardBonusTokenAt(address token, uint256 index)
        external
        view
        override
        returns (address bonusToken, uint256 bonusTokenAmount)
    {
        return (
            lmRewards[token].bonusTokens.at(index),
            lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]
        );
    }

    function getNumVestingLMTokenRewards(address user)
        external
        view
        override
        returns (uint256 num)
    {
        return vestingLMTokenRewards[user].length();
    }

    function getVestingLMTokenAt(address user, uint256 index)
        external
        view
        override
        returns (address token)
    {
        return vestingLMTokenRewards[user].at(index);
    }

    function getNumVests(address user, address token) external view override returns (uint256 num) {
        return vestingLMRewards[user][token].length;
    }

    function getLMRewardVestingData(
        address user,
        address token,
        uint256 index
    ) external view override returns (uint256 amount, uint256 startedAt) {
        return (
            vestingLMRewards[user][token][index].amount,
            vestingLMRewards[user][token][index].startedAt
        );
    }

    function getNumRewardCalcTemplates() external view override returns (uint256 num) {
        return rewardCalcTemplateNames.length;
    }

    /* helper functions */

    function isValidVault(address vault, address factory)
        public
        view
        override
        returns (bool validity)
    {
        // validate vault is created from whitelisted vault factory and is an instance of that factory
        return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault);
    }

    function isValidAddress(address target) public view override returns (bool validity) {
        // sanity check target for potential input errors
        return
            target != address(this) &&
            target != address(0) &&
            target != rewardToken &&
            target != rewardPool &&
            !_bonusTokenSet.contains(target);
    }

    function _tierMultipliedReward(
        uint256 nftId,
        address nftFactory,
        uint256 reward
    ) private view returns (uint256 multipliedReward) {
        // get tier
        string memory tier = getNftTier(nftId, nftFactory);
        bytes32 tierHash = keccak256(abi.encodePacked(tier));

        if (tierHash == keccak256(abi.encodePacked(PIONNER))) {
            multipliedReward = reward.mul(PIONNER_LM_REWARD_MULTIPLIER_NUM).div(
                PIONNER_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(PRECURSOR))) {
            multipliedReward = reward.mul(PRECURSOR_LM_REWARD_MULTIPLIER_NUM).div(
                PRECURSOR_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(INNOVATOR))) {
            multipliedReward = reward.mul(INNOVATOR_LM_REWARD_MULTIPLIER_NUM).div(
                INNOVATOR_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(EARLY_ADOPTER))) {
            multipliedReward = reward.mul(EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM).div(
                EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(STANDARD))) {
            multipliedReward = reward.mul(STANDARD_LM_REWARD_MULTIPLIER_NUM).div(
                STANDARD_LM_REWARD_MULTIPLIER_DENOM
            );
        }
    }

    /* user functions */

    /// @notice Exit ArbiStaker without claiming reward
    /// @dev This function should never revert when correctly called by the vault.
    ///      A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to
    ///      place an upper bound on the for loop.
    /// access control: callable by anyone but fails if caller is not an approved vault
    /// state machine:
    ///   - when vault exists on this ArbiStaker
    ///   - when active stake from this vault
    ///   - any power state
    /// state scope:
    ///   - decrease stakedTokenTotal[token], delete if 0
    ///   - delete _vaults[vault].tokenStake[token]
    ///   - remove _vaults[vault].tokens.remove(token)
    ///   - delete _vaults[vault]
    ///   - remove vault from _vaultSet
    ///   - remove token from _allStakedTokens if required
    /// token transfer: none
    function rageQuit() external override {
        require(_vaultSet.contains(msg.sender), "ArbiStakerERC20: no vault");
        //fetch vault storage reference
        VaultData storage vaultData = _vaults[msg.sender];
        // revert if no active tokens staked
        EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens;
        require(vaultTokens.length() > 0, "ArbiStakerERC20: no stake");

        // update totals
        for (uint256 index = 0; index < vaultTokens.length(); index++) {
            address token = vaultTokens.at(index);
            vaultTokens.remove(token);
            uint256 amount = vaultData.tokenStake[token];
            uint256 newTotal = stakedTokenTotal[token].sub(amount);
            assert(newTotal >= 0);
            if (newTotal == 0) {
                _allStakedTokens.remove(token);
                delete stakedTokenTotal[token];
            } else {
                stakedTokenTotal[token] = newTotal;
            }
            delete vaultData.tokenStake[token];
        }

        // delete vault data
        _vaultSet.remove(msg.sender);
        delete _vaults[msg.sender];

        // emit event
        emit RageQuit(msg.sender);
    }

    /// @notice Stake ERC20 tokens
    /// @dev anyone can stake to any vault if they have valid permission
    /// access control: anyone
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    ///   - when vault exists on this ArbiStaker
    /// state scope:
    ///   - add token to _vaults[vault].tokens if not already exists
    ///   - increase _vaults[vault].tokenStake[token]
    ///   - add vault to _vaultSet if not already exists
    ///   - add token to _allStakedTokens if not already exists
    ///   - increase stakedTokenTotal[token]
    /// token transfer: transfer staking tokens from msg.sender to vault
    /// @param vault address The address of the vault to stake to
    /// @param vaultFactory address The address of the vault factory which created the vault
    /// @param token address The address of the token being staked
    /// @param amount uint256 The amount of tokens to stake
    function stakeERC20(
        address vault,
        address vaultFactory,
        address token,
        uint256 amount,
        bytes calldata permission
    ) external override onlyOnline {
        // verify vault is valid
        require(isValidVault(vault, vaultFactory), "ArbiStakerERC20: vault is not valid");
        // verify non-zero amount
        require(amount != 0, "ArbiStakerERC20: no amount staked");
        // check sender balance
        require(IERC20(token).balanceOf(msg.sender) >= amount, "insufficient token balance");

        // add vault to set
        _vaultSet.add(vault);
        // fetch vault storage reference
        VaultData storage vaultData = _vaults[vault];

        // verify stakes boundary not reached
        require(
            vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT,
            "ArbiStakerERC20: MAX_TOKENS_STAKED_PER_VAULT reached"
        );

        // add token to set and increase amount
        vaultData.tokens.add(token);
        vaultData.tokenStake[token] = vaultData.tokenStake[token].add(amount);

        // update total token staked
        _allStakedTokens.add(token);
        stakedTokenTotal[token] = stakedTokenTotal[token].add(amount);

        // perform transfer
        TransferHelper.safeTransferFrom(token, msg.sender, vault, amount);
        // call lock on vault
        IUniversalVault(vault).lockERC20(token, amount, permission);

        // check if there is a reward program currently running
        if (lmRewards[token].startedAt != 0) {
            address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
            (, uint256 rewardEarned, ) =
                IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, amount);
            earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(
                rewardEarned
            );
        }

        // emit event
        emit Staked(vault, amount);
    }

    /// @notice Unstake ERC20 tokens and claim reward
    /// @dev LM rewards can only be claimed when unstaking
    /// access control: anyone with permission
    /// state machine:
    ///   - when vault exists on this ArbiStakerERC20
    ///   - after stake from vault
    ///   - can be called multiple times while sufficient stake remains
    ///   - only online
    /// state scope:
    ///   - decrease _vaults[vault].tokenStake[token]
    ///   - delete token from _vaults[vault].tokens if token stake is 0
    ///   - decrease stakedTokenTotal[token]
    ///   - delete token from _allStakedTokens if total token stake is 0
    /// token transfer:
    ///   - transfer reward tokens from reward pool to recipient
    ///   - transfer bonus tokens from reward pool to recipient
    /// @param vault address The vault to unstake from
    /// @param vaultFactory address The vault factory that created this vault
    /// @param recipient address The recipient to send reward to
    /// @param token address The staking token
    /// @param amount uint256 The amount of staking tokens to unstake
    /// @param claimBonusReward bool flag to claim bonus rewards
    function unstakeERC20AndClaim(
        address vault,
        address vaultFactory,
        address recipient,
        address token,
        uint256 amount,
        bool claimBonusReward,
        bytes calldata permission
    ) external override onlyOnline {
        require(_vaultSet.contains(vault), "ArbiStakerERC20: no vault");
        // fetch vault storage reference
        VaultData storage vaultData = _vaults[vault];
        // verify non-zero amount
        require(amount != 0, "ArbiStakerERC20: no amount unstaked");
        // validate recipient
        require(isValidAddress(recipient), "ArbiStakerERC20: invalid recipient");
        // check for sufficient vault stake amount
        require(vaultData.tokens.contains(token), "ArbiStakerERC20: no token in vault");
        // check for sufficient vault stake amount
        require(
            vaultData.tokenStake[token] >= amount,
            "ArbiStakerERC20: insufficient vault token stake"
        );
        // check for sufficient total token stake amount
        // if the above check succeeds and this check fails, there is a bug in stake accounting
        require(
            stakedTokenTotal[token] >= amount,
            "stakedTokenTotal[token] is less than amount being unstaked"
        );

        // check if there is a reward program currently running
        uint256 rewardEarned = earnedLMRewards[msg.sender][token];
        if (lmRewards[token].startedAt != 0) {
            address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
            (, uint256 newReward, ) =
                IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, amount);
            rewardEarned = rewardEarned.add(newReward);
        }

        // decrease vaultTokenStake of token in this vault
        vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(amount);
        if (vaultData.tokenStake[token] == 0) {
            vaultData.tokens.remove(token);
            delete vaultData.tokenStake[token];
        }

        // decrease stakedTokenTotal across all vaults
        stakedTokenTotal[token] = stakedTokenTotal[token].sub(amount);
        if (stakedTokenTotal[token] == 0) {
            _allStakedTokens.remove(token);
            delete stakedTokenTotal[token];
        }

        // unlock staking tokens from vault
        IUniversalVault(vault).unlockERC20(token, amount, permission);

        // emit event
        emit Unstaked(vault, amount);

        // only perform on non-zero reward
        if (rewardEarned > 0) {
            // transfer bonus tokens from reward pool to recipient
            // bonus tokens can only be claimed during an active rewards program
            if (claimBonusReward && lmRewards[token].startedAt != 0) {
                for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
                    // fetch bonus token address reference
                    address bonusToken = lmRewards[token].bonusTokens.at(index);
                    // calculate bonus token amount
                    // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward
                    uint256 bonusAmount =
                        rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(
                            lmRewards[token].amount
                        );
                    // transfer bonus token
                    IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
                    // emit event
                    emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
                }
            }
            // take care of multiplier
            uint256 multipliedReward =
                _tierMultipliedReward(uint256(vault), vaultFactory, rewardEarned);
            // take care of vesting
            uint256 vestingPortion =
                multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(
                    LM_REWARD_VESTING_PORTION_DENOM
                );
            vestingLMRewards[msg.sender][token].push(
                LMRewardVestingData(vestingPortion, block.timestamp)
            );
            vestingLMTokenRewards[msg.sender].add(token);
            // set earned reward to 0
            earnedLMRewards[msg.sender][token] = 0;
            // transfer reward tokens from reward pool to recipient
            IRewardPool(rewardPool).sendERC20(
                rewardToken,
                recipient,
                multipliedReward.sub(vestingPortion)
            );
            // emit event
            emit RewardClaimed(vault, recipient, rewardToken, rewardEarned);
        }
    }

    function claimVestedRewardAll() external override onlyOnline {
        uint256 numTokens = vestingLMTokenRewards[msg.sender].length();
        for (uint256 index = 0; index < numTokens; index++) {
            address token = vestingLMTokenRewards[msg.sender].at(index);
            claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
        }
    }

    function claimVestedRewardToken(address token) external override onlyOnline {
        claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
    }

    function claimVestedReward(address token, uint256 numVests) public onlyOnline {
        require(
            numVests <= vestingLMRewards[msg.sender][token].length,
            "num vests can't be greater than available vests"
        );
        LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token];
        uint256 vestedReward;
        for (uint256 index = 0; index < numVests; index++) {
            LMRewardVestingData storage vest = vests[index];
            uint256 duration = block.timestamp.sub(vest.startedAt);
            uint256 vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD);
            if (vested >= vest.amount) {
                // completely vested
                vested = vest.amount;
                // copy last element into this slot and pop last
                vests[index] = vests[vests.length - 1];
                vests.pop();
                index--;
                numVests--;
                // if all vested remove from set
                if (vests.length == 0) {
                    vestingLMTokenRewards[msg.sender].remove(token);
                    break;
                }
            } else {
                vest.amount = vest.amount.sub(vested);
            }
            vestedReward = vestedReward.add(vested);
        }
        if (vestedReward > 0) {
            // transfer reward tokens from reward pool to recipient
            IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward);
            // emit event
            emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward);
        }
    }
}

File 2 of 33 : SafeMath.sol
// SPDX-License-Identifier: MIT

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 3 of 33 : EnumerableSet.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }


    // 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 4 of 33 : IERC20.sol
// SPDX-License-Identifier: MIT

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 5 of 33 : TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeApprove: approve failed'
        );
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeTransfer: transfer failed'
        );
    }

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::transferFrom: transferFrom failed'
        );
    }

    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
    }
}

File 6 of 33 : IFactory.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

interface IFactory {
    function create(bytes calldata args) external returns (address instance);

    function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}

File 7 of 33 : InstanceRegistry.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";

interface IInstanceRegistry {
    /* events */

    event InstanceAdded(address instance);
    event InstanceRemoved(address instance);

    /* view functions */

    function isInstance(address instance) external view returns (bool validity);

    function instanceCount() external view returns (uint256 count);

    function instanceAt(uint256 index) external view returns (address instance);
}

/// @title InstanceRegistry
contract InstanceRegistry is IInstanceRegistry {
    using EnumerableSet for EnumerableSet.AddressSet;

    /* storage */

    EnumerableSet.AddressSet private _instanceSet;

    /* view functions */

    function isInstance(address instance) external view override returns (bool validity) {
        return _instanceSet.contains(instance);
    }

    function instanceCount() external view override returns (uint256 count) {
        return _instanceSet.length();
    }

    function instanceAt(uint256 index) external view override returns (address instance) {
        return _instanceSet.at(index);
    }

    /* admin functions */

    function _register(address instance) internal {
        require(_instanceSet.add(instance), "InstanceRegistry: already registered");
        emit InstanceAdded(instance);
    }
}

File 8 of 33 : ArbiVault.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";

import {EIP712} from "./EIP712.sol";
import {ERC1271} from "./ERC1271.sol";
import {OwnableERC721} from "./OwnableERC721.sol";
import {IRageQuit} from "../arbiStaker/ArbiStakerERC721.sol";

interface IUniversalVault {
    /* user events */

    event LockedERC20(address delegate, address token, uint256 amount);
    event UnlockedERC20(address delegate, address token, uint256 amount);
    event LockedERC721(address delegate, address token, uint256 tokenId);
    event UnlockedERC721(address delegate, address token, uint256 tokenId);
    event RageQuit(address delegate, address token, bool notified, string reason);

    /* data types */

    struct LockData {
        address delegate;
        address token;
        uint256 balance;
    }

    /* initialize function */

    function initialize() external;

    /* user functions */

    function lockERC20(
        address token,
        uint256 amount,
        bytes calldata permission
    ) external;

    function unlockERC20(
        address token,
        uint256 amount,
        bytes calldata permission
    ) external;

    function lockERC721(
        address token,
        uint256 tokenId,
        bytes calldata permission
    ) external;

    function unlockERC721(
        address token,
        uint256 tokenId,
        bytes calldata permission
    ) external;

    function rageQuit(address delegate, address token)
        external
        returns (bool notified, string memory error);

    function transferERC20(
        address token,
        address to,
        uint256 amount
    ) external;

    function transferERC721(
        address token,
        address to,
        uint256 tokenId
    ) external;

    function transferETH(address to, uint256 amount) external payable;

    /* pure functions */

    function calculateLockID(address delegate, address token)
        external
        pure
        returns (bytes32 lockID);

    /* getter functions */

    function getPermissionHash(
        bytes32 eip712TypeHash,
        address delegate,
        address token,
        uint256 amount,
        uint256 nonce
    ) external view returns (bytes32 permissionHash);

    function getPermissionHashERC721(
        bytes32 eip712TypeHash,
        address delegate,
        address token,
        uint256 tokenId,
        uint256 nonce
    ) external view returns (bytes32 permissionHash);

    function getNonce() external view returns (uint256 nonce);

    function owner() external view returns (address ownerAddress);

    function getLockSetCount() external view returns (uint256 count);

    function getLockAt(uint256 index) external view returns (LockData memory lockData);

    function getLockSetAt(uint256 index) external view returns (bytes32 lockId);

    function getBalanceDelegated(address token, address delegate)
        external
        view
        returns (uint256 balance);

    function getBalanceLocked(address token) external view returns (uint256 balance);

    function checkBalances() external view returns (bool validity);

    function checkERC20Balances() external view returns (bool validity);

    function checkERC721Balances() external view returns (bool validity);
}

/// @title ArbiVault
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
contract ArbiVault is
    IUniversalVault,
    EIP712("UniversalVault", "1.0.0"),
    ERC1271,
    OwnableERC721,
    Initializable,
    IERC721Receiver
{
    using SafeMath for uint256;
    using Address for address;
    using Address for address payable;
    using EnumerableSet for EnumerableSet.Bytes32Set;

    /* constant */

    // Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
    // the gas requirement cannot be determined at runtime by querying the delegate
    // as it could potentially be manipulated by a malicious delegate who could force
    // the calls to revert.
    // The gas limit could alternatively be set upon vault initialization or creation
    // of a lock, but the gas consumption trade-offs are not favorable.
    // Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
    // an error code that allows for reliably catching out-of-gas errors on remote calls.
    uint256 public constant RAGEQUIT_GAS = 500000;
    bytes32 public constant LOCK_TYPEHASH =
        keccak256("LockERC20(address delegate,address token,uint256 amount,uint256 nonce)");
    bytes32 public constant UNLOCK_TYPEHASH =
        keccak256("UnlockERC20(address delegate,address token,uint256 amount,uint256 nonce)");
    bytes32 public constant LOCK_ERC721_TYPEHASH =
        keccak256("LockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)");
    bytes32 public constant UNLOCK_ERC721_TYPEHASH =
        keccak256("UnlockERC721(address delegate,address token,uint256 tokenId,uint256 nonce)");
    string public constant VERSION = "1.0.0";

    /* storage */

    uint256 private _nonce;
    // nft type to id mapping
    mapping(address => mapping(uint256 => bool)) public lockedERC721s;

    mapping(bytes32 => LockData) private _locks;
    EnumerableSet.Bytes32Set private _lockSet;

    /* initialization function */

    function initializeLock() external initializer {}

    function initialize() external override initializer {
        OwnableERC721._setNFT(msg.sender);
    }

    /* ether receive */

    receive() external payable {}

    /* internal overrides */

    function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
        return OwnableERC721.owner();
    }

    /* overrides */

    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external override returns (bytes4) {
        return IERC721Receiver(0).onERC721Received.selector;
    }

    /* pure functions */

    function calculateLockID(address delegate, address token)
        public
        pure
        override
        returns (bytes32 lockID)
    {
        return keccak256(abi.encodePacked(delegate, token));
    }

    /* getter functions */

    function getPermissionHash(
        bytes32 eip712TypeHash,
        address delegate,
        address token,
        uint256 amount,
        uint256 nonce
    ) public view override returns (bytes32 permissionHash) {
        return
            EIP712._hashTypedDataV4(
                keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
            );
    }

    function getPermissionHashERC721(
        bytes32 eip712TypeHash,
        address delegate,
        address token,
        uint256 tokenId,
        uint256 nonce
    ) public view override returns (bytes32 permissionHash) {
        return
            EIP712._hashTypedDataV4(
                keccak256(abi.encode(eip712TypeHash, delegate, token, tokenId, nonce))
            );
    }

    function getNonce() external view override returns (uint256 nonce) {
        return _nonce;
    }

    function owner()
        public
        view
        override(IUniversalVault, OwnableERC721)
        returns (address ownerAddress)
    {
        return OwnableERC721.owner();
    }

    function getLockSetCount() external view override returns (uint256 count) {
        return _lockSet.length();
    }

    function getLockSetAt(uint256 index) external view override returns (bytes32 lockId) {
        return _lockSet.at(index);
    }

    function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
        return _locks[_lockSet.at(index)];
    }

    function getBalanceDelegated(address token, address delegate)
        external
        view
        override
        returns (uint256 balance)
    {
        return _locks[calculateLockID(delegate, token)].balance;
    }

    function getBalanceLocked(address token) public view override returns (uint256 balance) {
        uint256 count = _lockSet.length();
        for (uint256 index; index < count; index++) {
            LockData storage _lockData = _locks[_lockSet.at(index)];
            if (_lockData.token == token && _lockData.balance > balance)
                balance = _lockData.balance;
        }
        return balance;
    }

    function checkBalances() external view override returns (bool validity) {
        // iterate over all token locks and validate sufficient balance
        uint256 count = _lockSet.length();
        for (uint256 index; index < count; index++) {
            // fetch storage lock reference
            LockData storage _lockData = _locks[_lockSet.at(index)];
            // if insufficient balance and no∏t shutdown, return false
            if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
        }
        // if sufficient balance or shutdown, return true
        return true;
    }

    function checkERC20Balances() external view override returns (bool validity) {
        // iterate over all token locks and validate sufficient balance
        uint256 count = _lockSet.length();
        for (uint256 index; index < count; index++) {
            // fetch storage lock reference
            LockData storage _lockData = _locks[_lockSet.at(index)];
            // if insufficient balance return false
            if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
        }
        // if sufficient balance return true
        return true;
    }

    function checkERC721Balances() external view override returns (bool validity) {
        // iterate over all token locks and validate sufficient balance
        uint256 count = _lockSet.length();
        for (uint256 index; index < count; index++) {
            // fetch storage lock reference
            LockData storage _lockData = _locks[_lockSet.at(index)];
            // if insufficient balance return false
            if (IERC721(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
        }
        // if sufficient balance return true
        return true;
    }

    /* user functions */

    /// @notice Lock ERC20 tokens in the vault
    /// access control: called by delegate with signed permission from owner
    /// state machine: anytime
    /// state scope:
    /// - insert or update _locks
    /// - increase _nonce
    /// token transfer: none
    /// @param token Address of token being locked
    /// @param amount Amount of tokens being locked
    /// @param permission Permission signature payload
    function lockERC20(
        address token,
        uint256 amount,
        bytes calldata permission
    )
        external
        override
        onlyValidSignature(
            getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),
            permission
        )
    {
        // get lock id
        bytes32 lockID = calculateLockID(msg.sender, token);

        // add lock to storage
        if (_lockSet.contains(lockID)) {
            // if lock already exists, increase amount
            _locks[lockID].balance = _locks[lockID].balance.add(amount);
        } else {
            // if does not exist, create new lock
            // add lock to set
            assert(_lockSet.add(lockID));
            // add lock data to storage
            _locks[lockID] = LockData(msg.sender, token, amount);
        }

        // validate sufficient balance
        require(
            IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
            "UniversalVault: insufficient balance"
        );

        // increase nonce
        _nonce += 1;

        // emit event
        emit LockedERC20(msg.sender, token, amount);
    }

    /// @notice Lock ERC721 tokens in the vault
    /// access control: called by delegate with signed permission from owner
    /// state machine: anytime
    /// state scope:
    /// - insert or update _locks
    /// - increase _nonce
    /// token transfer: none
    /// @param token Address of token being locked
    /// @param tokenId TokenId of ERC721 token
    /// @param permission Permission signature payload
    function lockERC721(
        address token,
        uint256 tokenId,
        bytes calldata permission
    )
        external
        override
        onlyValidSignature(
            getPermissionHashERC721(LOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce),
            permission
        )
    {
        // sanity check, can't lock self
        require(address(tokenId) != address(this), "can't self lock");

        // validate ownership
        require(
            IERC721(token).ownerOf(tokenId) == address(this),
            "UniversalVault: vault not owner of nft"
        );

        require(lockedERC721s[token][tokenId] == false, "NFT already locked");

        lockedERC721s[token][tokenId] = true;

        // get lock id
        bytes32 lockID = calculateLockID(msg.sender, token);

        // add lock to storage
        if (_lockSet.contains(lockID)) {
            // if lock already exists, increase amount by 1
            _locks[lockID].balance = _locks[lockID].balance.add(1);
        } else {
            // if does not exist, create new lock
            // add lock to set
            assert(_lockSet.add(lockID));
            // add lock data to storage
            _locks[lockID] = LockData(msg.sender, token, 1);
        }

        // increase nonce
        _nonce += 1;

        // emit event
        emit LockedERC721(msg.sender, token, tokenId);
    }

    /// @notice Unlock ERC20 tokens in the vault
    /// access control: called by delegate with signed permission from owner
    /// state machine: after valid lock from delegate
    /// state scope:
    /// - remove or update _locks
    /// - increase _nonce
    /// token transfer: none
    /// @param token Address of token being unlocked
    /// @param amount Amount of tokens being unlocked
    /// @param permission Permission signature payload
    function unlockERC20(
        address token,
        uint256 amount,
        bytes calldata permission
    )
        external
        override
        onlyValidSignature(
            getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),
            permission
        )
    {
        // get lock id
        bytes32 lockID = calculateLockID(msg.sender, token);

        // validate existing lock
        require(_lockSet.contains(lockID), "UniversalVault: missing lock");

        // update lock data
        if (_locks[lockID].balance > amount) {
            // substract amount from lock balance
            _locks[lockID].balance = _locks[lockID].balance.sub(amount);
        } else {
            // delete lock data
            delete _locks[lockID];
            assert(_lockSet.remove(lockID));
        }

        // increase nonce
        _nonce += 1;

        // emit event
        emit UnlockedERC20(msg.sender, token, amount);
    }

    /// @notice Unlock ERC721 tokens in the vault
    /// access control: called by delegate with signed permission from owner
    /// state machine: after valid lock from delegate
    /// state scope:
    /// - remove or update _locks
    /// - increase _nonce
    /// token transfer: none
    /// @param token Address of token being unlocked
    /// @param tokenId TokenId of ERC721 token
    /// @param permission Permission signature payload
    function unlockERC721(
        address token,
        uint256 tokenId,
        bytes calldata permission
    )
        external
        override
        onlyValidSignature(
            getPermissionHashERC721(UNLOCK_ERC721_TYPEHASH, msg.sender, token, tokenId, _nonce),
            permission
        )
    {
        // validate ownership
        require(
            IERC721(token).ownerOf(tokenId) == address(this),
            "UniversalVault: vault not owner of nft"
        );

        require(lockedERC721s[token][tokenId] == true, "NFT not locked");

        lockedERC721s[token][tokenId] = false;

        // get lock id
        bytes32 lockID = calculateLockID(msg.sender, token);

        // validate existing lock
        require(_lockSet.contains(lockID), "UniversalVault: missing lock");

        // update lock data
        if (_locks[lockID].balance > 1) {
            // subtract 1 from lock balance
            _locks[lockID].balance = _locks[lockID].balance.sub(1);
        } else {
            // delete lock data
            delete _locks[lockID];
            assert(_lockSet.remove(lockID));
        }

        // increase nonce
        _nonce += 1;

        // emit event
        emit UnlockedERC721(msg.sender, token, tokenId);
    }

    /// @notice Forcibly cancel delegate lock
    /// @dev This function will attempt to notify the delegate of the rage quit using
    ///      a fixed amount of gas.
    /// access control: only owner
    /// state machine: after valid lock from delegate
    /// state scope:
    /// - remove item from _locks
    /// token transfer: none
    /// @param delegate Address of delegate
    /// @param token Address of token being unlocked
    function rageQuit(address delegate, address token)
        external
        override
        onlyOwner
        returns (bool notified, string memory error)
    {
        // get lock id
        bytes32 lockID = calculateLockID(delegate, token);

        // validate existing lock
        require(_lockSet.contains(lockID), "UniversalVault: missing lock");

        // attempt to notify delegate
        if (delegate.isContract()) {
            // check for sufficient gas
            require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas");

            // attempt rageQuit notification
            try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
                notified = true;
            } catch Error(string memory res) {
                notified = false;
                error = res;
            } catch (bytes memory) {
                notified = false;
            }
        }

        // update lock storage
        assert(_lockSet.remove(lockID));
        delete _locks[lockID];

        // emit event
        emit RageQuit(delegate, token, notified, error);
    }

    /// @notice Transfer ERC20 tokens out of vault
    /// access control: only owner
    /// state machine: when balance >= max(lock) + amount
    /// state scope: none
    /// token transfer: transfer any token
    /// @param token Address of token being transferred
    /// @param to Address of the recipient
    /// @param amount Amount of tokens to transfer
    function transferERC20(
        address token,
        address to,
        uint256 amount
    ) external override onlyOwner {
        // check for sufficient balance
        require(
            IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
            "UniversalVault: insufficient balance"
        );
        // perform transfer
        TransferHelper.safeTransfer(token, to, amount);
    }

    /// @notice Transfer ERC721 tokens out of vault
    /// access control: only owner
    /// state machine: when the owner of vault
    /// state scope: none
    /// token transfer: transfer any token
    /// @param token Address of token being transferred
    /// @param to Address of the recipient
    /// @param tokenId TokenId of token to transfer
    function transferERC721(
        address token,
        address to,
        uint256 tokenId
    ) external override onlyOwner {
        // validate ownership
        require(
            IERC721(token).ownerOf(tokenId) == address(this),
            "UniversalVault: vault not owner of nft"
        );
        // perform transfer
        IERC721(token).safeTransferFrom(address(this), to, tokenId);
    }

    /// @notice Transfer ERC20 tokens out of vault
    /// access control: only owner
    /// state machine: when balance >= amount
    /// state scope: none
    /// token transfer: transfer any token
    /// @param to Address of the recipient
    /// @param amount Amount of ETH to transfer
    function transferETH(address to, uint256 amount) external payable override onlyOwner {
        // perform transfer
        TransferHelper.safeTransferETH(to, amount);
    }
}

File 9 of 33 : ArbiVaultFactory.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";

import {IUniversalVault} from "./ArbiVault.sol";

/// @title ArbiVaultFactory
contract ArbiVaultFactory is Ownable, IFactory, IInstanceRegistry, ERC721 {
    using SafeMath for uint256;

    bytes32[] public names;
    mapping(bytes32 => address) public templates;
    bytes32 public activeTemplate;

    uint256 public tokenSerialNumber;
    mapping(uint256 => uint256) public serialNumberToTokenId;
    mapping(uint256 => uint256) public tokenIdToSerialNumber;

    mapping(address => address[]) private ownerToVaultsMap;

    event TemplateAdded(bytes32 indexed name, address indexed template);
    event TemplateActive(bytes32 indexed name, address indexed template);

    constructor() ERC721("ArbiVault", "ARBIVAULT") {
        ERC721._setBaseURI("https://backend.arbirise.finance/nft/");
    }

    function addTemplate(bytes32 name, address template) public onlyOwner {
        require(templates[name] == address(0), "Template already exists");
        templates[name] = template;
        if (names.length == 0) {
            activeTemplate = name;
            emit TemplateActive(name, template);
        }
        names.push(name);
        emit TemplateAdded(name, template);
    }

    function setActive(bytes32 name) public onlyOwner {
        require(templates[name] != address(0), "Template does not exist");
        activeTemplate = name;
        emit TemplateActive(name, templates[name]);
    }

    /* registry functions */

    function isInstance(address instance) external view override returns (bool validity) {
        return ERC721._exists(uint256(instance));
    }

    function instanceCount() external view override returns (uint256 count) {
        return ERC721.totalSupply();
    }

    function instanceAt(uint256 index) external view override returns (address instance) {
        return address(ERC721.tokenByIndex(index));
    }

    /* factory functions */

    function create(bytes calldata) external override returns (address vault) {
        return createSelected(activeTemplate);
    }

    function create2(bytes calldata, bytes32 salt) external override returns (address vault) {
        return createSelected2(activeTemplate, salt);
    }

    function create() public returns (address vault) {
        return createSelected(activeTemplate);
    }

    function create2(bytes32 salt) public returns (address vault) {
        return createSelected2(activeTemplate, salt);
    }

    function createSelected(bytes32 name) public returns (address vault) {
        // create clone and initialize
        vault = ProxyFactory._create(
            templates[name],
            abi.encodeWithSelector(IUniversalVault.initialize.selector)
        );

        // mint nft to caller
        uint256 tokenId = uint256(vault);
        ERC721._safeMint(msg.sender, tokenId);
        // push vault to owner's map
        ownerToVaultsMap[msg.sender].push(vault);
        // update serial number
        tokenSerialNumber = tokenSerialNumber.add(1);
        serialNumberToTokenId[tokenSerialNumber] = tokenId;
        tokenIdToSerialNumber[tokenId] = tokenSerialNumber;

        // emit event
        emit InstanceAdded(vault);

        // explicit return
        return vault;
    }

    function createSelected2(bytes32 name, bytes32 salt) public returns (address vault) {
        // create clone and initialize
        vault = ProxyFactory._create2(
            templates[name],
            abi.encodeWithSelector(IUniversalVault.initialize.selector),
            salt
        );

        // mint nft to caller
        uint256 tokenId = uint256(vault);
        ERC721._safeMint(msg.sender, tokenId);
        // push vault to owner's map
        ownerToVaultsMap[msg.sender].push(vault);
        // update serial number
        tokenSerialNumber = tokenSerialNumber.add(1);
        serialNumberToTokenId[tokenSerialNumber] = tokenId;
        tokenIdToSerialNumber[tokenId] = tokenSerialNumber;

        // emit event
        emit InstanceAdded(vault);

        // explicit return
        return vault;
    }

    /* getter functions */

    function nameCount() public view returns (uint256) {
        return names.length;
    }

    function vaultCount(address owner) public view returns (uint256) {
        return ownerToVaultsMap[owner].length;
    }

    function getVault(address owner, uint256 index) public view returns (address) {
        return ownerToVaultsMap[owner][index];
    }

    function getAllVaults(address owner) public view returns (address[] memory) {
        return ownerToVaultsMap[owner];
    }

    function getTemplate() external view returns (address) {
        return templates[activeTemplate];
    }

    function getVaultOfNFT(uint256 nftId) public pure returns (address) {
        return address(nftId);
    }

    function getNFTOfVault(address vault) public pure returns (uint256) {
        return uint256(vault);
    }
}

File 10 of 33 : RewardPool.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";

import {Powered} from "./Powered.sol";

interface IRewardPool {
    function sendERC20(
        address token,
        address to,
        uint256 value
    ) external;

    function rescueERC20(address[] calldata tokens, address recipient) external;
}

/// @title Reward Pool
/// @notice Vault for isolated storage of reward tokens
contract RewardPool is IRewardPool, Powered, Ownable {
    /* initializer */

    constructor(address powerSwitch) {
        Powered._setPowerSwitch(powerSwitch);
    }

    /* user functions */

    /// @notice Send an ERC20 token
    /// access control: only owner
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    /// state scope: none
    /// token transfer: transfer tokens from self to recipient
    /// @param token address The token to send
    /// @param to address The recipient to send to
    /// @param value uint256 Amount of tokens to send
    function sendERC20(
        address token,
        address to,
        uint256 value
    ) external override onlyOwner onlyOnline {
        TransferHelper.safeTransfer(token, to, value);
    }

    /* emergency functions */

    /// @notice Rescue multiple ERC20 tokens
    /// access control: only power controller
    /// state machine:
    ///   - can be called multiple times
    ///   - only shutdown
    /// state scope: none
    /// token transfer: transfer tokens from self to recipient
    /// @param tokens address[] The tokens to rescue
    /// @param recipient address The recipient to rescue to
    function rescueERC20(address[] calldata tokens, address recipient)
        external
        override
        onlyShutdown
    {
        // only callable by controller
        require(
            msg.sender == Powered.getPowerController(),
            "RewardPool: only controller can withdraw after shutdown"
        );

        // assert recipient is defined
        require(recipient != address(0), "RewardPool: recipient not defined");

        // transfer tokens
        for (uint256 index = 0; index < tokens.length; index++) {
            // get token
            address token = tokens[index];
            // get balance
            uint256 balance = IERC20(token).balanceOf(address(this));
            // transfer token
            TransferHelper.safeTransfer(token, recipient, balance);
        }
    }
}

File 11 of 33 : Powered.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {IPowerSwitch} from "./PowerSwitch.sol";

interface IPowered {
    function isOnline() external view returns (bool status);

    function isOffline() external view returns (bool status);

    function isShutdown() external view returns (bool status);

    function getPowerSwitch() external view returns (address powerSwitch);

    function getPowerController() external view returns (address controller);
}

/// @title Powered
/// @notice Helper for calling external PowerSwitch
contract Powered is IPowered {
    /* storage */

    address private _powerSwitch;

    /* modifiers */

    modifier onlyOnline() {
        _onlyOnline();
        _;
    }

    modifier onlyOffline() {
        _onlyOffline();
        _;
    }

    modifier notShutdown() {
        _notShutdown();
        _;
    }

    modifier onlyShutdown() {
        _onlyShutdown();
        _;
    }

    /* initializer */

    function _setPowerSwitch(address powerSwitch) internal {
        _powerSwitch = powerSwitch;
    }

    /* getter functions */

    function isOnline() public view override returns (bool status) {
        return IPowerSwitch(_powerSwitch).isOnline();
    }

    function isOffline() public view override returns (bool status) {
        return IPowerSwitch(_powerSwitch).isOffline();
    }

    function isShutdown() public view override returns (bool status) {
        return IPowerSwitch(_powerSwitch).isShutdown();
    }

    function getPowerSwitch() public view override returns (address powerSwitch) {
        return _powerSwitch;
    }

    function getPowerController() public view override returns (address controller) {
        return IPowerSwitch(_powerSwitch).getPowerController();
    }

    /* convenience functions */

    function _onlyOnline() private view {
        require(isOnline(), "Powered: is not online");
    }

    function _onlyOffline() private view {
        require(isOffline(), "Powered: is not offline");
    }

    function _notShutdown() private view {
        require(!isShutdown(), "Powered: is shutdown");
    }

    function _onlyShutdown() private view {
        require(isShutdown(), "Powered: is not shutdown");
    }
}

File 12 of 33 : IERC2917.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

interface IERC2917 {
    /// @dev This emits when interests amount per block is changed by the owner of the contract.
    /// It emits with the old interests amount and the new interests amount.
    event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue);

    /// @dev This emits when a users' productivity has changed
    /// It emits with the user's address and the the value after the change.
    event ProductivityIncreased(address indexed user, uint256 value);

    /// @dev This emits when a users' productivity has changed
    /// It emits with the user's address and the the value after the change.
    event ProductivityDecreased(address indexed user, uint256 value);

    function initialize() external;

    /// @dev Note best practice will be to restrict the caller to staking contract address.
    function setImplementor(address newImplementor) external;

    /// @dev Return the current contract's interest rate per block.
    /// @return The amount of interests currently producing per each block.
    function interestsPerBlock() external view returns (uint256);

    /// @notice Change the current contract's interest rate.
    /// @dev Note best practice will be to restrict the caller to staking contract address.
    /// @return The true/fase to notice that the value has successfully changed or not, when it succeeds, it will emit the InterestRatePerBlockChanged event.
    function changeInterestRatePerBlock(uint256 value) external returns (bool);

    /// @notice It will get the productivity of a given user.
    /// @dev it will return 0 if user has no productivity in the contract.
    /// @return user's productivity and overall productivity.
    function getProductivity(address user) external view returns (uint256, uint256);

    /// @notice increase a user's productivity.
    /// @dev Note best practice will be to restrict the caller to staking contract address.
    /// @return productivity added status as well as interest earned prior period and total productivity
    function increaseProductivity(address user, uint256 value)
        external
        returns (
            bool,
            uint256,
            uint256
        );

    /// @notice decrease a user's productivity.
    /// @dev Note best practice will be to restrict the caller to staking contract address.
    /// @return productivity removed status as well as interest earned prior period and total productivity
    function decreaseProductivity(address user, uint256 value)
        external
        returns (
            bool,
            uint256,
            uint256
        );

    /// @notice take() will return the interest that callee will get at current block height.
    /// @dev it will always be calculated by block.number, so it will change when block height changes.
    /// @return amount of the interest that user is able to mint() at current block height.
    function take() external view returns (uint256);

    /// @notice similar to take(), but with the block height joined to calculate return.
    /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interest.
    /// @return amount of interest and the block height.
    function takeWithBlock() external view returns (uint256, uint256);

    /// @notice mint the avaiable interests to callee.
    /// @dev once it mints, the amount of interests will transfer to callee's address.
    /// @return the amount of interest minted.
    function mint() external returns (uint256);
}

File 13 of 33 : ProxyFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";

library ProxyFactory {
    /* functions */

    function _create(address logic, bytes memory data) internal returns (address proxy) {
        // deploy clone
        proxy = Clones.clone(logic);

        // attempt initialization
        if (data.length > 0) {
            (bool success, bytes memory err) = proxy.call(data);
            require(success, string(err));
        }

        // explicit return
        return proxy;
    }

    function _create2(
        address logic,
        bytes memory data,
        bytes32 salt
    ) internal returns (address proxy) {
        // deploy clone
        proxy = Clones.cloneDeterministic(logic, salt);

        // attempt initialization
        if (data.length > 0) {
            (bool success, bytes memory err) = proxy.call(data);
            require(success, string(err));
        }

        // explicit return
        return proxy;
    }
}

File 14 of 33 : IERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "../../introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
      * @dev Safely transfers `tokenId` token from `from` to `to`.
      *
      * Requirements:
      *
      * - `from` cannot be the zero address.
      * - `to` cannot be the zero address.
      * - `tokenId` token must exist and be owned by `from`.
      * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
      * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
      *
      * Emits a {Transfer} event.
      */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}

File 15 of 33 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}

File 16 of 33 : ERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";

/**
 * @title ERC721 Non-Fungible Token Standard basic implementation
 * @dev see https://eips.ethereum.org/EIPS/eip-721
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
    using SafeMath for uint256;
    using Address for address;
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableMap for EnumerableMap.UintToAddressMap;
    using Strings for uint256;

    // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
    // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
    bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;

    // Mapping from holder address to their (enumerable) set of owned tokens
    mapping (address => EnumerableSet.UintSet) private _holderTokens;

    // Enumerable mapping from token ids to their owners
    EnumerableMap.UintToAddressMap private _tokenOwners;

    // Mapping from token ID to approved address
    mapping (uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping (address => mapping (address => bool)) private _operatorApprovals;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Optional mapping for token URIs
    mapping (uint256 => string) private _tokenURIs;

    // Base URI
    string private _baseURI;

    /*
     *     bytes4(keccak256('balanceOf(address)')) == 0x70a08231
     *     bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
     *     bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
     *     bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
     *     bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
     *     bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
     *     bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
     *     bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
     *     bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
     *
     *     => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
     *        0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
     */
    bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;

    /*
     *     bytes4(keccak256('name()')) == 0x06fdde03
     *     bytes4(keccak256('symbol()')) == 0x95d89b41
     *     bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
     *
     *     => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
     */
    bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;

    /*
     *     bytes4(keccak256('totalSupply()')) == 0x18160ddd
     *     bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
     *     bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
     *
     *     => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
     */
    bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor (string memory name_, string memory symbol_) public {
        _name = name_;
        _symbol = symbol_;

        // register the supported interfaces to conform to ERC721 via ERC165
        _registerInterface(_INTERFACE_ID_ERC721);
        _registerInterface(_INTERFACE_ID_ERC721_METADATA);
        _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _holderTokens[owner].length();
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
        if (bytes(_tokenURI).length > 0) {
            return string(abi.encodePacked(base, _tokenURI));
        }
        // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
        return string(abi.encodePacked(base, tokenId.toString()));
    }

    /**
    * @dev Returns the base URI set via {_setBaseURI}. This will be
    * automatically added as a prefix in {tokenURI} to each token's URI, or
    * to the token ID if no specific URI is set for that token ID.
    */
    function baseURI() public view virtual returns (string memory) {
        return _baseURI;
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        return _holderTokens[owner].at(index);
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
        return _tokenOwners.length();
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        (uint256 tokenId, ) = _tokenOwners.at(index);
        return tokenId;
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(operator != _msgSender(), "ERC721: approve to caller");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _tokenOwners.contains(tokenId);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     d*
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
        _mint(to, tokenId);
        require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _holderTokens[to].add(tokenId);

        _tokenOwners.set(tokenId, to);

        emit Transfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId); // internal owner

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        // Clear metadata (if any)
        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }

        _holderTokens[owner].remove(tokenId);

        _tokenOwners.remove(tokenId);

        emit Transfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _holderTokens[from].remove(tokenId);
        _holderTokens[to].add(tokenId);

        _tokenOwners.set(tokenId, to);

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        _tokenURIs[tokenId] = _tokenURI;
    }

    /**
     * @dev Internal function to set the base URI for all token IDs. It is
     * automatically added as a prefix to the value returned in {tokenURI},
     * or to the token ID if {tokenURI} is empty.
     */
    function _setBaseURI(string memory baseURI_) internal virtual {
        _baseURI = baseURI_;
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
        private returns (bool)
    {
        if (!to.isContract()) {
            return true;
        }
        bytes memory returndata = to.functionCall(abi.encodeWithSelector(
            IERC721Receiver(to).onERC721Received.selector,
            _msgSender(),
            from,
            tokenId,
            _data
        ), "ERC721: transfer to non ERC721Receiver implementer");
        bytes4 retval = abi.decode(returndata, (bytes4));
        return (retval == _ERC721_RECEIVED);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}

File 17 of 33 : Initializable.sol
// SPDX-License-Identifier: MIT

// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;

import "../utils/Address.sol";

/**
 * @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 {UpgradeableProxy-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.
 */
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() {
        require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /// @dev Returns true if and only if the function is running in the constructor
    function _isConstructor() private view returns (bool) {
        return !Address.isContract(address(this));
    }
}

File 18 of 33 : Address.sol
// SPDX-License-Identifier: MIT

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 19 of 33 : EIP712.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/* solhint-disable max-line-length */

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private constant _TYPE_HASH =
        keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */

    constructor(string memory name, string memory version) {
        _HASHED_NAME = keccak256(bytes(name));
        _HASHED_VERSION = keccak256(bytes(version));
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 name,
        bytes32 version
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
    }

    function _getChainId() private view returns (uint256 chainId) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        // solhint-disable-next-line no-inline-assembly
        assembly {
            chainId := chainid()
        }
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712NameHash() internal view virtual returns (bytes32) {
        return _HASHED_NAME;
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712VersionHash() internal view virtual returns (bytes32) {
        return _HASHED_VERSION;
    }
}

File 20 of 33 : ERC1271.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

interface IERC1271 {
    function isValidSignature(bytes32 _messageHash, bytes memory _signature)
        external
        view
        returns (bytes4 magicValue);
}

library SignatureChecker {
    function isValidSignature(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        if (Address.isContract(signer)) {
            bytes4 selector = IERC1271.isValidSignature.selector;
            (bool success, bytes memory returndata) =
                signer.staticcall(abi.encodeWithSelector(selector, hash, signature));
            return success && abi.decode(returndata, (bytes4)) == selector;
        } else {
            return ECDSA.recover(hash, signature) == signer;
        }
    }
}

/// @title ERC1271
/// @notice Module for ERC1271 compatibility
abstract contract ERC1271 is IERC1271 {
    // Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)")
    bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;
    // Invalid magic value
    bytes4 internal constant INVALID_SIG = bytes4(0);

    modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) {
        require(
            isValidSignature(permissionHash, signature) == VALID_SIG,
            "ERC1271: Invalid signature"
        );
        _;
    }

    function _getOwner() internal view virtual returns (address owner);

    function isValidSignature(bytes32 permissionHash, bytes memory signature)
        public
        view
        override
        returns (bytes4)
    {
        return
            SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature)
                ? VALID_SIG
                : INVALID_SIG;
    }
}

File 21 of 33 : OwnableERC721.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";

/// @title OwnableERC721
/// @notice Use ERC721 ownership for access control
contract OwnableERC721 {
    address private _nftAddress;

    modifier onlyOwner() {
        require(owner() == msg.sender, "OwnableERC721: caller is not the owner");
        _;
    }

    function _setNFT(address nftAddress) internal {
        _nftAddress = nftAddress;
    }

    function nft() public view virtual returns (address nftAddress) {
        return _nftAddress;
    }

    function owner() public view virtual returns (address ownerAddress) {
        return IERC721(_nftAddress).ownerOf(uint256(address(this)));
    }
}

File 22 of 33 : ArbiStakerERC721.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";

import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVault} from "../arbiVault/ArbiVault.sol";
import {ArbiVaultFactory} from "../arbiVault/ArbiVaultFactory.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
import {IERC2917} from "./IERC2917.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";

interface IRageQuit {
    function rageQuit() external;
}

interface IArbiStakerERC721 is IRageQuit {
    /* admin events */

    event ArbiStakerERC721Created(address rewardPool, address powerSwitch);
    event ArbiStakerERC721Funded(address token, uint256 amount);
    event BonusTokenRegistered(address token);
    event BonusTokenRemoved(address token);
    event VaultFactoryRegistered(address factory);
    event VaultFactoryRemoved(address factory);
    event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin);

    /* user events */

    event Staked(address vault, address token, uint256 tokenId);
    event Unstaked(address vault, address token, uint256 tokenId);
    event RageQuit(address vault);
    event RewardClaimed(address vaultFactory, address recipient, address token, uint256 amount);
    event VestedRewardClaimed(address recipient, address token, uint256 amount);

    /* data types */

    struct VaultData {
        // token address to total token stake mapping
        mapping(address => uint256) tokenStake;
        EnumerableSet.AddressSet tokens;
    }

    struct LMRewardData {
        uint256 amount;
        uint256 duration;
        uint256 startedAt;
        address rewardCalcInstance;
        EnumerableSet.AddressSet bonusTokens;
        mapping(address => uint256) bonusTokenAmounts;
    }

    struct LMRewardVestingData {
        uint256 amount;
        uint256 startedAt;
    }

    /* getter functions */
    function getBonusTokenSetLength() external view returns (uint256 length);

    function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);

    function getVaultFactorySetLength() external view returns (uint256 length);

    function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);

    function getNumVaults() external view returns (uint256 num);

    function getVaultAt(uint256 index) external view returns (address vault);

    function getNumTokensStaked() external view returns (uint256 num);

    function getTokenStakedAt(uint256 index) external view returns (address token);

    function getNumTokensStakedInVault(address vault) external view returns (uint256 num);

    function getVaultTokenAtIndex(address vault, uint256 index)
        external
        view
        returns (address vaultToken);

    function getVaultTokenStake(address vault, address token)
        external
        view
        returns (uint256 tokenStake);

    function getLMRewardData(address token)
        external
        view
        returns (
            uint256 amount,
            uint256 duration,
            uint256 startedAt,
            address rewardCalcInstance
        );

    function getLMRewardBonusTokensLength(address token) external view returns (uint256 length);

    function getLMRewardBonusTokenAt(address token, uint256 index)
        external
        view
        returns (address bonusToken, uint256 bonusTokenAmount);

    function getNumVestingLMTokenRewards(address user) external view returns (uint256 num);

    function getVestingLMTokenAt(address user, uint256 index) external view returns (address token);

    function getNumVests(address user, address token) external view returns (uint256 num);

    function getNumRewardCalcTemplates() external view returns (uint256 num);

    function getLMRewardVestingData(
        address user,
        address token,
        uint256 index
    ) external view returns (uint256 amount, uint256 startedAt);

    function isValidAddress(address target) external view returns (bool validity);

    function isValidVault(address vault, address factory) external view returns (bool validity);

    /* user functions */

    function stakeERC721(
        address vault,
        address vaultFactory,
        address token,
        uint256 tokenId,
        bytes calldata permission
    ) external;

    function unstakeERC721AndClaimReward(
        address vault,
        address vaultFactory,
        address recipient,
        address token,
        uint256 tokenId,
        bool claimBonusReward,
        bytes calldata permission
    ) external;

    function claimVestedRewardAll() external;

    function claimVestedRewardToken(address token) external;
}

/// @title ArbiStakerERC721
/// @notice Reward distribution contract that handles ERC721 Token with Tiers
/// Access Control
/// - Power controller:
///     Can power off / shutdown the ArbiStakerERC721
///     Can withdraw rewards from reward pool once shutdown
/// - Owner:
///     Is unable to operate on user funds due to UniversalVault
///     Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - ArbiStakerERC721 admin:
///     Can add funds to the ArbiStakerERC721, register bonus tokens, and whitelist new vault factories
///     Is a subset of owner permissions
/// - User:
///     Can stake / unstake / ragequit / claim vested rewards
/// ArbiStakerERC721 State Machine
/// - Online:
///     ArbiStakerERC721 is operating normally, all functions are enabled
/// - Offline:
///     ArbiStakerERC721 is temporarely disabled for maintenance
///     User staking and unstaking is disabled, ragequit remains enabled
///     Users can delete their stake through rageQuit() but forego their pending reward
///     Should only be used when downtime required for an upgrade
/// - Shutdown:
///     ArbiStakerERC721 is permanently disabled
///     All functions are disabled with the exception of ragequit
///     Users can delete their stake through rageQuit()
///     Power controller can withdraw from the reward pool
///     Should only be used if Owner role is compromised
contract ArbiStakerERC721 is IArbiStakerERC721, Powered {
    using SafeMath for uint256;
    using EnumerableSet for EnumerableSet.AddressSet;

    /* constants */
    string public constant PIONNER = "PIONNER";
    string public constant PRECURSOR = "PRECURSOR";
    string public constant INNOVATOR = "INNOVATOR";
    string public constant EARLY_ADOPTER = "EARLY_ADOPTER";
    string public constant STANDARD = "STANDARD";
    uint256 public PIONNER_LM_REWARD_MULTIPLIER_NUM = 6;
    uint256 public PIONNER_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public PRECURSOR_LM_REWARD_MULTIPLIER_NUM = 5;
    uint256 public PRECURSOR_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public INNOVATOR_LM_REWARD_MULTIPLIER_NUM = 2;
    uint256 public INNOVATOR_LM_REWARD_MULTIPLIER_DENOM = 1;
    uint256 public EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM = 3;
    uint256 public EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM = 2;
    uint256 public STANDARD_LM_REWARD_MULTIPLIER_NUM = 1;
    uint256 public STANDARD_LM_REWARD_MULTIPLIER_DENOM = 1;
    uint256 public LM_REWARD_VESTING_PERIOD = 7776000; // 3 months
    uint256 public LM_REWARD_VESTING_PORTION_NUM = 1;
    uint256 public LM_REWARD_VESTING_PORTION_DENOM = 2;

    // An upper bound on the number of active tokens staked per vault is required to prevent
    // calls to rageQuit() from reverting.
    // With 30 tokens staked in a vault, ragequit costs 432811 gas which is conservatively lower
    // than the hardcoded limit of 500k gas on the vault.
    // This limit is configurable and could be increased in a future deployment.
    // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
    // an error code that allows for reliably catching out-of-gas errors on remote calls.
    uint256 public MAX_TOKENS_STAKED_PER_VAULT = 30;
    uint256 public MAX_BONUS_TOKENS = 50;

    /* storage */
    address public admin;
    address public rewardToken;
    address public rewardPool;

    EnumerableSet.AddressSet private _vaultSet;
    mapping(address => VaultData) private _vaults;

    EnumerableSet.AddressSet private _bonusTokenSet;
    EnumerableSet.AddressSet private _vaultFactorySet;

    EnumerableSet.AddressSet private _allStakedTokens;
    mapping(address => uint256) public stakedTokenTotal;

    mapping(address => LMRewardData) private lmRewards;

    // user to token to earned reward mapping
    mapping(address => mapping(address => uint256)) public earnedLMRewards;
    // user to token to vesting data mapping
    mapping(address => mapping(address => LMRewardVestingData[])) public vestingLMRewards;
    // user to vesting lm token rewards set
    mapping(address => EnumerableSet.AddressSet) private vestingLMTokenRewards;

    // erc2917 template names
    string[] public rewardCalcTemplateNames;
    // erc2917 template names to erc 2917 templates
    mapping(string => address) public rewardCalcTemplates;
    string public activeRewardCalcTemplate;
    event RewardCalcTemplateAdded(string indexed name, address indexed template);
    event RewardCalcTemplateActive(string indexed name, address indexed template);

    /* initializer */

    /// @notice Initizalize ArbiStakerERC721
    /// access control: only proxy constructor
    /// state machine: can only be called once
    /// state scope: set initialization variables
    /// token transfer: none
    /// @param adminAddress address The admin address
    /// @param rewardPoolFactory address The factory to use for deploying the RewardPool
    /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
    /// @param rewardTokenAddress address The address of the reward token for this ArbiStakerERC721
    constructor(
        address adminAddress,
        address rewardPoolFactory,
        address powerSwitchFactory,
        address rewardTokenAddress
    ) {
        // deploy power switch
        address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(adminAddress));

        // deploy reward pool
        rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));

        // set internal config
        admin = adminAddress;
        rewardToken = rewardTokenAddress;
        Powered._setPowerSwitch(powerSwitch);

        // emit event
        emit ArbiStakerERC721Created(rewardPool, powerSwitch);
    }

    /* admin functions */

    function _admin() private {
        require(msg.sender == admin, "not allowed");
    }

    /**
     * @dev Leaves the contract without admin. It will not be possible to call
     * `admin` functions anymore. Can only be called by the current admin.
     *
     * NOTE: Renouncing adminship will leave the contract without an admin,
     * thereby removing any functionality that is only available to the admin.
     */
    function renounceAdminship() public {
        _admin();
        emit AdminshipTransferred(admin, address(0));
        admin = address(0);
    }

    /**
     * @dev Transfers adminship of the contract to a new account (`newAdmin`).
     * Can only be called by the current admin.
     */
    function transferAdminship(address newAdmin) public {
        _admin();
        require(newAdmin != address(0), "new admin can't the zero address");
        emit AdminshipTransferred(admin, newAdmin);
        admin = newAdmin;
    }

    /// @notice Add funds to ArbiStakerERC721
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    /// state scope:
    ///   - none
    /// token transfer: transfer staking tokens from msg.sender to reward pool
    /// @param amount uint256 Amount of reward tokens to deposit
    function fund(address token, uint256 amount) external {
        _admin();
        require(
            _bonusTokenSet.contains(token) || token == rewardToken,
            "cannot fund with unrecognized token"
        );
        // transfer reward tokens to reward pool
        TransferHelper.safeTransferFrom(token, msg.sender, rewardPool, amount);

        // emit event
        emit ArbiStakerERC721Funded(token, amount);
    }

    /// @notice Rescue tokens from RewardPool
    /// @dev use this function to rescue tokens from RewardPool contract without distributing to stakers or triggering emergency shutdown
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope: none
    /// token transfer: transfer requested token from RewardPool to recipient
    /// @param token address The address of the token to rescue
    /// @param recipient address The address of the recipient
    /// @param amount uint256 The amount of tokens to rescue
    function rescueTokensFromRewardPool(
        address token,
        address recipient,
        uint256 amount
    ) external {
        _admin();
        // verify recipient
        require(isValidAddress(recipient), "invalid recipient");
        // transfer tokens to recipient
        IRewardPool(rewardPool).sendERC20(token, recipient, amount);
    }

    /// @notice Add vault factory to whitelist
    /// @dev use this function to enable stakes to vaults coming from the specified factory contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - append to _vaultFactorySet
    /// token transfer: none
    /// @param factory address The address of the vault factory
    function registerVaultFactory(address factory) external {
        _admin();
        // add factory to set
        require(
            _vaultFactorySet.add(factory),
            "ArbiStakerERC721: vault factory already registered"
        );

        // emit event
        emit VaultFactoryRegistered(factory);
    }

    /// @notice Remove vault factory from whitelist
    /// @dev use this function to disable new stakes to vaults coming from the specified factory contract.
    ///      note: vaults with existing stakes from this factory are sill able to unstake
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - remove from _vaultFactorySet
    /// token transfer: none
    /// @param factory address The address of the vault factory
    function removeVaultFactory(address factory) external {
        _admin();
        // remove factory from set
        require(_vaultFactorySet.remove(factory), "ArbiStakerERC721: vault factory not registered");

        // emit event
        emit VaultFactoryRemoved(factory);
    }

    /// @notice Register bonus token for distribution
    /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    /// state scope:
    ///   - append to _bonusTokenSet
    /// token transfer: none
    /// @param bonusToken address The address of the bonus token
    function registerBonusToken(address bonusToken) external {
        _admin();
        // verify valid bonus token
        require(isValidAddress(bonusToken), "invalid bonus token address or is already present");

        // verify bonus token count
        require(
            _bonusTokenSet.length() < MAX_BONUS_TOKENS,
            "ArbiStakerERC721: max bonus tokens reached "
        );

        // add token to set
        _bonusTokenSet.add(bonusToken);

        // emit event
        emit BonusTokenRegistered(bonusToken);
    }

    /// @notice Remove bonus token
    /// @dev use this function to disable distribution of a token held by the RewardPool contract
    /// access control: only admin
    /// state machine:
    ///   - can be called multiple times
    ///   - not shutdown
    /// state scope:
    ///   - remove from _bonusTokenSet
    /// token transfer: none
    /// @param bonusToken address The address of the bonus token
    function removeBonusToken(address bonusToken) external {
        _admin();
        require(_bonusTokenSet.remove(bonusToken), "ArbiStakerERC721: bonus token not present ");

        // emit event
        emit BonusTokenRemoved(bonusToken);
    }

    function addRewardCalcTemplate(string calldata name, address template) external {
        _admin();
        require(rewardCalcTemplates[name] == address(0), "Template already exists");
        rewardCalcTemplates[name] = template;
        if (rewardCalcTemplateNames.length == 0) {
            activeRewardCalcTemplate = name;
            emit RewardCalcTemplateActive(name, template);
        }
        rewardCalcTemplateNames.push(name);
        emit RewardCalcTemplateAdded(name, template);
    }

    function setRewardCalcActiveTemplate(string calldata name) external {
        _admin();
        require(rewardCalcTemplates[name] != address(0), "Template does not exist");
        activeRewardCalcTemplate = name;
        emit RewardCalcTemplateActive(name, rewardCalcTemplates[name]);
    }

    function startLMRewards(
        address token,
        uint256 amount,
        uint256 duration
    ) external {
        startLMRewardsToken(token, amount, duration, activeRewardCalcTemplate);
    }

    function startLMRewardsToken(
        address token,
        uint256 amount,
        uint256 duration,
        string memory rewardCalcTemplateName
    ) public {
        _admin();
        require(lmRewards[token].startedAt == 0, "A reward program already live for this token");
        require(
            rewardCalcTemplates[rewardCalcTemplateName] != address(0),
            "Reward Calculator Template does not exist"
        );
        // create reward calc clone from template
        address rewardCalcInstance =
            ProxyFactory._create(
                rewardCalcTemplates[rewardCalcTemplateName],
                abi.encodeWithSelector(IERC2917.initialize.selector)
            );
        LMRewardData storage lmrd = lmRewards[token];
        lmrd.amount = amount;
        lmrd.duration = duration;
        lmrd.startedAt = block.timestamp;
        lmrd.rewardCalcInstance = rewardCalcInstance;
    }

    function setImplementorForRewardsCalculator(address token, address newImplementor) public {
        _admin();
        require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
        address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
        IERC2917(rewardCalcInstance).setImplementor(newImplementor);
    }

    function setLMRewardsPerBlock(address token, uint256 value) public onlyOnline {
        _admin();
        require(lmRewards[token].startedAt != 0, "No reward program currently live for this token");
        address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
        IERC2917(rewardCalcInstance).changeInterestRatePerBlock(value);
    }

    function addBonusTokenToLMRewards(
        address lmToken,
        address bonusToken,
        uint256 bonusTokenAmount
    ) public {
        _admin();
        require(
            lmRewards[lmToken].startedAt != 0,
            "No reward program currently live for this LM token"
        );
        require(_bonusTokenSet.contains(bonusToken), "Bonus token not registered");
        lmRewards[lmToken].bonusTokens.add(bonusToken);
        lmRewards[lmToken].bonusTokenAmounts[bonusToken] = lmRewards[lmToken].bonusTokenAmounts[
            bonusToken
        ]
            .add(bonusTokenAmount);
    }

    function endLMRewards(address token, bool removeBonusTokenData) public {
        _admin();
        lmRewards[token].amount = 0;
        lmRewards[token].duration = 0;
        lmRewards[token].startedAt = 0;
        lmRewards[token].rewardCalcInstance = address(0);
        if (removeBonusTokenData) {
            for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
                address bonusToken = lmRewards[token].bonusTokens.at(index);
                lmRewards[token].bonusTokens.remove(bonusToken);
                delete lmRewards[token].bonusTokenAmounts[bonusToken];
            }
        }
    }

    function setMaxStakesPerVault(uint256 amount) external {
        _admin();
        MAX_TOKENS_STAKED_PER_VAULT = amount;
    }

    function setMaxBonusTokens(uint256 amount) external {
        _admin();
        MAX_BONUS_TOKENS = amount;
    }

    function setPionnerLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        PIONNER_LM_REWARD_MULTIPLIER_NUM = numerator;
        PIONNER_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setEarlyAdopterLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        PRECURSOR_LM_REWARD_MULTIPLIER_NUM = numerator;
        PRECURSOR_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setPrecursorLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        INNOVATOR_LM_REWARD_MULTIPLIER_NUM = numerator;
        INNOVATOR_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setInnovatorLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM = numerator;
        EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setStandardLMRewardMultiplier(uint256 numerator, uint256 denominator) external {
        _admin();
        STANDARD_LM_REWARD_MULTIPLIER_NUM = numerator;
        STANDARD_LM_REWARD_MULTIPLIER_DENOM = denominator;
    }

    function setLMRewardVestingPeriod(uint256 amount) external {
        _admin();
        LM_REWARD_VESTING_PERIOD = amount;
    }

    function setLMRewardVestingPortion(uint256 numerator, uint256 denominator) external {
        _admin();
        LM_REWARD_VESTING_PORTION_NUM = numerator;
        LM_REWARD_VESTING_PORTION_DENOM = denominator;
    }

    /* getter functions */

    function getBonusTokenSetLength() external view override returns (uint256 length) {
        return _bonusTokenSet.length();
    }

    function getBonusTokenAtIndex(uint256 index)
        external
        view
        override
        returns (address bonusToken)
    {
        return _bonusTokenSet.at(index);
    }

    function getVaultFactorySetLength() external view override returns (uint256 length) {
        return _vaultFactorySet.length();
    }

    function getVaultFactoryAtIndex(uint256 index)
        external
        view
        override
        returns (address factory)
    {
        return _vaultFactorySet.at(index);
    }

    function getNumVaults() external view override returns (uint256 num) {
        return _vaultSet.length();
    }

    function getVaultAt(uint256 index) external view override returns (address vault) {
        return _vaultSet.at(index);
    }

    function getNumTokensStaked() external view override returns (uint256 num) {
        return _allStakedTokens.length();
    }

    function getTokenStakedAt(uint256 index) external view override returns (address token) {
        return _allStakedTokens.at(index);
    }

    function getNumTokensStakedInVault(address vault) external view override returns (uint256 num) {
        return _vaults[vault].tokens.length();
    }

    function getVaultTokenAtIndex(address vault, uint256 index)
        external
        view
        override
        returns (address vaultToken)
    {
        return _vaults[vault].tokens.at(index);
    }

    function getVaultTokenStake(address vault, address token)
        external
        view
        override
        returns (uint256 tokenStake)
    {
        return _vaults[vault].tokenStake[token];
    }

    function getNftTier(uint256 nftId, address nftFactory)
        public
        view
        returns (string memory tier)
    {
        uint256 serialNumber = ArbiVaultFactory(nftFactory).tokenIdToSerialNumber(nftId);
        if (serialNumber >= 1 && serialNumber <= 10) {
            tier = PIONNER;
        } else if (serialNumber >= 11 && serialNumber <= 100) {
            tier = PRECURSOR;
        } else if (serialNumber >= 101 && serialNumber <= 500) {
            tier = INNOVATOR;
        } else if (serialNumber >= 501 && serialNumber <= 1000) {
            tier = EARLY_ADOPTER;
        } else if (serialNumber >= 1001) {
            tier = STANDARD;
        }
    }

    function getLMRewardData(address token)
        external
        view
        override
        returns (
            uint256 amount,
            uint256 duration,
            uint256 startedAt,
            address rewardCalcInstance
        )
    {
        return (
            lmRewards[token].amount,
            lmRewards[token].duration,
            lmRewards[token].startedAt,
            lmRewards[token].rewardCalcInstance
        );
    }

    function getLMRewardBonusTokensLength(address token)
        external
        view
        override
        returns (uint256 length)
    {
        return lmRewards[token].bonusTokens.length();
    }

    function getLMRewardBonusTokenAt(address token, uint256 index)
        external
        view
        override
        returns (address bonusToken, uint256 bonusTokenAmount)
    {
        return (
            lmRewards[token].bonusTokens.at(index),
            lmRewards[token].bonusTokenAmounts[lmRewards[token].bonusTokens.at(index)]
        );
    }

    function getNumVestingLMTokenRewards(address user)
        external
        view
        override
        returns (uint256 num)
    {
        return vestingLMTokenRewards[user].length();
    }

    function getVestingLMTokenAt(address user, uint256 index)
        external
        view
        override
        returns (address token)
    {
        return vestingLMTokenRewards[user].at(index);
    }

    function getNumVests(address user, address token) external view override returns (uint256 num) {
        return vestingLMRewards[user][token].length;
    }

    function getLMRewardVestingData(
        address user,
        address token,
        uint256 index
    ) external view override returns (uint256 amount, uint256 startedAt) {
        return (
            vestingLMRewards[user][token][index].amount,
            vestingLMRewards[user][token][index].startedAt
        );
    }

    function getNumRewardCalcTemplates() external view override returns (uint256 num) {
        return rewardCalcTemplateNames.length;
    }

    /* helper functions */

    function isValidVault(address vault, address factory)
        public
        view
        override
        returns (bool validity)
    {
        // validate vault is created from whitelisted vault factory and is an instance of that factory
        return _vaultFactorySet.contains(factory) && IInstanceRegistry(factory).isInstance(vault);
    }

    function isValidAddress(address target) public view override returns (bool validity) {
        // sanity check target for potential input errors
        return
            target != address(this) &&
            target != address(0) &&
            target != rewardToken &&
            target != rewardPool &&
            !_bonusTokenSet.contains(target);
    }

    /* convenience functions */

    function _tierMultipliedReward(
        uint256 nftId,
        address nftFactory,
        uint256 reward
    ) private view returns (uint256 multipliedReward) {
        // get tier
        string memory tier = getNftTier(nftId, nftFactory);
        bytes32 tierHash = keccak256(abi.encodePacked(tier));

        if (tierHash == keccak256(abi.encodePacked(PIONNER))) {
            multipliedReward = reward.mul(PIONNER_LM_REWARD_MULTIPLIER_NUM).div(
                PIONNER_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(PRECURSOR))) {
            multipliedReward = reward.mul(PRECURSOR_LM_REWARD_MULTIPLIER_NUM).div(
                PRECURSOR_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(INNOVATOR))) {
            multipliedReward = reward.mul(INNOVATOR_LM_REWARD_MULTIPLIER_NUM).div(
                INNOVATOR_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(EARLY_ADOPTER))) {
            multipliedReward = reward.mul(EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM).div(
                EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM
            );
        } else if (tierHash == keccak256(abi.encodePacked(STANDARD))) {
            multipliedReward = reward.mul(STANDARD_LM_REWARD_MULTIPLIER_NUM).div(
                STANDARD_LM_REWARD_MULTIPLIER_DENOM
            );
        }
    }

    /* user functions */

    /// @notice Exit ArbiStakerERC721 without claiming reward
    /// @dev This function should never revert when correctly called by the vault.
    ///      A max number of tokens staked per vault is set with MAX_TOKENS_STAKED_PER_VAULT to
    ///      place an upper bound on the for loop.
    /// access control: callable by anyone but fails if caller is not an approved vault
    /// state machine:
    ///   - when vault exists on this ArbiStakerERC721
    ///   - when active stake from this vault
    ///   - any power state
    /// state scope:
    ///   - decrease stakedTokenTotal[token], delete if 0
    ///   - delete _vaults[vault].tokenStake[token]
    ///   - remove _vaults[vault].tokens.remove(token)
    ///   - delete _vaults[vault]
    ///   - remove vault from _vaultSet
    ///   - remove token from _allStakedTokens if required
    /// token transfer: none
    function rageQuit() external override {
        require(_vaultSet.contains(msg.sender), "ArbiStakerERC721: no vault");
        //fetch vault storage reference
        VaultData storage vaultData = _vaults[msg.sender];
        // revert if no active tokens staked
        EnumerableSet.AddressSet storage vaultTokens = vaultData.tokens;
        require(vaultTokens.length() > 0, "ArbiStakerERC721: no stake");

        // update totals
        for (uint256 index = 0; index < vaultTokens.length(); index++) {
            address token = vaultTokens.at(index);
            vaultTokens.remove(token);
            uint256 amount = vaultData.tokenStake[token];
            uint256 newTotal = stakedTokenTotal[token].sub(amount);
            assert(newTotal >= 0);
            if (newTotal == 0) {
                _allStakedTokens.remove(token);
                delete stakedTokenTotal[token];
            } else {
                stakedTokenTotal[token] = newTotal;
            }
            delete vaultData.tokenStake[token];
        }

        // delete vault data
        _vaultSet.remove(msg.sender);
        delete _vaults[msg.sender];

        // emit event
        emit RageQuit(msg.sender);
    }

    /// @notice Stake ERC721 tokens
    /// @dev anyone can stake to any vault if they have valid permission
    /// access control: anyone
    /// state machine:
    ///   - can be called multiple times
    ///   - only online
    ///   - when vault exists on this ArbiStakerERC721
    /// state scope:
    ///   - add token to _vaults[vault].tokens if not already exists
    ///   - increase _vaults[vault].tokenStake[token]
    ///   - add vault to _vaultSet if not already exists
    ///   - add token to _allStakedTokens if not already exists
    ///   - increase stakedTokenTotal[token]
    /// token transfer: transfer staking tokens from msg.sender to vault
    /// @param vault address The address of the vault to stake to
    /// @param vaultFactory address The address of the vault factory which created the vault
    /// @param token address The address of the token being staked
    /// @param tokenId uint256 The id of token to stake
    function stakeERC721(
        address vault,
        address vaultFactory,
        address token,
        uint256 tokenId,
        bytes calldata permission
    ) external override onlyOnline {
        // verify vault is valid
        require(isValidVault(vault, vaultFactory), "ArbiStakerERC721: vault is not valid");

        // add vault to set
        _vaultSet.add(vault);
        // fetch vault storage reference
        VaultData storage vaultData = _vaults[vault];

        // verify stakes boundary not reached
        require(
            vaultData.tokens.length() < MAX_TOKENS_STAKED_PER_VAULT,
            "ArbiStakerERC721: MAX_TOKENS_STAKED_PER_VAULT reached"
        );

        // add token to set and increase amount
        vaultData.tokens.add(token);
        vaultData.tokenStake[token] = vaultData.tokenStake[token].add(1);

        // update total token staked
        _allStakedTokens.add(token);
        stakedTokenTotal[token] = stakedTokenTotal[token].add(1);

        // perform transfer to vault
        IERC721(token).safeTransferFrom(msg.sender, vault, tokenId);
        // call lock on vault
        IUniversalVault(vault).lockERC721(token, tokenId, permission);

        // check if there is a reward program currently running
        if (lmRewards[token].startedAt != 0) {
            address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
            (, uint256 rewardEarned, ) =
                IERC2917(rewardCalcInstance).increaseProductivity(msg.sender, 1);
            earnedLMRewards[msg.sender][token] = earnedLMRewards[msg.sender][token].add(
                rewardEarned
            );
        }

        // emit event
        emit Staked(vault, token, tokenId);
    }

    /// @notice Unstake ERC721 tokens and claim reward
    /// @dev LM rewards can only be claimed when unstaking
    /// access control: anyone with permission
    /// state machine:
    ///   - when vault exists on this ArbiStakerERC721
    ///   - after stake from vault
    ///   - can be called multiple times while sufficient stake remains
    ///   - only online
    /// state scope:
    ///   - decrease _vaults[vault].tokenStake[token]
    ///   - delete token from _vaults[vault].tokens if token stake is 0
    ///   - decrease stakedTokenTotal[token]
    ///   - delete token from _allStakedTokens if total token stake is 0
    /// token transfer:
    ///   - transfer reward tokens from reward pool to recipient
    ///   - transfer bonus tokens from reward pool to recipient
    /// @param vault address The vault to unstake from
    /// @param vaultFactory address The vault factory that created this vault
    /// @param recipient address The recipient to send reward to
    /// @param token address The staking token
    /// @param tokenId uint256 The id of the token to unstake
    /// @param claimBonusReward bool flag to claim bonus rewards
    function unstakeERC721AndClaimReward(
        address vault,
        address vaultFactory,
        address recipient,
        address token,
        uint256 tokenId,
        bool claimBonusReward,
        bytes calldata permission
    ) external override onlyOnline {
        require(_vaultSet.contains(vault), "ArbiStakerERC721: no vault");
        // fetch vault storage reference
        VaultData storage vaultData = _vaults[vault];
        // validate recipient
        require(isValidAddress(recipient), "ArbiStakerERC721: invalid recipient");
        // check for sufficient vault stake amount
        require(vaultData.tokens.contains(token), "ArbiStakerERC721: no token in vault");
        // check for sufficient vault stake amount
        require(
            vaultData.tokenStake[token] >= 1,
            "ArbiStakerERC721: insufficient vault token stake"
        );
        // check for sufficient total token stake amount
        // if the above check succeeds and this check fails, there is a bug in stake accounting
        require(stakedTokenTotal[token] >= 1, "stakedTokenTotal[token] is less than 1");

        // check if there is a reward program currently running
        uint256 rewardEarned = earnedLMRewards[msg.sender][token];
        if (lmRewards[token].startedAt != 0) {
            address rewardCalcInstance = lmRewards[token].rewardCalcInstance;
            (, uint256 newReward, ) =
                IERC2917(rewardCalcInstance).decreaseProductivity(msg.sender, 1);
            rewardEarned = rewardEarned.add(newReward);
        }

        // decrease vaultTokenStake of token in this vault
        vaultData.tokenStake[token] = vaultData.tokenStake[token].sub(1);
        if (vaultData.tokenStake[token] == 0) {
            vaultData.tokens.remove(token);
            delete vaultData.tokenStake[token];
        }

        // decrease stakedTokenTotal across all vaults
        stakedTokenTotal[token] = stakedTokenTotal[token].sub(1);
        if (stakedTokenTotal[token] == 0) {
            _allStakedTokens.remove(token);
            delete stakedTokenTotal[token];
        }

        // unlock staking tokens from vault
        IUniversalVault(vault).unlockERC721(token, tokenId, permission);

        // emit event
        emit Unstaked(vault, token, tokenId);

        // only perform on non-zero reward
        if (rewardEarned > 0) {
            // transfer bonus tokens from reward pool to recipient
            // bonus tokens can only be claimed during an active rewards program
            if (claimBonusReward && lmRewards[token].startedAt != 0) {
                for (uint256 index = 0; index < lmRewards[token].bonusTokens.length(); index++) {
                    // fetch bonus token address reference
                    address bonusToken = lmRewards[token].bonusTokens.at(index);
                    // calculate bonus token amount
                    // bonusAmount = rewardEarned * allocatedBonusReward / allocatedMainReward
                    uint256 bonusAmount =
                        rewardEarned.mul(lmRewards[token].bonusTokenAmounts[bonusToken]).div(
                            lmRewards[token].amount
                        );
                    // transfer bonus token
                    IRewardPool(rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
                    // emit event
                    emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
                }
            }
            // take care of multiplier
            uint256 multipliedReward =
                _tierMultipliedReward(uint256(vault), vaultFactory, rewardEarned);
            // take care of vesting
            uint256 vestingPortion =
                multipliedReward.mul(LM_REWARD_VESTING_PORTION_NUM).div(
                    LM_REWARD_VESTING_PORTION_DENOM
                );
            vestingLMRewards[msg.sender][token].push(
                LMRewardVestingData(vestingPortion, block.timestamp)
            );
            vestingLMTokenRewards[msg.sender].add(token);
            // set earned reward to 0
            earnedLMRewards[msg.sender][token] = 0;
            // transfer reward tokens from reward pool to recipient
            IRewardPool(rewardPool).sendERC20(
                rewardToken,
                recipient,
                multipliedReward.sub(vestingPortion)
            );
            // emit event
            emit RewardClaimed(vault, recipient, rewardToken, rewardEarned);
        }
    }

    function claimVestedRewardAll() external override onlyOnline {
        uint256 numTokens = vestingLMTokenRewards[msg.sender].length();
        for (uint256 index = 0; index < numTokens; index++) {
            address token = vestingLMTokenRewards[msg.sender].at(index);
            claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
        }
    }

    function claimVestedRewardToken(address token) external override onlyOnline {
        claimVestedReward(token, vestingLMRewards[msg.sender][token].length);
    }

    function claimVestedReward(address token, uint256 numVests) public onlyOnline {
        require(
            numVests <= vestingLMRewards[msg.sender][token].length,
            "num vests can't be greater than available vests"
        );
        LMRewardVestingData[] storage vests = vestingLMRewards[msg.sender][token];
        uint256 vestedReward;
        for (uint256 index = 0; index < numVests; index++) {
            LMRewardVestingData storage vest = vests[index];
            uint256 duration = block.timestamp.sub(vest.startedAt);
            uint256 vested = vest.amount.mul(duration).div(LM_REWARD_VESTING_PERIOD);
            if (vested >= vest.amount) {
                // completely vested
                vested = vest.amount;
                // copy last element into this slot and pop last
                vests[index] = vests[vests.length - 1];
                vests.pop();
                index--;
                numVests--;
                // if all vested remove from set
                if (vests.length == 0) {
                    vestingLMTokenRewards[msg.sender].remove(token);
                    break;
                }
            } else {
                vest.amount = vest.amount.sub(vested);
            }
            vestedReward = vestedReward.add(vested);
        }
        if (vestedReward > 0) {
            // transfer reward tokens from reward pool to recipient
            IRewardPool(rewardPool).sendERC20(rewardToken, msg.sender, vestedReward);
            // emit event
            emit VestedRewardClaimed(msg.sender, rewardToken, vestedReward);
        }
    }
}

File 23 of 33 : IERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 24 of 33 : Context.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

File 25 of 33 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {

    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 26 of 33 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {

    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 27 of 33 : ERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts may inherit from this and call {_registerInterface} to declare
 * their support of an interface.
 */
abstract contract ERC165 is IERC165 {
    /*
     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
     */
    bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;

    /**
     * @dev Mapping of interface ids to whether or not it's supported.
     */
    mapping(bytes4 => bool) private _supportedInterfaces;

    constructor () internal {
        // Derived contracts need only register support for their own interfaces,
        // we register support for ERC165 itself here
        _registerInterface(_INTERFACE_ID_ERC165);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     *
     * Time complexity O(1), guaranteed to always use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return _supportedInterfaces[interfaceId];
    }

    /**
     * @dev Registers the contract as an implementer of the interface defined by
     * `interfaceId`. Support of the actual ERC165 interface is automatic and
     * registering its interface id is not required.
     *
     * See {IERC165-supportsInterface}.
     *
     * Requirements:
     *
     * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
     */
    function _registerInterface(bytes4 interfaceId) internal virtual {
        require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
        _supportedInterfaces[interfaceId] = true;
    }
}

File 28 of 33 : EnumerableMap.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Library for managing an enumerable variant of Solidity's
 * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
 * type.
 *
 * Maps have the following properties:
 *
 * - Entries are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Entries are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableMap for EnumerableMap.UintToAddressMap;
 *
 *     // Declare a set state variable
 *     EnumerableMap.UintToAddressMap private myMap;
 * }
 * ```
 *
 * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
 * supported.
 */
library EnumerableMap {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Map type with
    // bytes32 keys and values.
    // The Map implementation uses private functions, and user-facing
    // implementations (such as Uint256ToAddressMap) are just wrappers around
    // the underlying Map.
    // This means that we can only create new EnumerableMaps for types that fit
    // in bytes32.

    struct MapEntry {
        bytes32 _key;
        bytes32 _value;
    }

    struct Map {
        // Storage of map keys and values
        MapEntry[] _entries;

        // Position of the entry defined by a key in the `entries` array, plus 1
        // because index 0 means a key is not in the map.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
        // We read and store the key's index to prevent multiple reads from the same storage slot
        uint256 keyIndex = map._indexes[key];

        if (keyIndex == 0) { // Equivalent to !contains(map, key)
            map._entries.push(MapEntry({ _key: key, _value: value }));
            // The entry is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            map._indexes[key] = map._entries.length;
            return true;
        } else {
            map._entries[keyIndex - 1]._value = value;
            return false;
        }
    }

    /**
     * @dev Removes a key-value pair from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function _remove(Map storage map, bytes32 key) private returns (bool) {
        // We read and store the key's index to prevent multiple reads from the same storage slot
        uint256 keyIndex = map._indexes[key];

        if (keyIndex != 0) { // Equivalent to contains(map, key)
            // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
            // in the array, and then remove the last entry (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = keyIndex - 1;
            uint256 lastIndex = map._entries.length - 1;

            // When the entry 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.

            MapEntry storage lastEntry = map._entries[lastIndex];

            // Move the last entry to the index where the entry to delete is
            map._entries[toDeleteIndex] = lastEntry;
            // Update the index for the moved entry
            map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved entry was stored
            map._entries.pop();

            // Delete the index for the deleted slot
            delete map._indexes[key];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function _contains(Map storage map, bytes32 key) private view returns (bool) {
        return map._indexes[key] != 0;
    }

    /**
     * @dev Returns the number of key-value pairs in the map. O(1).
     */
    function _length(Map storage map) private view returns (uint256) {
        return map._entries.length;
    }

   /**
    * @dev Returns the key-value pair stored at position `index` in the map. O(1).
    *
    * Note that there are no guarantees on the ordering of entries inside the
    * array, and it may change when more entries are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
        require(map._entries.length > index, "EnumerableMap: index out of bounds");

        MapEntry storage entry = map._entries[index];
        return (entry._key, entry._value);
    }

    /**
     * @dev Tries to returns the value associated with `key`.  O(1).
     * Does not revert if `key` is not in the map.
     */
    function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
        uint256 keyIndex = map._indexes[key];
        if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
        return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
    }

    /**
     * @dev Returns the value associated with `key`.  O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function _get(Map storage map, bytes32 key) private view returns (bytes32) {
        uint256 keyIndex = map._indexes[key];
        require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
        return map._entries[keyIndex - 1]._value; // All indexes are 1-based
    }

    /**
     * @dev Same as {_get}, with a custom error message when `key` is not in the map.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {_tryGet}.
     */
    function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
        uint256 keyIndex = map._indexes[key];
        require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
        return map._entries[keyIndex - 1]._value; // All indexes are 1-based
    }

    // UintToAddressMap

    struct UintToAddressMap {
        Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
        return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
        return _remove(map._inner, bytes32(key));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
        return _contains(map._inner, bytes32(key));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToAddressMap storage map) internal view returns (uint256) {
        return _length(map._inner);
    }

   /**
    * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
        (bytes32 key, bytes32 value) = _at(map._inner, index);
        return (uint256(key), address(uint160(uint256(value))));
    }

    /**
     * @dev Tries to returns the value associated with `key`.  O(1).
     * Does not revert if `key` is not in the map.
     *
     * _Available since v3.4._
     */
    function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
        (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
        return (success, address(uint160(uint256(value))));
    }

    /**
     * @dev Returns the value associated with `key`.  O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
        return address(uint160(uint256(_get(map._inner, bytes32(key)))));
    }

    /**
     * @dev Same as {get}, with a custom error message when `key` is not in the map.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryGet}.
     */
    function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
        return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
    }
}

File 29 of 33 : Strings.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    /**
     * @dev Converts a `uint256` to its ASCII `string` representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        uint256 index = digits - 1;
        temp = value;
        while (temp != 0) {
            buffer[index--] = bytes1(uint8(48 + temp % 10));
            temp /= 10;
        }
        return string(buffer);
    }
}

File 30 of 33 : ECDSA.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        // Check the signature length
        if (signature.length != 65) {
            revert("ECDSA: invalid signature length");
        }

        // Divide the signature in r, s and v variables
        bytes32 r;
        bytes32 s;
        uint8 v;

        // ecrecover takes the signature parameters, and the only way to get them
        // currently is to use assembly.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            r := mload(add(signature, 0x20))
            s := mload(add(signature, 0x40))
            v := byte(0, mload(add(signature, 0x60)))
        }

        return recover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
        require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        require(signer != address(0), "ECDSA: invalid signature");

        return signer;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * replicates the behavior of the
     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
     * JSON-RPC method.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }
}

File 31 of 33 : Ownable.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <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 () internal {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

File 32 of 33 : Clones.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address master) internal returns (address instance) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, master))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create(0, ptr, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `master` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, master))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create2(0, ptr, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, master))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
            mstore(add(ptr, 0x38), shl(0x60, deployer))
            mstore(add(ptr, 0x4c), salt)
            mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
            predicted := keccak256(add(ptr, 0x37), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
        return predictDeterministicAddress(master, salt, address(this));
    }
}

File 33 of 33 : PowerSwitch.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

interface IPowerSwitch {
    /* admin events */

    event PowerOn();
    event PowerOff();
    event EmergencyShutdown();

    /* data types */

    enum State {Online, Offline, Shutdown}

    /* admin functions */

    function powerOn() external;

    function powerOff() external;

    function emergencyShutdown() external;

    /* view functions */

    function isOnline() external view returns (bool status);

    function isOffline() external view returns (bool status);

    function isShutdown() external view returns (bool status);

    function getStatus() external view returns (State status);

    function getPowerController() external view returns (address controller);
}

/// @title PowerSwitch
/// @notice Standalone pausing and emergency stop functionality
contract PowerSwitch is IPowerSwitch, Ownable {
    /* storage */

    IPowerSwitch.State private _status;

    /* initializer */

    constructor(address owner) {
        // sanity check owner
        require(owner != address(0), "PowerSwitch: invalid owner");
        // transfer ownership
        Ownable.transferOwnership(owner);
    }

    /* admin functions */

    /// @notice Turn Power On
    /// access control: only admin
    /// state machine: only when offline
    /// state scope: only modify _status
    /// token transfer: none
    function powerOn() external override onlyOwner {
        require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on");
        _status = IPowerSwitch.State.Online;
        emit PowerOn();
    }

    /// @notice Turn Power Off
    /// access control: only admin
    /// state machine: only when online
    /// state scope: only modify _status
    /// token transfer: none
    function powerOff() external override onlyOwner {
        require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off");
        _status = IPowerSwitch.State.Offline;
        emit PowerOff();
    }

    /// @notice Shutdown Permanently
    /// access control: only admin
    /// state machine:
    /// - when online or offline
    /// - can only be called once
    /// state scope: only modify _status
    /// token transfer: none
    function emergencyShutdown() external override onlyOwner {
        require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown");
        _status = IPowerSwitch.State.Shutdown;
        emit EmergencyShutdown();
    }

    /* getter functions */

    function isOnline() external view override returns (bool status) {
        return _status == State.Online;
    }

    function isOffline() external view override returns (bool status) {
        return _status == State.Offline;
    }

    function isShutdown() external view override returns (bool status) {
        return _status == State.Shutdown;
    }

    function getStatus() external view override returns (IPowerSwitch.State status) {
        return _status;
    }

    function getPowerController() external view override returns (address controller) {
        return Ownable.owner();
    }
}

Settings
{
  "evmVersion": "istanbul",
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract ABI

[{"inputs":[{"internalType":"address","name":"adminAddress","type":"address"},{"internalType":"address","name":"rewardPoolFactory","type":"address"},{"internalType":"address","name":"powerSwitchFactory","type":"address"},{"internalType":"address","name":"rewardTokenAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":true,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminshipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"rewardPool","type":"address"},{"indexed":false,"internalType":"address","name":"powerSwitch","type":"address"}],"name":"ArbiStakerERC20Created","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ArbiStakerERC20Funded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"BonusTokenRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"BonusTokenRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"vault","type":"address"}],"name":"RageQuit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"name","type":"string"},{"indexed":true,"internalType":"address","name":"template","type":"address"}],"name":"RewardCalcTemplateActive","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"name","type":"string"},{"indexed":true,"internalType":"address","name":"template","type":"address"}],"name":"RewardCalcTemplateAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"vaultFactory","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"vault","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"vault","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Unstaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"factory","type":"address"}],"name":"VaultFactoryRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"factory","type":"address"}],"name":"VaultFactoryRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"VestedRewardClaimed","type":"event"},{"inputs":[],"name":"EARLY_ADOPTER","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EARLY_ADOPTER_LM_REWARD_MULTIPLIER_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EARLY_ADOPTER_LM_REWARD_MULTIPLIER_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INNOVATOR","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INNOVATOR_LM_REWARD_MULTIPLIER_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INNOVATOR_LM_REWARD_MULTIPLIER_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LM_REWARD_VESTING_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LM_REWARD_VESTING_PORTION_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LM_REWARD_VESTING_PORTION_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_BONUS_TOKENS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TOKENS_STAKED_PER_VAULT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PIONNER","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PIONNER_LM_REWARD_MULTIPLIER_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PIONNER_LM_REWARD_MULTIPLIER_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECURSOR","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECURSOR_LM_REWARD_MULTIPLIER_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECURSOR_LM_REWARD_MULTIPLIER_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STANDARD","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STANDARD_LM_REWARD_MULTIPLIER_DENOM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STANDARD_LM_REWARD_MULTIPLIER_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activeRewardCalcTemplate","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"lmToken","type":"address"},{"internalType":"address","name":"bonusToken","type":"address"},{"internalType":"uint256","name":"bonusTokenAmount","type":"uint256"}],"name":"addBonusTokenToLMRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"template","type":"address"}],"name":"addRewardCalcTemplate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"numVests","type":"uint256"}],"name":"claimVestedReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimVestedRewardAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"claimVestedRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"earnedLMRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"removeBonusTokenData","type":"bool"}],"name":"endLMRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"fund","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getBonusTokenAtIndex","outputs":[{"internalType":"address","name":"bonusToken","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBonusTokenSetLength","outputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getLMRewardBonusTokenAt","outputs":[{"internalType":"address","name":"bonusToken","type":"address"},{"internalType":"uint256","name":"bonusTokenAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getLMRewardBonusTokensLength","outputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getLMRewardData","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"address","name":"rewardCalcInstance","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getLMRewardVestingData","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"startedAt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"nftId","type":"uint256"},{"internalType":"address","name":"nftFactory","type":"address"}],"name":"getNftTier","outputs":[{"internalType":"string","name":"tier","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"nftFactory","type":"address"}],"name":"getNftsOfOwner","outputs":[{"internalType":"uint256[]","name":"nftIds","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNumRewardCalcTemplates","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNumTokensStaked","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"}],"name":"getNumTokensStakedInVault","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNumVaults","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getNumVestingLMTokenRewards","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"getNumVests","outputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPowerController","outputs":[{"internalType":"address","name":"controller","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPowerSwitch","outputs":[{"internalType":"address","name":"powerSwitch","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getTokenStakedAt","outputs":[{"internalType":"address","name":"token","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getVaultAt","outputs":[{"internalType":"address","name":"vault","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getVaultFactoryAtIndex","outputs":[{"internalType":"address","name":"factory","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getVaultFactorySetLength","outputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getVaultTokenAtIndex","outputs":[{"internalType":"address","name":"vaultToken","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"getVaultTokenStake","outputs":[{"internalType":"uint256","name":"tokenStake","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getVestingLMTokenAt","outputs":[{"internalType":"address","name":"token","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOffline","outputs":[{"internalType":"bool","name":"status","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOnline","outputs":[{"internalType":"bool","name":"status","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isShutdown","outputs":[{"internalType":"bool","name":"status","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"isValidAddress","outputs":[{"internalType":"bool","name":"validity","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"factory","type":"address"}],"name":"isValidVault","outputs":[{"internalType":"bool","name":"validity","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rageQuit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"bonusToken","type":"address"}],"name":"registerBonusToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"factory","type":"address"}],"name":"registerVaultFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"bonusToken","type":"address"}],"name":"removeBonusToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"factory","type":"address"}],"name":"removeVaultFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceAdminship","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"rescueTokensFromRewardPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"rewardCalcTemplateNames","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"rewardCalcTemplates","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setEarlyAdopterLMRewardMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"newImplementor","type":"address"}],"name":"setImplementorForRewardsCalculator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setInnovatorLMRewardMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setLMRewardVestingPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setLMRewardVestingPortion","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setLMRewardsPerBlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setMaxBonusTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setMaxStakesPerVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setPionnerLMRewardMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setPrecursorLMRewardMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"name","type":"string"}],"name":"setRewardCalcActiveTemplate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"numerator","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"setStandardLMRewardMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"vaultFactory","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"permission","type":"bytes"}],"name":"stakeERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"stakedTokenTotal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"}],"name":"startLMRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"string","name":"rewardCalcTemplateName","type":"string"}],"name":"startLMRewardsToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newAdmin","type":"address"}],"name":"transferAdminship","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"vaultFactory","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimBonusReward","type":"bool"},{"internalType":"bytes","name":"permission","type":"bytes"}],"name":"unstakeERC20AndClaim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"vestingLMRewards","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"startedAt","type":"uint256"}],"stateMutability":"view","type":"function"}]

608060405260066001556002805560056003556002600455600260055560016006556003600755600260085560016009556001600a5562278d00600b556001600c556002600d55600a600e55600a600f553480156200005d57600080fd5b506040516200512b3803806200512b8339810160408190526200008091620002d7565b6000826001600160a01b031663cf5ba53f86604051602001620000a4919062000333565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401620000d1919062000361565b602060405180830381600087803b158015620000ec57600080fd5b505af115801562000101573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001279190620002b3565b9050836001600160a01b031663cf5ba53f826040516020016200014b919062000333565b6040516020818303038152906040526040518263ffffffff1660e01b815260040162000178919062000361565b602060405180830381600087803b1580156200019357600080fd5b505af1158015620001a8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001ce9190620002b3565b601280546001600160a01b03199081166001600160a01b039384161790915560108054821688841617905560118054909116918416919091179055620002208162000274602090811b6200326217901c565b6012546040517f4fbfb9179e69ca41a1bfa54049eb6a0ca4f55fd463521510031e30a22268414e9162000261916001600160a01b0390911690849062000347565b60405180910390a15050505050620003b7565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b80516001600160a01b0381168114620002ae57600080fd5b919050565b600060208284031215620002c5578081fd5b620002d08262000296565b9392505050565b60008060008060808587031215620002ed578283fd5b620002f88562000296565b9350620003086020860162000296565b9250620003186040860162000296565b9150620003286060860162000296565b905092959194509250565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6000602080835283518082850152825b818110156200038f5785810183015185820160400152820162000371565b81811115620003a15783604083870101525b50601f01601f1916929092016040019392505050565b614d6480620003c76000396000f3fe608060405234801561001057600080fd5b50600436106105d75760003560e01c806378d6575a11610303578063bc5fe6d91161019c578063e7cd487f116100ee578063f6e3b7e6116100a2578063f90394371161007c578063f903943714610b17578063f935e01614610b2a578063f935e1e814610b3d576105d7565b8063f6e3b7e614610aff578063f7c618c114610b07578063f851a44014610b0f576105d7565b8063ef12120c116100d3578063ef12120c14610ad1578063f229cea614610ad9578063f4c7afa214610aec576105d7565b8063e7cd487f14610ab6578063e86d3b4714610ac9576105d7565b8063d92acb4811610150578063e567aa1d1161012a578063e567aa1d14610a88578063e601446f14610a9b578063e78d3ee214610aa3576105d7565b8063d92acb4814610a65578063d94d843a14610a78578063e2bb9c0f14610a80576105d7565b8063be4445d411610181578063be4445d414610a29578063bf86d69014610a3c578063d0b29f2b14610a44576105d7565b8063bc5fe6d914610a0e578063bcaedade14610a21576105d7565b80638e0ef636116102555780639bed25d811610209578063a96f12b6116101e3578063a96f12b6146109e0578063aa29057b146109f3578063b0ccbf8c14610a06576105d7565b80639bed25d8146109b2578063a001145a146109ba578063a2784f54146109cd576105d7565b8063968618aa1161023a578063968618aa1461098457806397378a021461098c57806399493c511461099f576105d7565b80638e0ef6361461095e57806390f51a3314610971576105d7565b80638531a636116102b75780638a633df6116102915780638a633df61461093b5780638b1c69e7146109435780638d7e431b1461094b576105d7565b80638531a63614610918578063857a02aa14610920578063891d613214610933576105d7565b80637b1837de116102e85780637b1837de146108df5780637c0c17b2146108f2578063838b8cf514610905576105d7565b806378d6575a146108b95780637a98742d146108cc576105d7565b806337fa9126116104755780635bc2a18c116103c7578063664ab18e1161037b5780636f6b108b116103555780636f6b108b146108965780637221ba661461089e578063766f13bc146108b1576105d7565b8063664ab18e1461086357806366666aa91461086b5780636b1141b514610873576105d7565b8063636e78fe116103ac578063636e78fe1461084b578063643cd8781461085357806365bbaf311461085b576105d7565b80635bc2a18c146108255780635be7cc1614610838576105d7565b80634e2388b9116104295780635431320e116104035780635431320e146107ec578063586b2b99146107ff578063589a079c14610812576105d7565b80634e2388b9146107c95780634eb40698146107d1578063508a1cba146107d9576105d7565b8063447ed4291161045a578063447ed429146107905780634890b3b7146107a35780634dd878d9146107b6576105d7565b806337fa912614610780578063438cae7e14610788576105d7565b80630ec52dd11161052e5780631f1b6538116104e25780632ee0b2bc116104bc5780632ee0b2bc1461075257806330267b231461076557806332c3dce514610778576105d7565b80631f1b6538146107225780632cab36831461072a5780632d9c0ce41461074a576105d7565b806313254de01161051357806313254de0146106e9578063155c9ed4146106fc5780631644fdaf1461070f576105d7565b80630ec52dd1146106ce5780630ed88bae146106e1576105d7565b806308fef60d116105905780630ca6d92f1161056a5780630ca6d92f146106935780630dc9e5cb1461069b5780630e1e91e7146106bb576105d7565b806308fef60d146106575780630955c04a1461065f5780630a16167214610680576105d7565b806304bd2583116105c157806304bd25831461061a5780630513247b1461062d57806306cd734714610642576105d7565b80623f07fa146105dc57806303aaee1114610605575b600080fd5b6105ef6105ea366004613ddc565b610b45565b6040516105fc9190614333565b60405180910390f35b61060d610bb8565b6040516105fc9190614c45565b61060d610628366004613df6565b610bc9565b61064061063b366004613ddc565b610be6565b005b61064a610c58565b6040516105fc919061433e565b61060d610c7d565b61067261066d366004613f45565b610c83565b6040516105fc929190614c4e565b61064061068e366004613ddc565b610d15565b61060d610d4f565b6106ae6106a9366004613fb6565b610d55565b6040516105fc919061422e565b6106406106c936600461418f565b610d83565b6106406106dc366004613df6565b610d90565b61060d610e64565b6106406106f7366004613e28565b610e6a565b61064061070a3660046140c2565b611512565b61064061071d3660046141e1565b6115e8565b61060d6115fb565b61073d610738366004613df6565b611601565b6040516105fc91906142ef565b61060d611797565b610640610760366004613ddc565b61179d565b61064061077336600461418f565b6117fb565b61060d611808565b61064061180e565b6105ef611891565b61064061079e366004613ddc565b611911565b6106ae6107b1366004613fb6565b61196f565b6106ae6107c436600461418f565b611990565b61060d61199d565b61064a6119a9565b6106406107e7366004613fb6565b6119cc565b6106ae6107fa36600461418f565b611c3f565b61064061080d3660046141e1565b611c4c565b610640610820366004613ec8565b611c5f565b6106406108333660046141e1565b612037565b610640610846366004613ddc565b61204a565b61060d6120d4565b61060d6120da565b61060d6120e6565b6105ef6120ec565b6106ae61213b565b610886610881366004613ddc565b61214a565b6040516105fc9493929190614c5c565b61060d612180565b6106406108ac3660046141e1565b612186565b6106ae612199565b6106726108c7366004613f45565b6121e8565b6106ae6108da36600461418f565b612232565b6106406108ed366004613fb6565b61223f565b61064a6109003660046141bf565b6122dd565b61060d610913366004613df6565b612498565b6106ae6124c3565b61064061092e3660046141e1565b6124d2565b61060d6124e5565b61060d6124eb565b61064a6124f1565b61060d610959366004613ddc565b61251a565b61064061096c366004613ddc565b61253e565b61060d61097f366004613ddc565b6125d0565b61060d6125f4565b61060d61099a366004613df6565b6125fa565b6106ae6109ad36600461418f565b612625565b610640612632565b6106406109c8366004613f80565b612684565b6106406109db3660046141e1565b612783565b6106406109ee366004613fdf565b612796565b610640610a0136600461418f565b612830565b61064061283d565b610640610a1c366004613fb6565b6129cc565b61064a612ac3565b6106ae610a37366004614154565b612ae7565b6105ef612b0d565b610a57610a52366004613fb6565b612b5c565b6040516105fc929190614266565b610640610a73366004614011565b612bdb565b61064a612d3c565b61060d612d61565b610640610a96366004614102565b612d6d565b61060d612ef6565b61064a610ab136600461418f565b612efc565b61060d610ac4366004613ddc565b612fa5565b61064a612fb7565b61060d613012565b61060d610ae7366004613ddc565b613018565b6105ef610afa366004613df6565b613038565b61060d6130e1565b6106ae6130e7565b6106ae6130f6565b610640610b25366004613f45565b613105565b610640610b38366004613f45565b613166565b61060d61325c565b60006001600160a01b0382163014801590610b6857506001600160a01b03821615155b8015610b8257506011546001600160a01b03838116911614155b8015610b9c57506012546001600160a01b03838116911614155b8015610bb05750610bae601683613284565b155b90505b919050565b6000610bc46013613299565b905090565b601e60209081526000928352604080842090915290825290205481565b610bee6132a4565b610bf96018826132d0565b610c1e5760405162461bcd60e51b8152600401610c15906145e5565b60405180910390fd5b7f040b321f0ccd1b9d7890282c99da1d97cbf2de30c3af0782aba31fbd9528324381604051610c4d919061422e565b60405180910390a150565b60405180604001604052806009815260200168282922a1aaa929a7a960b91b81525081565b60065481565b6001600160a01b038084166000908152601f602090815260408083209386168352929052908120805482919084908110610cb957fe5b600091825260208083206002909202909101546001600160a01b038089168452601f83526040808520918916855292529120805485908110610cf757fe5b90600052602060002090600202016001015491509150935093915050565b610d1d6132e5565b336000908152601f602090815260408083206001600160a01b0385168452909152902054610d4c9082906119cc565b50565b60015481565b6001600160a01b0382166000908152601560205260408120610d7a906001018361333e565b90505b92915050565b610d8b6132a4565b600e55565b610d986132a4565b6001600160a01b0382166000908152601d6020526040902060020154610dd05760405162461bcd60e51b8152600401610c15906149e0565b6001600160a01b038083166000908152601d6020526040908190206003015490517fbb0842f9000000000000000000000000000000000000000000000000000000008152911690819063bb0842f990610e2d90859060040161422e565b600060405180830381600087803b158015610e4757600080fd5b505af1158015610e5b573d6000803e3d6000fd5b50505050505050565b600e5481565b610e726132e5565b610e7d601389613284565b610e995760405162461bcd60e51b8152600401610c1590614972565b6001600160a01b038816600090815260156020526040902084610ece5760405162461bcd60e51b8152600401610c1590614588565b610ed787610b45565b610ef35760405162461bcd60e51b8152600401610c1590614642565b610f006001820187613284565b610f1c5760405162461bcd60e51b8152600401610c1590614497565b6001600160a01b038616600090815260208290526040902054851115610f545760405162461bcd60e51b8152600401610c1590614915565b6001600160a01b0386166000908152601c6020526040902054851115610f8c5760405162461bcd60e51b8152600401610c15906147c7565b336000908152601e602090815260408083206001600160a01b038a168452825280832054601d9092529091206002015415611085576001600160a01b038088166000908152601d60205260408082206003015490517f4afa66d60000000000000000000000000000000000000000000000000000000081529216918290634afa66d69061101f9033908c90600401614266565b606060405180830381600087803b15801561103957600080fd5b505af115801561104d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611071919061408c565b5091506110809050838261334a565b925050505b6001600160a01b0387166000908152602083905260409020546110a890876133a4565b6001600160a01b03881660009081526020849052604090208190556110ef576110d460018301886132d0565b506001600160a01b0387166000908152602083905260408120555b6001600160a01b0387166000908152601c602052604090205461111290876133a4565b6001600160a01b0388166000908152601c602052604090208190556111575761113c601a886132d0565b506001600160a01b0387166000908152601c60205260408120555b6040517fc8bf29a90000000000000000000000000000000000000000000000000000000081526001600160a01b038b169063c8bf29a9906111a2908a908a90899089906004016142a9565b600060405180830381600087803b1580156111bc57600080fd5b505af11580156111d0573d6000803e3d6000fd5b505050507f0f5bb82176feb1b5e747e28471aa92156a04d9f3ab9f45f28e2d704232b93f758a87604051611205929190614266565b60405180910390a180156115065784801561123a57506001600160a01b0387166000908152601d602052604090206002015415155b156113885760005b6001600160a01b0388166000908152601d6020526040902061126690600401613299565b811015611386576001600160a01b0388166000908152601d60205260408120611292906004018361333e565b6001600160a01b03808b166000908152601d6020908152604080832080549486168452600601909152812054929350916112d891906112d2908790613401565b9061345a565b6012546040516323e5d69960e21b81529192506001600160a01b031690638f975a649061130d9085908f908690600401614242565b600060405180830381600087803b15801561132757600080fd5b505af115801561133b573d6000803e3d6000fd5b505050507f2422cac5e23c46c890fdcf42d0c64757409df6832174df639337558f09d99c688d8c8484604051611374949392919061427f565b60405180910390a15050600101611242565b505b600061139e8b6001600160a01b03168b846134c1565b905060006113bd600d546112d2600c548561340190919063ffffffff16565b336000818152601f602090815260408083206001600160a01b038f168452825280832081518083018352868152428185019081528254600181810185559387528587209251600290910290920191825551910155928252805220909150611424908a613719565b50336000908152601e602090815260408083206001600160a01b038d81168552925282209190915560125460115490821691638f975a6491168c61146886866133a4565b6040518463ffffffff1660e01b815260040161148693929190614242565b600060405180830381600087803b1580156114a057600080fd5b505af11580156114b4573d6000803e3d6000fd5b50506011546040517f2422cac5e23c46c890fdcf42d0c64757409df6832174df639337558f09d99c6893506114fb92508f918e916001600160a01b0390911690889061427f565b60405180910390a150505b50505050505050505050565b61151a6132a4565b60006001600160a01b031660228383604051611537929190614202565b908152604051908190036020019020546001600160a01b0316141561156e5760405162461bcd60e51b8152600401610c15906149a9565b61157a60238383613c55565b506022828260405161158d929190614202565b908152604051908190036020018120546001600160a01b0316906115b49084908490614202565b604051908190038120907f512a5fdf5985b6c25e3b3be26ae9fb57e01ada0858b870a99ede17b652e104da90600090a35050565b6115f06132a4565b600391909155600455565b600d5481565b60606000826001600160a01b03166370a08231856040518263ffffffff1660e01b8152600401611631919061422e565b60206040518083038186803b15801561164957600080fd5b505afa15801561165d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061168191906141a7565b90508067ffffffffffffffff8111801561169a57600080fd5b506040519080825280602002602001820160405280156116c4578160200160208202803683370190505b50915060005b8181101561178f576040517f2f745c590000000000000000000000000000000000000000000000000000000081526000906001600160a01b03861690632f745c599061171c9089908690600401614266565b60206040518083038186803b15801561173457600080fd5b505afa158015611748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176c91906141a7565b90508084838151811061177b57fe5b6020908102919091010152506001016116ca565b505092915050565b60035481565b6117a56132a4565b6117b0601882613719565b6117cc5760405162461bcd60e51b8152600401610c1590614a9a565b7f059b5054f04b000050b3cbdf0ad2d8bce0dfca886836a4742ab837cc948cd1af81604051610c4d919061422e565b6118036132a4565b600b55565b60095481565b6118166132e5565b336000908152602080526040812061182d90613299565b905060005b8181101561188d573360009081526020805260408120611852908361333e565b336000908152601f602090815260408083206001600160a01b03851684529091529020549091506118849082906119cc565b50600101611832565b5050565b60008060009054906101000a90046001600160a01b03166001600160a01b031663438cae7e6040518163ffffffff1660e01b815260040160206040518083038186803b1580156118e057600080fd5b505afa1580156118f4573d6000803e3d6000fd5b505050506040513d602081101561190a57600080fd5b5051905090565b6119196132a4565b6119246016826132d0565b6119405760405162461bcd60e51b8152600401610c159061469f565b7fc8db8c20f7ca9f01bf59db26d6be7a30614f45354c1b050c8ce5d8986cab9e0c81604051610c4d919061422e565b6001600160a01b03821660009081526020805260408120610d7a908361333e565b6000610bb060168361333e565b6000610bc4601a613299565b604051806040016040528060078152602001662824a7a72722a960c91b81525081565b6119d46132e5565b336000908152601f602090815260408083206001600160a01b0386168452909152902054811115611a175760405162461bcd60e51b8152600401610c15906146fc565b336000908152601f602090815260408083206001600160a01b0386168452909152812090805b83811015611b80576000838281548110611a5357fe5b906000526020600020906002020190506000611a7c8260010154426133a490919063ffffffff16565b90506000611a9d600b546112d284866000015461340190919063ffffffff16565b83549091508110611b5657508154855486906000198101908110611abd57fe5b9060005260206000209060020201868581548110611ad757fe5b6000918252602090912082546002909202019081556001918201549101558554869080611b0057fe5b6000828152602081206000199283016002810290910182815560010191909155909155865497810197940193611b51573360009081526020805260409020611b4890896132d0565b50505050611b80565b611b65565b8254611b6290826133a4565b83555b611b6f858261334a565b94505060019092019150611a3d9050565b508015611c39576012546011546040516323e5d69960e21b81526001600160a01b0392831692638f975a6492611bbf9291169033908690600401614242565b600060405180830381600087803b158015611bd957600080fd5b505af1158015611bed573d6000803e3d6000fd5b50506011546040517f39db3bad855b0ce17d962982f25b626918ed5b60587c0b497606c1f1fbc220aa9350611c30925033916001600160a01b0316908590614242565b60405180910390a15b50505050565b6000610bb0601a8361333e565b611c546132a4565b600591909155600655565b611c676132e5565b611c718686613038565b611c8d5760405162461bcd60e51b8152600401610c1590614af7565b82611caa5760405162461bcd60e51b8152600401610c1590614bb1565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815283906001600160a01b038616906370a0823190611cf190339060040161422e565b60206040518083038186803b158015611d0957600080fd5b505afa158015611d1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d4191906141a7565b1015611d5f5760405162461bcd60e51b8152600401610c1590614790565b611d6a601387613719565b506001600160a01b0386166000908152601560205260409020600e54611d9260018301613299565b10611daf5760405162461bcd60e51b8152600401610c1590614405565b611dbc6001820186613719565b506001600160a01b038516600090815260208290526040902054611de0908561334a565b6001600160a01b038616600090815260208390526040902055611e04601a86613719565b506001600160a01b0385166000908152601c6020526040902054611e28908561334a565b6001600160a01b0386166000908152601c6020526040902055611e4d8533898761372e565b6040517f949e31100000000000000000000000000000000000000000000000000000000081526001600160a01b0388169063949e311090611e989088908890889088906004016142a9565b600060405180830381600087803b158015611eb257600080fd5b505af1158015611ec6573d6000803e3d6000fd5b505050506001600160a01b0385166000908152601d602052604090206002015415611ff5576001600160a01b038086166000908152601d60205260408082206003015490517f36f04e4500000000000000000000000000000000000000000000000000000000815292169182906336f04e4590611f499033908a90600401614266565b606060405180830381600087803b158015611f6357600080fd5b505af1158015611f77573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9b919061408c565b50336000908152601e602090815260408083206001600160a01b038d168452909152902054909250611fce91508261334a565b336000908152601e602090815260408083206001600160a01b038c16845290915290205550505b7f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d8785604051612026929190614266565b60405180910390a150505050505050565b61203f6132a4565b600c91909155600d55565b6120526132a4565b6001600160a01b0381166120785760405162461bcd60e51b8152600401610c1590614462565b6010546040516001600160a01b038084169216907f2931ebb3d190545dcf6801c37aa686b74f2e1000e753d0fac6e471a2aa5a621390600090a3601080546001600160a01b0319166001600160a01b0392909216919091179055565b60075481565b6000610bc46018613299565b60085481565b60008060009054906101000a90046001600160a01b03166001600160a01b031663664ab18e6040518163ffffffff1660e01b815260040160206040518083038186803b1580156118e057600080fd5b6012546001600160a01b031681565b6001600160a01b039081166000908152601d60205260409020805460018201546002830154600390930154919490939190911690565b600f5481565b61218e6132a4565b600791909155600855565b60008060009054906101000a90046001600160a01b03166001600160a01b031663766f13bc6040518163ffffffff1660e01b815260040160206040518083038186803b1580156118e057600080fd5b601f602052826000526040600020602052816000526040600020818154811061221057600080fd5b6000918252602090912060029091020180546001909101549093509150839050565b6000610bb060138361333e565b6122476132a4565b612252601683613284565b8061226a57506011546001600160a01b038381169116145b6122865760405162461bcd60e51b8152600401610c1590614b54565b6012546122a090839033906001600160a01b03168461372e565b7f37f4630fe7d7bcd5bcf6f5764fe0fe6671aaeaaf8cc9de8a77e4b568841e83df82826040516122d1929190614266565b60405180910390a15050565b60606000826001600160a01b03166363b6c375856040518263ffffffff1660e01b815260040161230d9190614c45565b60206040518083038186803b15801561232557600080fd5b505afa158015612339573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061235d91906141a7565b9050600181101580156123715750600a8111155b1561239d57604051806040016040528060078152602001662824a7a72722a960c91b8152509150612491565b600b81101580156123af575060648111155b156123dd5760405180604001604052806009815260200168282922a1aaa929a7a960b91b8152509150612491565b606581101580156123f057506101f48111155b1561241e576040518060400160405280600981526020016824a72727ab20aa27a960b91b8152509150612491565b6101f5811015801561243257506103e88111155b15612464576040518060400160405280600d81526020016c22a0a9262cafa0a227a82a22a960991b8152509150612491565b6103e98110612491576040518060400160405280600881526020016714d510539110549160c21b81525091505b5092915050565b6001600160a01b03918216600090815260156020908152604080832093909416825291909152205490565b6000546001600160a01b031690565b6124da6132a4565b600991909155600a55565b600c5481565b600b5481565b6040518060400160405280600d81526020016c22a0a9262cafa0a227a82a22a960991b81525081565b6001600160a01b0381166000908152601560205260408120610bb090600101613299565b6125466132a4565b61254f81610b45565b61256b5760405162461bcd60e51b8152600401610c1590614371565b600f546125786016613299565b106125955760405162461bcd60e51b8152600401610c1590614a3d565b6125a0601682613719565b507fbca954c637e20d265d501f3c0c9d0df1440001376c36ac73bd296c1a628f528c81604051610c4d919061422e565b6001600160a01b0381166000908152601d60205260408120610bb090600401613299565b60025481565b6001600160a01b039182166000908152601f6020908152604080832093909416825291909152205490565b6000610bb060188361333e565b61263a6132a4565b6010546040516000916001600160a01b0316907f2931ebb3d190545dcf6801c37aa686b74f2e1000e753d0fac6e471a2aa5a6213908390a3601080546001600160a01b0319169055565b61268c6132a4565b6001600160a01b0382166000908152601d6020526040812081815560018101829055600281019190915560030180546001600160a01b0319169055801561188d5760005b6001600160a01b0383166000908152601d602052604090206126f490600401613299565b81101561277e576001600160a01b0383166000908152601d60205260408120612720906004018361333e565b6001600160a01b0385166000908152601d6020526040902090915061274890600401826132d0565b506001600160a01b038085166000908152601d6020908152604080832094909316825260069093019092528120556001016126d0565b505050565b61278b6132a4565b600191909155600255565b6023805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815261277e9387938793879392918301828280156128265780601f106127fb57610100808354040283529160200191612826565b820191906000526020600020905b81548152906001019060200180831161280957829003601f168201915b5050505050612bdb565b6128386132a4565b600f55565b612848601333613284565b6128645760405162461bcd60e51b8152600401610c1590614972565b33600090815260156020526040812090600182019061288282613299565b1161289f5760405162461bcd60e51b8152600401610c1590614551565b60005b6128ab82613299565b8110156129695760006128be838361333e565b90506128ca83826132d0565b506001600160a01b03811660009081526020858152604080832054601c9092528220549091906128fa90836133a4565b90508061292b5761290c601a846132d0565b506001600160a01b0383166000908152601c6020526040812055612947565b6001600160a01b0383166000908152601c602052604090208190555b50506001600160a01b03166000908152602084905260408120556001016128a2565b506129756013336132d0565b5033600090815260156020526040812090600182018181816129978282613ce1565b5050505050507f0c01085b5358e7ac314990249afd110d83037861ffb61c449ca17c7926b9d9ab336040516122d1919061422e565b6129d46132e5565b6129dc6132a4565b6001600160a01b0382166000908152601d6020526040902060020154612a145760405162461bcd60e51b8152600401610c15906149e0565b6001600160a01b038083166000908152601d6020526040908190206003015490517f7b381b350000000000000000000000000000000000000000000000000000000081529116908190637b381b3590612a71908590600401614c45565b602060405180830381600087803b158015612a8b57600080fd5b505af1158015612a9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c399190614070565b6040518060400160405280600881526020016714d510539110549160c21b81525081565b80516020818301810180516022825292820191909301209152546001600160a01b031681565b60008060009054906101000a90046001600160a01b03166001600160a01b031663bf86d6906040518163ffffffff1660e01b815260040160206040518083038186803b1580156118e057600080fd5b6001600160a01b0382166000908152601d602052604081208190612b83906004018461333e565b6001600160a01b0385166000908152601d60205260408120600681019190612bae906004018761333e565b6001600160a01b03166001600160a01b0316815260200190815260200160002054915091505b9250929050565b612be36132a4565b6001600160a01b0384166000908152601d602052604090206002015415612c1c5760405162461bcd60e51b8152600401610c15906148b8565b60006001600160a01b0316602282604051612c379190614212565b908152604051908190036020019020546001600160a01b03161415612c6e5760405162461bcd60e51b8152600401610c15906144f4565b6000612cf6602283604051612c839190614212565b908152604080519182900360209081018320546004845260248401909252820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f8129fc1c000000000000000000000000000000000000000000000000000000001790526001600160a01b0316906138b8565b6001600160a01b039586166000908152601d6020526040902094855560018501939093555050426002830155600390910180546001600160a01b03191691909216179055565b6040518060400160405280600981526020016824a72727ab20aa27a960b91b81525081565b6000610bc46016613299565b612d756132a4565b60006001600160a01b031660228484604051612d92929190614202565b908152604051908190036020019020546001600160a01b031614612dc85760405162461bcd60e51b8152600401610c1590614c0e565b8060228484604051612ddb929190614202565b90815260405190819003602001902080546001600160a01b03929092166001600160a01b0319909216919091179055602154612e6957612e1d60238484613c55565b50806001600160a01b03168383604051612e38929190614202565b604051908190038120907f512a5fdf5985b6c25e3b3be26ae9fb57e01ada0858b870a99ede17b652e104da90600090a35b60218054600181018255600091909152612ea6907f3a6357012c1a3ae0a17d304c9920310382d968ebcc4b1771f41c6b304205b570018484613c55565b50806001600160a01b03168383604051612ec1929190614202565b604051908190038120907f2ed629fe351d78c132bd54e9e53965bd1cbdd0cc478bc915448fae9e5fd02a6b90600090a3505050565b600a5481565b60218181548110612f0c57600080fd5b600091825260209182902001805460408051601f6002600019610100600187161502019094169390930492830185900485028101850190915281815293509091830182828015612f9d5780601f10612f7257610100808354040283529160200191612f9d565b820191906000526020600020905b815481529060010190602001808311612f8057829003601f168201915b505050505081565b601c6020526000908152604090205481565b6023805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015612f9d5780601f10612f7257610100808354040283529160200191612f9d565b60055481565b6001600160a01b03811660009081526020805260408120610bb090613299565b6000613045601883613284565b8015610d7a57506040517f6b44e6be0000000000000000000000000000000000000000000000000000000081526001600160a01b03831690636b44e6be9061309190869060040161422e565b60206040518083038186803b1580156130a957600080fd5b505afa1580156130bd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d7a9190614070565b60215490565b6011546001600160a01b031681565b6010546001600160a01b031681565b61310d6132a4565b61311682610b45565b6131325760405162461bcd60e51b8152600401610c1590614881565b6012546040516323e5d69960e21b81526001600160a01b0390911690638f975a6490610e2d90869086908690600401614242565b61316e6132a4565b6001600160a01b0383166000908152601d60205260409020600201546131a65760405162461bcd60e51b8152600401610c1590614824565b6131b1601683613284565b6131cd5760405162461bcd60e51b8152600401610c15906143ce565b6001600160a01b0383166000908152601d602052604090206131f29060040183613719565b506001600160a01b038084166000908152601d602090815260408083209386168352600690930190522054613227908261334a565b6001600160a01b039384166000908152601d602090815260408083209590961682526006909401909352929091209190915550565b60045481565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000610d7a836001600160a01b038416613a0a565b6000610bb082613a22565b6010546001600160a01b031633146132ce5760405162461bcd60e51b8152600401610c1590614759565b565b6000610d7a836001600160a01b038416613a26565b6132ed6120ec565b6132ce576040805162461bcd60e51b815260206004820152601660248201527f506f77657265643a206973206e6f74206f6e6c696e6500000000000000000000604482015290519081900360640190fd5b6000610d7a8383613aec565b600082820183811015610d7a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6000828211156133fb576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b60008261341057506000610d7d565b8282028284828161341d57fe5b0414610d7a5760405162461bcd60e51b8152600401808060200182810382526021815260200180614d0e6021913960400191505060405180910390fd5b60008082116134b0576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b8183816134b957fe5b049392505050565b6000806134ce85856122dd565b90506000816040516020016134e39190614212565b60408051601f198184030181528282528051602091820120838301835260078452662824a7a72722a960c91b848301529151919350613523929101614212565b604051602081830303815290604052805190602001208114156135625761355b6002546112d26001548761340190919063ffffffff16565b9250613710565b60405180604001604052806009815260200168282922a1aaa929a7a960b91b8152506040516020016135949190614212565b604051602081830303815290604052805190602001208114156135cc5761355b6004546112d26003548761340190919063ffffffff16565b6040518060400160405280600981526020016824a72727ab20aa27a960b91b8152506040516020016135fe9190614212565b604051602081830303815290604052805190602001208114156136365761355b6006546112d26005548761340190919063ffffffff16565b6040518060400160405280600d81526020016c22a0a9262cafa0a227a82a22a960991b81525060405160200161366c9190614212565b604051602081830303815290604052805190602001208114156136a45761355b6008546112d26007548761340190919063ffffffff16565b6040518060400160405280600881526020016714d510539110549160c21b8152506040516020016136d59190614212565b604051602081830303815290604052805190602001208114156137105761370d600a546112d26009548761340190919063ffffffff16565b92505b50509392505050565b6000610d7a836001600160a01b038416613b50565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f23b872dd00000000000000000000000000000000000000000000000000000000178152925182516000948594938a169392918291908083835b602083106137e05780518252601f1990920191602091820191016137c1565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613842576040519150601f19603f3d011682016040523d82523d6000602084013e613847565b606091505b5091509150818015613875575080511580613875575080806020019051602081101561387257600080fd5b50515b6138b05760405162461bcd60e51b8152600401808060200182810382526031815260200180614cdd6031913960400191505060405180910390fd5b505050505050565b60006138c383613b9a565b825190915015610d7d57600080826001600160a01b0316846040518082805190602001908083835b6020831061390a5780518252601f1990920191602091820191016138eb565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461396c576040519150601f19603f3d011682016040523d82523d6000602084013e613971565b606091505b5091509150818190613a015760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156139c65781810151838201526020016139ae565b50505050905090810190601f1680156139f35780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50505092915050565b60009081526001919091016020526040902054151590565b5490565b60008181526001830160205260408120548015613ae25783546000198083019190810190600090879083908110613a5957fe5b9060005260206000200154905080876000018481548110613a7657fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080613aa657fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610d7d565b6000915050610d7d565b81546000908210613b2e5760405162461bcd60e51b8152600401808060200182810382526022815260200180614cbb6022913960400191505060405180910390fd5b826000018281548110613b3d57fe5b9060005260206000200154905092915050565b6000613b5c8383613a0a565b613b9257508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610d7d565b506000610d7d565b60006040517f3d602d80600a3d3981f3363d3d373d3d3d363d7300000000000000000000000081528260601b60148201527f5af43d82803e903d91602b57fd5bf3000000000000000000000000000000000060288201526037816000f09150506001600160a01b038116610bb3576040805162461bcd60e51b815260206004820152601660248201527f455243313136373a20637265617465206661696c656400000000000000000000604482015290519081900360640190fd5b828054600181600116156101000203166002900490600052602060002090601f016020900481019282613c8b5760008555613cd1565b82601f10613ca45782800160ff19823516178555613cd1565b82800160010185558215613cd1579182015b82811115613cd1578235825591602001919060010190613cb6565b50613cdd929150613cfb565b5090565b5080546000825590600052602060002090810190610d4c91905b5b80821115613cdd5760008155600101613cfc565b80356001600160a01b0381168114610bb357600080fd5b60008083601f840112613d38578182fd5b50813567ffffffffffffffff811115613d4f578182fd5b602083019150836020828501011115612bd457600080fd5b600082601f830112613d77578081fd5b813567ffffffffffffffff80821115613d8c57fe5b604051601f8301601f191681016020018281118282101715613daa57fe5b604052828152848301602001861015613dc1578384fd5b82602086016020830137918201602001929092529392505050565b600060208284031215613ded578081fd5b610d7a82613d10565b60008060408385031215613e08578081fd5b613e1183613d10565b9150613e1f60208401613d10565b90509250929050565b60008060008060008060008060e0898b031215613e43578384fd5b613e4c89613d10565b9750613e5a60208a01613d10565b9650613e6860408a01613d10565b9550613e7660608a01613d10565b94506080890135935060a0890135613e8d81614cac565b925060c089013567ffffffffffffffff811115613ea8578283fd5b613eb48b828c01613d27565b999c989b5096995094979396929594505050565b60008060008060008060a08789031215613ee0578182fd5b613ee987613d10565b9550613ef760208801613d10565b9450613f0560408801613d10565b935060608701359250608087013567ffffffffffffffff811115613f27578283fd5b613f3389828a01613d27565b979a9699509497509295939492505050565b600080600060608486031215613f59578283fd5b613f6284613d10565b9250613f7060208501613d10565b9150604084013590509250925092565b60008060408385031215613f92578182fd5b613f9b83613d10565b91506020830135613fab81614cac565b809150509250929050565b60008060408385031215613fc8578182fd5b613fd183613d10565b946020939093013593505050565b600080600060608486031215613ff3578283fd5b613ffc84613d10565b95602085013595506040909401359392505050565b60008060008060808587031215614026578384fd5b61402f85613d10565b93506020850135925060408501359150606085013567ffffffffffffffff811115614058578182fd5b61406487828801613d67565b91505092959194509250565b600060208284031215614081578081fd5b8151610d7a81614cac565b6000806000606084860312156140a0578081fd5b83516140ab81614cac565b602085015160409095015190969495509392505050565b600080602083850312156140d4578182fd5b823567ffffffffffffffff8111156140ea578283fd5b6140f685828601613d27565b90969095509350505050565b600080600060408486031215614116578081fd5b833567ffffffffffffffff81111561412c578182fd5b61413886828701613d27565b909450925061414b905060208501613d10565b90509250925092565b600060208284031215614165578081fd5b813567ffffffffffffffff81111561417b578182fd5b61418784828501613d67565b949350505050565b6000602082840312156141a0578081fd5b5035919050565b6000602082840312156141b8578081fd5b5051919050565b600080604083850312156141d1578182fd5b82359150613e1f60208401613d10565b600080604083850312156141f3578182fd5b50508035926020909101359150565b6000828483379101908152919050565b60008251614224818460208701614c80565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b60006001600160a01b03861682528460208301526060604083015282606083015282846080840137818301608090810191909152601f909201601f191601019392505050565b6020808252825182820181905260009190848201906040850190845b818110156143275783518352928401929184019160010161430b565b50909695505050505050565b901515815260200190565b600060208252825180602084015261435d816040850160208701614c80565b601f01601f19169190910160400192915050565b60208082526031908201527f696e76616c696420626f6e757320746f6b656e2061646472657373206f72206960408201527f7320616c72656164792070726573656e74000000000000000000000000000000606082015260800190565b6020808252601a908201527f426f6e757320746f6b656e206e6f742072656769737465726564000000000000604082015260600190565b60208082526034908201527f417262695374616b657245524332303a204d41585f544f4b454e535f5354414b60408201527f45445f5045525f5641554c542072656163686564000000000000000000000000606082015260800190565b6020808252818101527f6e65772061646d696e2063616e277420746865207a65726f2061646472657373604082015260600190565b60208082526022908201527f417262695374616b657245524332303a206e6f20746f6b656e20696e2076617560408201527f6c74000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526029908201527f5265776172642043616c63756c61746f722054656d706c61746520646f65732060408201527f6e6f742065786973740000000000000000000000000000000000000000000000606082015260800190565b60208082526019908201527f417262695374616b657245524332303a206e6f207374616b6500000000000000604082015260600190565b60208082526023908201527f417262695374616b657245524332303a206e6f20616d6f756e7420756e73746160408201527f6b65640000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526028908201527f417262695374616b65723a207661756c7420666163746f7279206e6f7420726560408201527f6769737465726564000000000000000000000000000000000000000000000000606082015260800190565b60208082526022908201527f417262695374616b657245524332303a20696e76616c6964207265636970696560408201527f6e74000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526024908201527f417262695374616b65723a20626f6e757320746f6b656e206e6f74207072657360408201527f656e742000000000000000000000000000000000000000000000000000000000606082015260800190565b6020808252602f908201527f6e756d2076657374732063616e27742062652067726561746572207468616e2060408201527f617661696c61626c652076657374730000000000000000000000000000000000606082015260800190565b6020808252600b908201527f6e6f7420616c6c6f776564000000000000000000000000000000000000000000604082015260600190565b6020808252601a908201527f696e73756666696369656e7420746f6b656e2062616c616e6365000000000000604082015260600190565b6020808252603a908201527f7374616b6564546f6b656e546f74616c5b746f6b656e5d206973206c6573732060408201527f7468616e20616d6f756e74206265696e6720756e7374616b6564000000000000606082015260800190565b60208082526032908201527f4e6f207265776172642070726f6772616d2063757272656e746c79206c69766560408201527f20666f722074686973204c4d20746f6b656e0000000000000000000000000000606082015260800190565b60208082526011908201527f696e76616c696420726563697069656e74000000000000000000000000000000604082015260600190565b6020808252602c908201527f41207265776172642070726f6772616d20616c7265616479206c69766520666f60408201527f72207468697320746f6b656e0000000000000000000000000000000000000000606082015260800190565b6020808252602f908201527f417262695374616b657245524332303a20696e73756666696369656e7420766160408201527f756c7420746f6b656e207374616b650000000000000000000000000000000000606082015260800190565b60208082526019908201527f417262695374616b657245524332303a206e6f207661756c7400000000000000604082015260600190565b60208082526017908201527f54656d706c61746520646f6573206e6f74206578697374000000000000000000604082015260600190565b6020808252602f908201527f4e6f207265776172642070726f6772616d2063757272656e746c79206c69766560408201527f20666f72207468697320746f6b656e0000000000000000000000000000000000606082015260800190565b60208082526025908201527f417262695374616b65723a206d617820626f6e757320746f6b656e732072656160408201527f6368656420000000000000000000000000000000000000000000000000000000606082015260800190565b6020808252602c908201527f417262695374616b65723a207661756c7420666163746f727920616c7265616460408201527f7920726567697374657265640000000000000000000000000000000000000000606082015260800190565b60208082526023908201527f417262695374616b657245524332303a207661756c74206973206e6f7420766160408201527f6c69640000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526023908201527f63616e6e6f742066756e64207769746820756e7265636f676e697a656420746f60408201527f6b656e0000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526021908201527f417262695374616b657245524332303a206e6f20616d6f756e74207374616b6560408201527f6400000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526017908201527f54656d706c61746520616c726561647920657869737473000000000000000000604082015260600190565b90815260200190565b918252602082015260400190565b938452602084019290925260408301526001600160a01b0316606082015260800190565b60005b83811015614c9b578181015183820152602001614c83565b83811115611c395750506000910152565b8015158114610d4c57600080fdfe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64735472616e7366657248656c7065723a3a7472616e7366657246726f6d3a207472616e7366657246726f6d206661696c6564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a264697066735822122084574eecc1540145d194311fc7dfe934b70fbf4b578309aae060391e4a3b98b564736f6c634300070600330000000000000000000000001d427f8f08cd8b40bf07f58f11acf39cf45504b0000000000000000000000000b3fc56f85ccd4d1be21a2ef01a1b7ddbe1f72664000000000000000000000000ea14fab219e02e1aaaefb521a3e1235aff5a7d2b000000000000000000000000eb6f8eebc83d85120f9299b84da558825685570e

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000001d427f8f08cd8b40bf07f58f11acf39cf45504b0000000000000000000000000b3fc56f85ccd4d1be21a2ef01a1b7ddbe1f72664000000000000000000000000ea14fab219e02e1aaaefb521a3e1235aff5a7d2b000000000000000000000000eb6f8eebc83d85120f9299b84da558825685570e

-----Decoded View---------------
Arg [0] : adminAddress (address): 0x1d427f8f08cd8b40bf07f58f11acf39cf45504b0
Arg [1] : rewardPoolFactory (address): 0xb3fc56f85ccd4d1be21a2ef01a1b7ddbe1f72664
Arg [2] : powerSwitchFactory (address): 0xea14fab219e02e1aaaefb521a3e1235aff5a7d2b
Arg [3] : rewardTokenAddress (address): 0xeb6f8eebc83d85120f9299b84da558825685570e

-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000001d427f8f08cd8b40bf07f58f11acf39cf45504b0
Arg [1] : 000000000000000000000000b3fc56f85ccd4d1be21a2ef01a1b7ddbe1f72664
Arg [2] : 000000000000000000000000ea14fab219e02e1aaaefb521a3e1235aff5a7d2b
Arg [3] : 000000000000000000000000eb6f8eebc83d85120f9299b84da558825685570e


Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.