{
  "language": "Solidity",
  "sources": {
    "contracts/election/Election.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\n\nimport '../interfaces/ICandidateElectionReward.sol';\nimport '../interfaces/IElection.sol';\n\ncontract Election is IElection, Initializable {\n\tstruct VoterInfo {\n\t\tuint256 amount;\n\t\tuint256 rewardDebt;\n\t}\n\n\tIERC20 public override token;\n\n\tICandidateElectionReward public override candidateElectionReward;\n\n\tIMajorCandidates public override majorCandidates;\n\n\tuint256 public override ACC_PRECISION;\n\n\tmapping(address => mapping(address => VoterInfo)) public voters;\n\n\tmapping(address => uint256) public override voteSupply;\n\n\tmapping(address => uint256) public accPerShares;\n\n\tmodifier onlyCandidateElectionReward() {\n\t\trequire(msg.sender == address(candidateElectionReward), 'Election: caller is not CandidateElectionReward contract');\n\t\t_;\n\t}\n\n\tfunction initialize(\n\t\tIERC20 _token,\n\t\tICandidateElectionReward _candidateElectionReward,\n\t\tIMajorCandidates _majorCandidates\n\t) external initializer {\n\t\t_setToken(_token);\n\t\t_setCandidateElectionReward(_candidateElectionReward);\n\t\t_setMajorCandidates(_majorCandidates);\n\t\tACC_PRECISION = 1e12;\n\t}\n\n\tfunction slipVote(\n\t\taddress candidate,\n\t\taddress voter,\n\t\tuint256 amount,\n\t\tuint256 slippage\n\t) external override {\n\t\trequire(candidateElectionReward.isCandidateRegistered(candidate), 'Election: nonexistent candidate');\n\t\ttoken.transferFrom(msg.sender, address(this), amount);\n\t\tcandidateElectionReward.voterClaim(candidate);\n\t\tvoters[candidate][voter].amount = voters[candidate][voter].amount + amount;\n\t\tvoters[candidate][voter].rewardDebt = voters[candidate][voter].rewardDebt + (amount * accPerShares[candidate] / ACC_PRECISION);\n\t\tvoteSupply[candidate] = voteSupply[candidate] + amount;\n\t\tmajorCandidates.slipUpdate(candidate, voteSupply[candidate], slippage);\n\n\t\temit Vote(candidate, voter, amount);\n\t}\n\n\tfunction vote(\n\t\taddress candidate,\n\t\taddress voter,\n\t\tuint256 amount,\n\t\taddress prev,\n\t\taddress next\n\t) external override {\n\t\trequire(candidateElectionReward.isCandidateRegistered(candidate), 'Election: nonexistent candidate');\n\t\ttoken.transferFrom(msg.sender, address(this), amount);\n\t\tcandidateElectionReward.voterClaim(candidate);\n\t\tvoters[candidate][voter].amount = voters[candidate][voter].amount + amount;\n\t\tvoters[candidate][voter].rewardDebt = voters[candidate][voter].rewardDebt + (amount * accPerShares[candidate] / ACC_PRECISION);\n\t\tvoteSupply[candidate] = voteSupply[candidate] + amount;\n\t\tmajorCandidates.upset(candidate, voteSupply[candidate], prev, next);\n\n\t\temit Vote(candidate, voter, amount);\n\t}\n\n\tfunction claim(address candidate, address to) external {\n\t\tcandidateElectionReward.voterClaim(candidate);\n\t\tVoterInfo storage voter = voters[candidate][msg.sender];\n\t\tuint256 accumulated = voter.amount * accPerShares[candidate] / ACC_PRECISION;\n\t\tuint256 pending = accumulated - voter.rewardDebt;\n\t\tvoter.rewardDebt = accumulated;\n\t\ttoken.transfer(to, pending);\n\t\temit Claimed(candidate, msg.sender, to, pending);\n\t}\n\n\tfunction withdrawAndClaim(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress to,\n\t\taddress prev,\n\t\taddress next\n\t) public override {\n\t\tcandidateElectionReward.voterClaim(candidate);\n\t\tVoterInfo storage voter = voters[candidate][msg.sender];\n\t\tuint256 accumulated = voter.amount * accPerShares[candidate] / ACC_PRECISION;\n\t\tuint256 pending = accumulated - voter.rewardDebt;\n\t\tvoter.rewardDebt = accumulated - (amount * accPerShares[candidate] / ACC_PRECISION);\n\t\tvoter.amount = voter.amount - amount;\n\t\tvoteSupply[candidate] = voteSupply[candidate] - amount;\n\t\tmajorCandidates.upset(candidate, voteSupply[candidate], prev, next);\n\t\ttoken.transfer(to,  pending + amount);\n\t\temit Claimed(candidate, msg.sender, to, pending);\n\t\temit Withdrawn(candidate, msg.sender, to, amount);\n\t}\n\n\tfunction slipWithdrawAndClaim(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress to,\n\t\tuint256 slippage\n\t) public override {\n\t\tcandidateElectionReward.voterClaim(candidate);\n\t\tVoterInfo storage voter = voters[candidate][msg.sender];\n\t\tuint256 accumulated = voter.amount * accPerShares[candidate] / ACC_PRECISION;\n\t\tuint256 pending = accumulated - voter.rewardDebt;\n\t\tvoter.rewardDebt = accumulated - (amount * accPerShares[candidate] / ACC_PRECISION);\n\t\tvoter.amount = voter.amount - amount;\n\t\tvoteSupply[candidate] = voteSupply[candidate] - amount;\n\t\tmajorCandidates.slipUpdate(candidate, voteSupply[candidate], slippage);\n\t\ttoken.transfer(to,  pending + amount);\n\t\temit Claimed(candidate, msg.sender, to, pending);\n\t\temit Withdrawn(candidate, msg.sender, to, amount);\n\t}\n\n\tfunction pendingReward(address candidate, address voter) public view returns (uint256 pending) {\n\t\tif (voteSupply[candidate] > 0) {\n\t\t\tuint256 pendingAllocation = candidateElectionReward.pendingAllocationReward(candidate);\n\t\t\tuint256 rewardDebt = voters[candidate][voter].rewardDebt;\n\t\t\tuint256 pendingShares = accPerShares[candidate] + (pendingAllocation * ACC_PRECISION / voteSupply[candidate]);\n\t\t\tpending = voters[candidate][voter].amount * pendingShares / ACC_PRECISION - rewardDebt;\n\t\t}\n\t}\n\n\tfunction allocateRewardFor(address candidate, uint256 amount) external override onlyCandidateElectionReward {\n\t\tif (voteSupply[candidate] > 0) {\n\t\t\taccPerShares[candidate] = accPerShares[candidate] + (amount * ACC_PRECISION / voteSupply[candidate]);\n\t\t\temit ShareUpdated(candidate);\n\t\t}\n\t}\n\n\tfunction _setCandidateElectionReward(ICandidateElectionReward _candidateElectionReward) internal {\n\t\tcandidateElectionReward = _candidateElectionReward;\n\t\temit CandidateElectionRewardUpdated(_candidateElectionReward);\n\t}\n\n\tfunction _setMajorCandidates(IMajorCandidates _majorCandidates) internal {\n\t\tmajorCandidates = _majorCandidates;\n\t\temit MajorCandidatesUpdated(_majorCandidates);\n\t}\n\n\tfunction _setToken(IERC20 _token) internal {\n\t\ttoken = _token;\n\t\temit TokenUpdated(_token);\n\t}\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n     * initialization step. This is essential to configure modules that are added through upgrades and that require\n     * initialization.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n}\n"
    },
    "contracts/interfaces/ICandidateElectionReward.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../libraries/Types.sol';\nimport './IElection.sol';\nimport './ICandidateRegistry.sol';\nimport './IPools.sol';\n\ninterface ICandidateElectionReward is ICandidateRegistry, IPools {\n\n\tevent ElectionUpdated(IElection election);\n\n\tevent Claimed(address candidate, address to, uint256 pending);\n\n\tevent Allocate(address candidate, uint256 amount);\n\n\tevent VoteRewardCoefUpdated(uint256 coef);\n\n\tfunction election() external view returns(IElection);\n\n\tfunction setVoteRewardCoef(uint256 coef) external;\n\n\tfunction voterClaim(address candidate) external;\n\n\tfunction voteRewardCoef(address candidate) external view returns (uint256 pending);\n\n\tfunction pendingAllocationReward(address candidate) external view returns (uint256 pending);\n\n}\n"
    },
    "contracts/interfaces/IElection.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport './ICandidateElectionReward.sol';\nimport './IMajorCandidates.sol';\nimport './IERC20.sol';\n\ninterface IElection {\n\n\tevent TokenUpdated(IERC20 token);\n\n\tevent CandidateElectionRewardUpdated(ICandidateElectionReward candidateElectionReward);\n\n\tevent MajorCandidatesUpdated(IMajorCandidates majorCandidates);\n\n\tevent ShareUpdated(address candidate);\n\n\tevent Vote(address candidate, address voter, uint256 amount);\n\n\tevent Claimed(address candidate, address voter, address to, uint256 amount);\n\n\tevent Withdrawn(address candidate, address voter, address to, uint256 amount);\n\n\tfunction token() external view returns(IERC20);\n\n\tfunction candidateElectionReward() external view returns(ICandidateElectionReward);\n\n\tfunction majorCandidates() external view returns(IMajorCandidates);\n\n\tfunction voteSupply(address candidate) external view returns(uint256);\n\n\tfunction ACC_PRECISION() external view returns(uint256);\n\n\tfunction allocateRewardFor(address candidate, uint256 amount) external;\n\n\tfunction slipVote(\n\t\taddress candidate,\n\t\taddress voter,\n\t\tuint256 amount,\n\t\tuint256 slippage\n\t) external;\n\n\tfunction vote(address candidate, address voter, uint256 amount, address prev, address next) external;\n\n\tfunction withdrawAndClaim(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress to,\n\t\taddress prev,\n\t\taddress next\n\t) external;\n\n\tfunction slipWithdrawAndClaim(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress to,\n\t\tuint256 slippage\n\t) external;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n                /// @solidity memory-safe-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
    },
    "contracts/libraries/Types.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nlibrary Types {\n\n\tenum Grade {\n\t\tNull,\n\t\tMajor,\n\t\tSecondary\n\t}\n\n\tstruct CandidateInfo {\n\t\tGrade grade;\n\t\tuint256 amount;\n\t\tuint256 rewardDebt;\n\t\tstring manifest;\n\t}\n\n\tstruct PoolInfo {\n\t\tuint256 accPerShare;\n\t\tuint256 lastRewardTime;\n\t\tuint256 allocPoint;\n\t}\n\n\tenum SlashStatus {\n\t\tDrafted,\n\t\tRejected,\n\t\tExecuted\n\t}\n\n\tstruct SlashInfo {\n\t\taddress candidate;\n\t\taddress drafter;\n\t\taddress[] validators;\n\t\tstring data;\n\t\tuint256 amount;\n\t\tuint256 timestamp;\n\t\tSlashStatus status;\n\t}\n\n}\n"
    },
    "contracts/interfaces/ICandidateRegistry.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../libraries/Types.sol';\n\ninterface ICandidateRegistry {\n\n\tevent Register(address candidate);\n\n\tfunction register(string memory manifest) external;\n\n\tfunction candidateInfo(address candidate) external view returns(Types.CandidateInfo memory);\n\n\tfunction isCandidateRegistered(address candidate) external view returns (bool);\n\n\tfunction gradeOf(address candidate) external view returns (Types.Grade);\n\n}\n"
    },
    "contracts/interfaces/IPools.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport './IERC20.sol';\nimport './IRewarder.sol';\nimport '../libraries/Types.sol';\n\ninterface IPools {\n\n\tevent TokenUpdated(IERC20 token);\n\n\tevent RewarderUpdated(IRewarder rewarder);\n\n\tevent RewardPerSecondUpdated(uint256 rewardPerSecond);\n\n\tevent PrecisionUpdated(uint256 precision);\n\n\tevent MaxCoefUpdated(uint256 maxCoef);\n\n\tevent AddPool(Types.Grade grade);\n\n\tevent PoolUpdated(Types.Grade grade);\n\n\tfunction token() external view returns(IERC20);\n\n\tfunction rewarder() external view returns(IRewarder);\n\n\tfunction ACC_PRECISION() external view returns(uint256);\n\n\tfunction MAXCOEF() external view returns(uint256);\n\n\tfunction updatePool(Types.Grade grade) external returns (Types.PoolInfo memory pool);\n\n\tfunction poolInfo(Types.Grade grade) external returns(Types.PoolInfo memory);\n\n\tfunction totalAllocPoint() external view returns(uint256);\n\n\tfunction rewardPerSecond() external view returns(uint256);\n\n}\n"
    },
    "contracts/interfaces/IMajorCandidates.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport './IElection.sol';\nimport './ICandidateElection.sol';\n\ninterface IMajorCandidates {\n\n\tevent MaxNodesLengthUpdated(uint256 _len);\n\n\tevent ElectionUpdated(IElection election);\n\n\tevent CandidateElectionUpdated(ICandidateElection candidateElection);\n\n\tevent AddCandidate(address candidate, uint256 amount, address prev, address next);\n\n\tevent UpdateCandidate(address candidate, uint256 amount, address prev, address next);\n\n\tevent RemoveCandidate(address candidate);\n\n\tfunction MAX_MAJOR_CANDIDATES() external view returns(uint256);\n\n\tfunction election() external view returns(IElection);\n\n\tfunction candidateElection() external view returns(ICandidateElection);\n\n\tfunction exists(address candidate) external view returns (bool);\n\n\tfunction existsInMajor(address candidate) external view returns(bool existed);\n\n\tfunction majorCandidateList() external view returns(address[] memory majors);\n\n\tfunction remove(address candidate) external;\n\n\tfunction upset(address candidate, uint256 amount, address prev, address next) external;\n\n\tfunction slipUpdate(address candidate, uint256 amount, uint256 slippage) external;\n\n}\n"
    },
    "contracts/interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\n\ninterface IERC20 is IERC20Upgradeable {\n\tfunction burn(uint256 amount) external;\n\n\tfunction burnFrom(address account, uint256 amount) external;\n}\n"
    },
    "contracts/interfaces/IRewarder.sol": {
      "content": "\n// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\n\ninterface IRewarder {\n\n\tevent TokenUpdated(IERC20Upgradeable token);\n\n\tevent StakeUpdated(address stake);\n\n\tevent SendReward(address to, uint256 amount);\n\n\tfunction token() external view returns(IERC20Upgradeable);\n\n\tfunction sendReward(address to, uint256 amount) external;\n\n}"
    },
    "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
    },
    "contracts/interfaces/ICandidateElection.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../libraries/Types.sol';\nimport './IMajorCandidates.sol';\n\ninterface ICandidateElection {\n\n\tevent IMajorCandidatesUpdated(IMajorCandidates majorCandidates);\n\n\tevent Upgrade(address candidate, Types.Grade fromGrade, Types.Grade toGrade);\n\n\tevent Downgrade(address candidate, Types.Grade fromGrade, Types.Grade toGrade);\n\n\tfunction majorCandidates() external view returns(IMajorCandidates);\n\n\tfunction upgrade(address candidate) external;\n\n\tfunction downgrade(address candidate) external;\n\n}\n"
    },
    "contracts/mock/MockElection.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../election/Election.sol';\n\ncontract MockElection is Election {\n\n\tfunction init(\n\t\tIERC20 _token,\n\t\tICandidateElectionReward _candidateElectionReward,\n\t\tIMajorCandidates _majorCandidates\n\t) external {\n\t\t_setToken(_token);\n\t\t_setCandidateElectionReward(_candidateElectionReward);\n\t\t_setMajorCandidates(_majorCandidates);\n\t\tACC_PRECISION = 1e12;\n\t}\n\n}"
    },
    "contracts/stake/Pools.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\n\nimport '../interfaces/IPools.sol';\n\ncontract Pools is IPools {\n\n\tIERC20 public override token;\n\n\tIRewarder public override rewarder;\n\n\tuint256 public override ACC_PRECISION;\n\n\tuint256 public override MAXCOEF;\n\n\tuint256 public override totalAllocPoint;\n\n\tuint256 public override rewardPerSecond;\n\n\tmapping(Types.Grade => Types.PoolInfo) internal pools;\n\n\tfunction _addPool(\n\t\tTypes.Grade grade,\n\t\tuint256 allocPoint\n\t) internal {\n\t\trequire(pools[grade].allocPoint == 0, 'Pools: pool exists');\n\t\ttotalAllocPoint = totalAllocPoint + allocPoint;\n\t\tpools[grade] = Types.PoolInfo({ allocPoint: allocPoint, lastRewardTime: block.timestamp, accPerShare: 0 });\n\t\temit AddPool(grade);\n\t}\n\n\tfunction updatePool(Types.Grade grade) public override returns (Types.PoolInfo memory pool) {\n\t\trequire(poolExists(grade), 'Pools: nonexistent pool');\n\t\tpool = pools[grade];\n\t\tif (block.timestamp > pool.lastRewardTime) {\n\t\t\tuint256 lpSupply = token.balanceOf(address(this));\n\t\t\tif (lpSupply > 0) {\n\t\t\t\tuint256 time = block.timestamp - pool.lastRewardTime;\n\t\t\t\tuint256 reward = time * rewardPerSecond * pool.allocPoint / totalAllocPoint;\n\t\t\t\tpool.accPerShare = pool.accPerShare + (reward * ACC_PRECISION / lpSupply);\n\t\t\t}\n\t\t\tpool.lastRewardTime = block.timestamp;\n\t\t\tpools[grade] = pool;\n\t\t}\n\t\temit PoolUpdated(grade);\n\t}\n\n\tfunction poolInfo(Types.Grade grade) public view override returns (Types.PoolInfo memory) {\n\t\treturn pools[grade];\n\t}\n\n\tfunction poolExists(Types.Grade grade) public view returns (bool) {\n\t\treturn pools[grade].allocPoint != 0;\n\t}\n\n\tfunction _setRewardPerSecond(uint256 _rewardPerSecond) internal {\n\t\trewardPerSecond = _rewardPerSecond;\n\t\temit RewardPerSecondUpdated(_rewardPerSecond);\n\t}\n\n\tfunction _setToken(IERC20 _token) internal {\n\t\ttoken = _token;\n\t\temit TokenUpdated(_token);\n\t}\n\n\tfunction _setRewarder(IRewarder _rewarder) internal {\n\t\trewarder = _rewarder;\n\t\temit RewarderUpdated(_rewarder);\n\t}\n\n\tfunction _setMaxCoef(uint256 _maxCoef) internal {\n\t\tMAXCOEF = _maxCoef;\n\t\temit MaxCoefUpdated(_maxCoef);\n\t}\n\n\tfunction _setAccPrecision(uint256 _precision) internal {\n\t\tACC_PRECISION = _precision;\n\t\temit PrecisionUpdated(_precision);\n\t}\n\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
    },
    "contracts/Pauser.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol';\n\n/// @author Alexandas\n/// @dev Pauser contract\nabstract contract Pauser is OwnableUpgradeable, PausableUpgradeable {\n\t/// @dev all pausers\n\tmapping(address => bool) public pausers;\n\n\t/// @dev emit when pauser is added\n\t/// @param account pauser address\n\tevent PauserAdded(address account);\n\n\t/// @dev emit when pauser is removed\n\t/// @param account pauser address\n\tevent PauserRemoved(address account);\n\n\tfunction __Init_Pauser(address account) internal onlyInitializing {\n\t\t_addPauser(account);\n\t}\n\n\tmodifier onlyPauser() {\n\t\trequire(isPauser(msg.sender), 'Pauser: caller is not the pauser');\n\t\t_;\n\t}\n\n\t/// @dev pause the contract\n\tfunction pause() public onlyPauser {\n\t\t_pause();\n\t}\n\n\t/// @dev unpause the contract\n\tfunction unpause() public onlyPauser {\n\t\t_unpause();\n\t}\n\n\t/// @dev whether the account is the contract pauser\n\t/// @param account address\n\t/// @return whether account is a pauser\n\tfunction isPauser(address account) public view returns (bool) {\n\t\treturn pausers[account];\n\t}\n\n\t/// @dev add a pauser for the contract\n\t/// @param account address\n\tfunction addPauser(address account) public onlyOwner {\n\t\t_addPauser(account);\n\t}\n\n\t/// @dev remove a pauser for the contract\n\t/// @param account address\n\tfunction removePauser(address account) public onlyOwner {\n\t\t_removePauser(account);\n\t}\n\n\t/// @dev remove a pauser for the contract\n\tfunction renouncePauser() public {\n\t\t_removePauser(msg.sender);\n\t}\n\n\tfunction _addPauser(address account) private {\n\t\trequire(!isPauser(account), 'Pauser: account is already pauser');\n\t\tpausers[account] = true;\n\t\temit PauserAdded(account);\n\t}\n\n\tfunction _removePauser(address account) private {\n\t\trequire(isPauser(account), 'Pauser: account is not pauser');\n\t\tdelete pausers[account];\n\t\temit PauserRemoved(account);\n\t}\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    bool private _paused;\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n        _paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        require(!paused(), \"Pausable: paused\");\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        require(paused(), \"Pausable: not paused\");\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
    },
    "contracts/stake/Stake.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\nimport './CandidateStake.sol';\nimport './CandidateSlash.sol';\n\ncontract Stake is CandidateSlash, Initializable {\n\n\tfunction initialize(\n\t\tIERC20 token,\n\t\tIRewarder rewarder,\n\t\tIElection election,\n\t\tIMajorCandidates majorCandidates,\n\t\tISlasher slasher,\n\t\tuint256 stakeFrozenPeriod,\n\t\tuint256 mintStake,\n\t\tuint256 rewardPerSecond\n\t) external initializer {\n\t\t_setToken(token);\n\t\t_setRewarder(rewarder);\n\t\t_setElection(election);\n\t\t_setMajorCandidates(majorCandidates);\n\t\t_setSlasher(slasher);\n\t\t_setStakeFrozenPeriod(stakeFrozenPeriod);\n\t\t_setMinStake(mintStake);\n\t\t_setRewardPerSecond(rewardPerSecond);\n\t\t_setMaxCoef(1e6);\n\t\t_setAccPrecision(1e12);\n\t\t_addPool(Types.Grade.Major, 750);\n\t\t_addPool(Types.Grade.Secondary, 250);\n\t}\n\n}\n"
    },
    "contracts/stake/CandidateStake.sol": {
      "content": "\n// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../interfaces/ICandidateStake.sol';\nimport './CandidateElection.sol';\n\ncontract CandidateStake is CandidateElection, ICandidateStake {\n\n\tuint256 public minStake;\n\n\tuint256 public stakeFrozenPeriod;\n\n\tmapping(address => uint256) public lastStakeTimestamp;\n\n\tfunction stake(uint256 amount) external override {\n\t\t_stake(msg.sender, msg.sender, amount);\n\t}\n\n\tfunction registerAndStake(uint256 amount, string memory manifest) external override {\n\t\t_register(msg.sender, manifest);\n\t\t_stake(msg.sender, msg.sender, amount);\n\t}\n\n\tfunction _stake(\n\t\taddress user,\n\t\taddress _candidate,\n\t\tuint256 amount\n\t) internal {\n\t\trequire(isCandidateRegistered(_candidate), 'CandidateStake: candidate is not registered');\n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\tTypes.PoolInfo memory pool;\n\t\tif (voteRewardCoef(_candidate) > 0) {\n\t\t\tpool = _claimAndAllocate(_candidate, _candidate);\n\t\t} else {\n\t\t\tpool = updatePool(candidate.grade);\n\t\t}\n\t\trequire(amount + candidate.amount >= minStake, 'CandidateStake: total amount is less than minimum stake');\n\t\ttoken.transferFrom(user, address(this), amount);\n\t\tcandidate.amount = candidate.amount + amount;\n\t\tcandidate.rewardDebt = candidate.rewardDebt + (amount * pool.accPerShare / ACC_PRECISION);\n\t\tlastStakeTimestamp[_candidate] = block.timestamp;\n\t\temit Stake(user, _candidate, amount);\n\t}\n\n\tfunction quit(address to) external override {\n\t\trequire(isStakeUnfrozen(msg.sender), 'CandidateStake: stake is frozen currently');\n\t\tif (majorCandidates.exists(msg.sender)) {\n\t\t\tmajorCandidates.remove(msg.sender);\n\t\t}\n\t\t_quit(msg.sender, to);\n\t}\n\n\tfunction _quit(address _candidate, address to) internal {\n\t\tTypes.CandidateInfo memory candidate = candidates[_candidate];\n\t\t_withdrawAndClaim(_candidate, candidate.amount, to);\n\t\tdelete candidates[_candidate];\n\t\temit Quit(candidate.grade, _candidate);\n\t}\n\n\tfunction claim(address candidate) public override returns (Types.PoolInfo memory pool) {\n\t\treturn _claimAndAllocate(msg.sender, candidate);\n\t}\n\n\tfunction isStakeUnfrozen(address candidate) public view returns(bool) {\n\t\treturn block.timestamp > stakeFrozenPeriod + lastStakeTimestamp[candidate];\n\t}\n\n\tfunction withdrawAndClaim(uint256 amount, address to) external override {\n\t\trequire(isStakeUnfrozen(msg.sender), 'CandidateStake: stake is frozen currently');\n\t\t_withdrawAndClaim(msg.sender, amount, to);\n\t}\n\n\tfunction _withdrawAndClaim(address _candidate, uint256 amount, address to) internal {\n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\tTypes.PoolInfo memory pool = updatePool(candidate.grade);\n\t\tuint256 accumulated = candidate.amount * pool.accPerShare / ACC_PRECISION;\n\t\tuint256 _pending = accumulated - candidate.rewardDebt;\n\t\tcandidate.rewardDebt = accumulated - (amount * pool.accPerShare / ACC_PRECISION);\n\t\tcandidate.amount = candidate.amount - amount;\n\t\t_allocateReward(_candidate, to, _pending);\n\t\ttoken.transfer(to, amount);\n\n\t\temit Withdrawn(msg.sender, to, amount);\n\t}\n\n\tfunction candidatePendingReward(address _candidate) public view override returns (uint256 pending) {\n\t\tpending = _pendingReward(_candidate);\n\t}\n\n\tfunction _setMinStake(uint256 amount) internal {\n\t\tminStake = amount;\n\t\temit MinStakeUpdated(amount);\n\t}\n\n\tfunction _setStakeFrozenPeriod(uint256 period) internal {\n\t\tstakeFrozenPeriod = period;\n\t\temit StakeFrozenPeriodUpdated(period);\n\t}\n\n}\n"
    },
    "contracts/stake/CandidateSlash.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../interfaces/ICandidateSlash.sol';\n\nimport './CandidateStake.sol';\n\ncontract CandidateSlash is CandidateStake, ICandidateSlash {\n\n\tISlasher public override slasher;\n\n\tmodifier onlySlasher() {\n\t\trequire(msg.sender == address(slasher), 'CandidateSlash: caller must be Slasher contract');\n\t\t_;\n\t}\n\n\tfunction _setSlasher(ISlasher _slasher) internal {\n\t\tslasher = _slasher;\n\t\temit SlasherUpdated(_slasher);\n\t}\n\n\tfunction draftSlash(address _candidate, uint256 amount) external override onlySlasher returns(uint256 pendingSlash) {\n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\trequire(candidate.amount > 0, 'CandidateSlash: zero stake amount');\n\t\tif (candidate.amount < amount) {\n\t\t\t_quit(_candidate, _candidate);\n\t\t} else {\n\t\t\tpendingSlash = amount;\n\t\t\tTypes.PoolInfo memory pool = updatePool(candidate.grade);\n\t\t\tuint256 accumulated = candidate.amount * pool.accPerShare / ACC_PRECISION;\n\t\t\tuint256 _pending = accumulated - candidate.rewardDebt;\n\t\t\tcandidate.rewardDebt = accumulated - (amount * pool.accPerShare / ACC_PRECISION);\n\t\t\tcandidate.amount = candidate.amount - amount;\n\t\t\t_allocateReward(_candidate, _candidate, _pending);\n\n\t\t\temit DraftSlash(_candidate, pendingSlash);\n\t\t}\n\t\n\t}\n\n\tfunction rejectSlash(address _candidate, uint256 pendingSlash) external override onlySlasher {\n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\tTypes.PoolInfo memory pool = updatePool(candidate.grade);\n\t\tuint256 accumulated = candidate.amount * pool.accPerShare / ACC_PRECISION;\n\t\tuint256 _pending = accumulated - candidate.rewardDebt;\n\t\tcandidate.amount = candidate.amount + pendingSlash;\n\t\tcandidate.rewardDebt = candidate.rewardDebt + (pendingSlash * pool.accPerShare / ACC_PRECISION);\n\t\t_allocateReward(_candidate, _candidate, _pending);\n\n\t\temit RejectSlash(_candidate, pendingSlash);\n\t}\n\n\tfunction executeSlash(\n\t\taddress _candidate, \n\t\tuint256 slash,\n\t\taddress[] memory beneficiaries, \n\t\tuint256[] memory amounts,\n\t\tuint256 burned\n\t) external override onlySlasher {\n\t\trequire(beneficiaries.length == amounts.length, 'CandidateSlash: invalid params');\n\t\tfor(uint8 i = 0; i < beneficiaries.length; i++) {\n\t\t\ttoken.transfer(beneficiaries[i], amounts[i]);\n\t\t}\n\t\ttoken.burn(burned);\n\t\temit ExcuteSlash(_candidate, slash, beneficiaries, amounts, burned);\n\t}\n\n}\n"
    },
    "contracts/interfaces/ICandidateStake.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport './ICandidateElection.sol';\nimport '../libraries/Types.sol';\n\ninterface ICandidateStake is ICandidateElection {\n\n\tevent MinStakeUpdated(uint256 amount);\n\n\tevent StakeFrozenPeriodUpdated(uint256 period);\n\n\tevent Quit(Types.Grade grade, address candidate);\n\n\tevent Stake(address from, address candidate, uint256 amount);\n\n\tevent Withdrawn(address candidate, address to, uint256 amount);\n\n\tfunction stake(uint256 amount) external;\n\n\tfunction registerAndStake(uint256 amount, string memory url) external;\n\t\n\tfunction quit(address to) external;\n\n\tfunction claim(address candidate) external returns(Types.PoolInfo memory pool);\n\n\tfunction withdrawAndClaim(uint256 amount, address to) external;\n\n\tfunction candidatePendingReward(address candidate) external view returns (uint256 pending);\n\n}\n"
    },
    "contracts/stake/CandidateElection.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../interfaces/ICandidateElection.sol';\n\nimport './CandidateElectionReward.sol';\nimport './Pools.sol';\n\ncontract CandidateElection is CandidateElectionReward, ICandidateElection {\n\n\tIMajorCandidates public override majorCandidates;\n\n\tmodifier onlyMajorCandidates() {\n\t\trequire(msg.sender == address(majorCandidates), 'CandidateElection: caller must be MajorCandidates contract');\n\t\t_;\n\t}\n\n\tfunction _setMajorCandidates(IMajorCandidates _majorCandidates) internal {\n\t\tmajorCandidates = _majorCandidates;\n\t\temit IMajorCandidatesUpdated(_majorCandidates);\n\t}\n\n\tfunction upgrade(address candidate) external override onlyMajorCandidates {\n\t\tif (gradeOf(candidate) == Types.Grade.Secondary) {\n\t\t\t_onCandidateGradeChanged(candidate, Types.Grade.Major);\n\t\t\temit Upgrade(candidate, Types.Grade.Secondary, Types.Grade.Major);\n\t\t}\n\t}\n\n\tfunction downgrade(address candidate) external override onlyMajorCandidates {\n\t\tif (gradeOf(candidate) == Types.Grade.Major) {\n\t\t\t_onCandidateGradeChanged(candidate, Types.Grade.Secondary);\n\t\t\temit Downgrade(candidate, Types.Grade.Major, Types.Grade.Secondary);\n\t\t}\n\t}\n\n\t// make sure pool updated and reward allocated\n\tfunction _onCandidateGradeChanged(address _candidate, Types.Grade grade) internal {\n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\tcandidate.grade = grade;\n\t\tTypes.PoolInfo memory pool = updatePool(grade);\n\t\tcandidate.rewardDebt = candidate.amount * pool.accPerShare / ACC_PRECISION;\n\t}\n\n}\n"
    },
    "contracts/stake/CandidateElectionReward.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../interfaces/ICandidateElectionReward.sol';\nimport './CandidateRegistry.sol';\nimport './Pools.sol';\n\ncontract CandidateElectionReward is CandidateRegistry, Pools, ICandidateElectionReward {\n\n\tIElection public override election;\n\n\tmapping(address => uint256) internal voteRewardCoefs;\n\n\tmodifier onlyElection() {\n\t\trequire(msg.sender == address(election), 'CandidateElectionReward: caller must be election contract');\n\t\t_;\n\t}\n\n\tfunction voterClaim(address candidate) external override onlyElection {\n\t\t_claimAndAllocate(candidate, candidate);\n\t}\n\n\tfunction _claimAndAllocate(address _candidate, address to) internal returns (Types.PoolInfo memory pool) {\n\t\tif (isCandidateRegistered(_candidate)) {\n\t\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\t\tpool = updatePool(candidate.grade);\n\t\t\tuint256 accumulated = candidate.amount * pool.accPerShare / ACC_PRECISION;\n\t\t\tuint256 _pending = accumulated - candidate.rewardDebt;\n\t\t\tcandidate.rewardDebt = accumulated;\n\t\t\t_allocateReward(_candidate, to, _pending);\n\t\t}\n\t}\n\n\tfunction _allocateReward(\n\t\taddress _candidate,\n\t\taddress to,\n\t\tuint256 _pending\n\t) internal {\n\t\tif (_pending > 0) {\n\t\t\tif (voteRewardCoef(_candidate) > 0 && election.voteSupply(_candidate) > 0) {\n\t\t\t\tuint256 allocation = _pending * voteRewardCoef(_candidate) / MAXCOEF;\n\t\t\t\telection.allocateRewardFor(_candidate, allocation);\n\t\t\t\t_pending = _pending - allocation;\n\t\t\t\trewarder.sendReward(address(election), allocation);\n\t\t\t\temit Allocate(_candidate, allocation);\n\t\t\t}\n\t\t\trewarder.sendReward(to, _pending);\n\t\t\temit Claimed(_candidate, to, _pending);\n\t\t}\n\t}\n\n\tfunction setVoteRewardCoef(uint256 coef) public override {\n\t\t_setVoteRewardCoef(msg.sender, coef);\n\t}\n\n\tfunction _setVoteRewardCoef(address candidate, uint256 coef) internal {\n\t\trequire(coef > 0 && coef < MAXCOEF, 'CandidateElection: invalid coef');\n\t\trequire(isCandidateRegistered(candidate), 'CandidateElection: candidate is not registered');\n\t\t_claimAndAllocate(candidate, candidate);\n\t\tvoteRewardCoefs[candidate] = coef;\n\t\temit VoteRewardCoefUpdated(coef);\n\t}\n\n\tfunction _setElection(IElection _election) internal {\n\t\telection = _election;\n\t\temit ElectionUpdated(_election);\n\t}\n\n\tfunction _pendingReward(address _candidate) internal view returns (uint256 pending) { \n\t\tTypes.CandidateInfo storage candidate = candidates[_candidate];\n\t\tTypes.PoolInfo memory pool = pools[candidate.grade];\n\t\tuint256 accPerShare = pool.accPerShare;\n\t\tuint256 lpSupply = token.balanceOf(address(this));\n\t\tif (block.timestamp > pool.lastRewardTime && lpSupply != 0) {\n\t\t\tuint256 time = block.timestamp - pool.lastRewardTime;\n\t\t\tuint256 reward = time * rewardPerSecond * pool.allocPoint / totalAllocPoint;\n\t\t\taccPerShare = accPerShare + (reward * ACC_PRECISION / lpSupply);\n\t\t}\n\t\tpending = candidate.amount * accPerShare / ACC_PRECISION - candidate.rewardDebt;\n\t}\n\n\tfunction pendingAllocationReward(address _candidate) public view override returns (uint256 pendingAllocation) {\n\t\tuint256 pending = _pendingReward(_candidate);\n\t\tif (voteRewardCoef(_candidate) > 0 && election.voteSupply(_candidate) > 0) {\n\t\t\tpendingAllocation = pending * voteRewardCoef(_candidate) / MAXCOEF;\n\t\t}\n\t}\n\n\tfunction voteRewardCoef(address candidate) public view override returns (uint256) {\n\t\treturn voteRewardCoefs[candidate];\n\t}\n\n}\n"
    },
    "contracts/stake/CandidateRegistry.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../interfaces/ICandidateRegistry.sol';\n\ncontract CandidateRegistry is ICandidateRegistry {\n\n\tmapping(address => Types.CandidateInfo) internal candidates;\n\n\tfunction register(string memory manifest) external override {\n\t\t_register(msg.sender, manifest);\n\t}\n\n\tfunction _register(address candidate, string memory manifest) internal {\n\t\trequire(candidates[candidate].grade == Types.Grade.Null, 'Candidate: candidate has been registered');\n\t\tcandidates[candidate].grade = Types.Grade.Secondary;\n\t\tcandidates[candidate].manifest = manifest;\n\t\temit Register(candidate);\n\t}\n\n\tfunction candidateInfo(address candidate) external view override returns (Types.CandidateInfo memory) {\n\t\treturn candidates[candidate];\n\t}\n\n\tfunction isCandidateRegistered(address candidate) public view override returns (bool) {\n\t\treturn candidates[candidate].grade != Types.Grade.Null;\n\t}\n\n\tfunction gradeOf(address candidate) public view override returns (Types.Grade) {\n\t\treturn candidates[candidate].grade;\n\t}\n\n}\n"
    },
    "contracts/interfaces/ICandidateSlash.sol": {
      "content": "\n// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport './ISlasher.sol';\n\ninterface ICandidateSlash {\n\n\tevent SlasherUpdated(ISlasher slasher);\n\n\tevent DraftSlash(address _candidate, uint256 pendingSlash);\n\n\tevent RejectSlash(address _candidate, uint256 pendingSlash);\n\n\tevent ExcuteSlash(address _candidate, uint256 pendingSlash, address[] beneficiaries, uint256[] amounts, uint256 burned);\n\n\tfunction slasher() external returns(ISlasher);\n\n\tfunction draftSlash(address _candidate, uint256 amount) external returns(uint256 pendingSlash);\n\n\tfunction rejectSlash(address _candidate, uint256 pendingSlash) external;\n\n\tfunction executeSlash(\n\t\taddress _candidate, \n\t\tuint256 slash,\n\t\taddress[] memory beneficiaries, \n\t\tuint256[] memory amounts,\n\t\tuint256 burned\n\t) external;\n\n}\n"
    },
    "contracts/interfaces/ISlasher.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../libraries/Types.sol';\nimport './IMajorCandidates.sol';\nimport './ICandidateSlash.sol';\n\ninterface ISlasher {\n\n\tevent GovernanceUpdated(address governance);\n\n\tevent CandidateSlashUpdated(ICandidateSlash candidateSlash);\n\n\tevent MajorCandidatesUpdated(IMajorCandidates _majorCandidates);\n\n\tevent DefaultSlashAmountUpdated(uint256 amount);\n\n\tevent PublicNoticePeriodUpdated(uint256 period);\n\n\tevent MaxCoefUpdated(uint256 maxCoef);\n\n\tevent DrafterCoefUpdated(uint64 drafterCoef);\n\n\tevent ValidatorCoefUpdated(uint256 validatorCoef);\n\n\tevent ExecutorCoefUpdated(uint256 executorCoef);\n\n\tevent DraftSlash(uint256 nonce);\n\n\tevent RejectSlash(uint256 nonce);\n\n\tevent ExecuteSlash(uint256 nonce, address executor);\n\n\tfunction candidateSlash() external view returns(ICandidateSlash);\n\n\tfunction majorCandidates() external view returns(IMajorCandidates);\n\n\tfunction defaultSlashAmount() external view returns(uint256);\n\n\tfunction publicNoticePeriod() external view returns(uint256);\n\n\tfunction nonce() external view returns(uint256);\n\n\tfunction MAXCOEF() external view returns(uint64);\n\n\tfunction drafterCoef() external view returns(uint64);\n\n\tfunction validatorCoef() external view returns(uint64);\n\n\tfunction executorCoef() external view returns(uint64);\n\n\tfunction getSlashAt(uint256 _nonce) external view returns(Types.SlashInfo memory);\n\n\tfunction nonceOf(address candidate) external view returns(uint256);\n\n\tfunction setDrafterCoef(uint64 _drafterCoef) external;\n\n\tfunction setValidatorCoef(uint64 _validatorCoef) external;\n\n\tfunction setExecutorCoef(uint64 _executorCoef) external;\n\n\tfunction draft(address candidate, string memory data, bytes[] memory signatures) external;\n\n\tfunction reject(address candidate) external;\n\n\tfunction execute(address candidate) external;\n\n\tfunction slashExists(address candidate) external view returns(bool);\n\n\tfunction checkNSignatures(bytes32 hash, bytes[] memory signatures) external view returns(address[] memory signers);\n\n}\n"
    },
    "contracts/slasher/Slasher.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';\nimport '../interfaces/ISlasher.sol';\n\ncontract Slasher is ISlasher, OwnableUpgradeable {\n\taddress public governance;\n\n\tICandidateSlash public override candidateSlash;\n\n\tIMajorCandidates public override majorCandidates;\n\n\tuint256 public override defaultSlashAmount;\n\n\tuint256 public override publicNoticePeriod;\n\n\tuint256 public override nonce;\n\n\tuint64 public override MAXCOEF;\n\n\tuint64 public override drafterCoef;\n\n\tuint64 public override validatorCoef;\n\n\tuint64 public override executorCoef;\n\n\tmapping(uint256 => Types.SlashInfo) internal slashes;\n\n\tmapping(address => uint256) internal nonces;\n\n\tmodifier onlyGovernance() {\n\t\trequire(msg.sender == governance, 'Slasher: caller is not the governace');\n\t\t_;\n\t}\n\n\tfunction initialize(\n\t\taddress newOwner,\n\t\taddress _governance,\n\t\tICandidateSlash _candidateSlash,\n\t\tIMajorCandidates _majorCandidates,\n\t\tuint256 _defaultSlashAmount,\n\t\tuint256 _publicNoticePeriod,\n\t\tuint64 maxCoef,\n\t\tuint64 _drafterCoef,\n\t\tuint64 _validatorCoef,\n\t\tuint64 _executorCoef\n\t) external initializer {\n\t\t_transferOwnership(newOwner);\n\t\t_initNonce();\n\t\t_setGovernance(_governance);\n\t\t_setCandidateSlash(_candidateSlash);\n\t\t_setMajorCandidates(_majorCandidates);\n\t\t_setDefaultSlashAmount(_defaultSlashAmount);\n\t\t_setPublicNoticePeriod(_publicNoticePeriod);\n\t\t_setMaxCoef(maxCoef);\n\t\t_setDrafterCoef(_drafterCoef);\n\t\t_setValidatorCoef(_validatorCoef);\n\t\t_setExecutorCoef(_executorCoef);\n\t}\n\n\tfunction draft(\n\t\taddress candidate,\n\t\tstring memory data,\n\t\tbytes[] memory signatures\n\t) external override onlyGovernance {\n\t\trequire(!slashExists(candidate), 'Slasher: candidate is in slash');\n\t\tbytes32 hash = keccak256(abi.encodePacked(nonce, candidate, data));\n\t\taddress[] memory validators = checkNSignatures(hash, signatures);\n\t\tuint256 amount = candidateSlash.draftSlash(candidate, defaultSlashAmount);\n\t\tif (amount > 0) {\n\t\t\tslashes[nonce] = Types.SlashInfo({\n\t\t\t\tcandidate: candidate,\n\t\t\t\tdrafter: msg.sender,\n\t\t\t\tvalidators: validators,\n\t\t\t\tdata: data,\n\t\t\t\tamount: amount,\n\t\t\t\ttimestamp: block.timestamp,\n\t\t\t\tstatus: Types.SlashStatus.Drafted\n\t\t\t});\n\t\t\tnonces[candidate] = nonce;\n\t\t\temit DraftSlash(nonce);\n\t\t\tnonce++;\n\t\t}\n\t}\n\n\tfunction reject(address candidate) external override onlyGovernance {\n\t\tuint256 _nonce = nonces[candidate];\n\t\trequire(slashes[_nonce].timestamp > 0, 'Slasher: nonexistent slash');\n\t\trequire(slashes[_nonce].status == Types.SlashStatus.Drafted, 'Slasher: slash status is not drafted');\n\t\trequire(block.timestamp <= slashes[_nonce].timestamp + publicNoticePeriod, 'Slasher: slash is not in public notice period');\n\t\tslashes[_nonce].status = Types.SlashStatus.Rejected;\n\t\tcandidateSlash.rejectSlash(candidate, slashes[_nonce].amount);\n\n\t\tdelete nonces[candidate];\n\t\temit RejectSlash(_nonce);\n\t}\n\n\tfunction execute(address candidate) external override onlyGovernance {\n\t\tuint256 _nonce = nonceOf(candidate);\n\t\trequire(slashes[_nonce].timestamp > 0, 'Slasher: nonexistent slash');\n\t\trequire(slashes[_nonce].status == Types.SlashStatus.Drafted, 'Slasher: slash status is not drafted');\n\t\trequire(block.timestamp > slashes[_nonce].timestamp + publicNoticePeriod, 'Slasher: slash is in public notice period');\n\t\tslashes[nonce].status = Types.SlashStatus.Executed;\n\t\tuint256 amount = slashes[_nonce].amount;\n\t\taddress[] memory validators = slashes[_nonce].validators;\n\t\tuint256 validatorLen = validators.length;\n\t\taddress[] memory beneficiaries = new address[](validatorLen + 2);\n\t\tuint256[] memory amounts = new uint256[](validatorLen + 2);\n\t\tuint256 validatorAmount = (amount * validatorCoef) / MAXCOEF;\n\t\tuint256 drafterAmount = (amount * drafterCoef) / MAXCOEF;\n\t\tuint256 executorAmount = (amount * executorCoef) / MAXCOEF;\n\t\tuint256 burned = amount - drafterAmount - validatorAmount - executorAmount;\n\t\tuint256 averageValidatorAmount = validatorAmount / validatorLen;\n\t\tfor (uint256 i = 0; i < validators.length; i++) {\n\t\t\tbeneficiaries[i] = validators[i];\n\t\t\tamounts[i] = averageValidatorAmount;\n\t\t}\n\t\tbeneficiaries[validatorLen] = slashes[_nonce].drafter;\n\t\tamounts[validatorLen] = drafterAmount;\n\t\tbeneficiaries[validatorLen + 1] = msg.sender;\n\t\tamounts[validatorLen + 1] = executorAmount;\n\n\t\tcandidateSlash.executeSlash(candidate, amount, beneficiaries, amounts, burned);\n\t\tdelete nonces[candidate];\n\n\t\temit ExecuteSlash(_nonce, msg.sender);\n\t}\n\n\tfunction executedResult(address candidate)\n\t\tpublic\n\t\tview\n\t\treturns (\n\t\t\taddress[] memory beneficiaries,\n\t\t\tuint256[] memory amounts,\n\t\t\tuint256 burned\n\t\t)\n\t{\n\t\tuint256 _nonce = nonceOf(candidate);\n\t\trequire(slashes[_nonce].timestamp > 0, 'Slasher: nonexistent slash');\n\t\trequire(slashes[_nonce].status == Types.SlashStatus.Drafted, 'Slasher: slash status is not draft');\n\t\trequire(block.timestamp > slashes[_nonce].timestamp + publicNoticePeriod, 'Slasher: slash is in public notice period');\n\t\tuint256 amount = slashes[_nonce].amount;\n\t\taddress[] memory validators = slashes[_nonce].validators;\n\t\tuint256 validatorLen = validators.length;\n\t\tuint256 validatorAmount = (amount * validatorCoef) / MAXCOEF;\n\t\tuint256 drafterAmount = (amount * drafterCoef) / MAXCOEF;\n\t\tuint256 executorAmount = (amount * executorCoef) / MAXCOEF;\n\t\tburned = amount - drafterAmount - validatorAmount - executorAmount;\n\t\tuint256 averageValidatorAmount = validatorAmount / validatorLen;\n\t\tbeneficiaries = new address[](validatorLen + 2);\n\t\tamounts = new uint256[](validatorLen + 2);\n\t\tfor (uint256 i = 0; i < validatorLen; i++) {\n\t\t\tbeneficiaries[i] = validators[i];\n\t\t\tamounts[i] = averageValidatorAmount;\n\t\t}\n\t\tbeneficiaries[validatorLen] = slashes[_nonce].drafter;\n\t\tamounts[validatorLen] = drafterAmount;\n\t\tbeneficiaries[validatorLen + 1] = msg.sender;\n\t\tamounts[validatorLen + 1] = executorAmount;\n\t}\n\n\tfunction slashExists(address candidate) public view override returns (bool) {\n\t\treturn nonces[candidate] > 0;\n\t}\n\n\tfunction checkNSignatures(bytes32 hash, bytes[] memory signatures) public view override returns (address[] memory signers) {\n\t\trequire(signatures.length >= (majorCandidates.MAX_MAJOR_CANDIDATES() * 2) / 3, 'Slasher: signature length is not enough');\n\t\taddress last = address(0);\n\t\tsigners = new address[](signatures.length);\n\t\tfor (uint8 i = 0; i < signatures.length; i++) {\n\t\t\t(address recovered, ECDSAUpgradeable.RecoverError err) = ECDSAUpgradeable.tryRecover(hash, signatures[i]);\n\t\t\trequire(err == ECDSAUpgradeable.RecoverError.NoError, 'Slasher: invalid signature');\n\t\t\trequire(recovered > last, 'Slasher: incorrect signature order');\n\t\t\trequire(majorCandidates.existsInMajor(recovered), 'Slasher: signer is not the major candidate');\n\t\t\tlast = recovered;\n\t\t\tsigners[i] = recovered;\n\t\t}\n\t}\n\n\tfunction getSlashAt(uint256 _nonce) public view override returns (Types.SlashInfo memory) {\n\t\treturn slashes[_nonce];\n\t}\n\n\tfunction nonceOf(address candidate) public view override returns (uint256) {\n\t\trequire(slashExists(candidate), 'Slasher: nonexistent slash');\n\t\treturn nonces[candidate];\n\t}\n\n\tfunction _initNonce() internal {\n\t\tnonce = 1;\n\t}\n\n\tfunction setDrafterCoef(uint64 _drafterCoef) external override onlyOwner {\n\t\t_setDrafterCoef(_drafterCoef);\n\t}\n\n\tfunction setValidatorCoef(uint64 _validatorCoef) external override onlyOwner {\n\t\t_setValidatorCoef(_validatorCoef);\n\t}\n\n\tfunction setExecutorCoef(uint64 _executorCoef) external override onlyOwner {\n\t\t_setExecutorCoef(_executorCoef);\n\t}\n\n\tfunction _setMaxCoef(uint64 maxCoef) internal {\n\t\tMAXCOEF = maxCoef;\n\t\temit MaxCoefUpdated(maxCoef);\n\t}\n\n\tfunction _setDrafterCoef(uint64 _drafterCoef) internal {\n\t\trequire(_drafterCoef + validatorCoef + executorCoef <= MAXCOEF, 'Slasher: invalid coefficient');\n\t\tdrafterCoef = _drafterCoef;\n\t\temit DrafterCoefUpdated(_drafterCoef);\n\t}\n\n\tfunction _setValidatorCoef(uint64 _validatorCoef) internal {\n\t\trequire(drafterCoef + _validatorCoef + executorCoef <= MAXCOEF, 'Slasher: invalid coefficient');\n\t\tvalidatorCoef = _validatorCoef;\n\t\temit ValidatorCoefUpdated(_validatorCoef);\n\t}\n\n\tfunction _setExecutorCoef(uint64 _executorCoef) internal {\n\t\trequire(drafterCoef + validatorCoef + _executorCoef <= MAXCOEF, 'Slasher: invalid coefficient');\n\t\texecutorCoef = _executorCoef;\n\t\temit ExecutorCoefUpdated(_executorCoef);\n\t}\n\n\tfunction _setGovernance(address _governance) internal {\n\t\tgovernance = _governance;\n\t\temit GovernanceUpdated(_governance);\n\t}\n\n\tfunction _setCandidateSlash(ICandidateSlash _candidateSlash) internal {\n\t\tcandidateSlash = _candidateSlash;\n\t\temit CandidateSlashUpdated(_candidateSlash);\n\t}\n\n\tfunction _setMajorCandidates(IMajorCandidates _majorCandidates) internal {\n\t\tmajorCandidates = _majorCandidates;\n\t\temit MajorCandidatesUpdated(_majorCandidates);\n\t}\n\n\tfunction _setDefaultSlashAmount(uint256 amount) internal {\n\t\tdefaultSlashAmount = amount;\n\t\temit DefaultSlashAmountUpdated(amount);\n\t}\n\n\tfunction _setPublicNoticePeriod(uint256 period) internal {\n\t\tpublicNoticePeriod = period;\n\t\temit PublicNoticePeriodUpdated(period);\n\t}\n\n\tfunction changeGovernance(address newGovernance) external onlyGovernance {\n\t\t_setGovernance(newGovernance);\n\t}\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS,\n        InvalidSignatureV\n    }\n\n    function _throwError(RecoverError error) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert(\"ECDSA: invalid signature\");\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert(\"ECDSA: invalid signature length\");\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert(\"ECDSA: invalid signature 's' value\");\n        } else if (error == RecoverError.InvalidSignatureV) {\n            revert(\"ECDSA: invalid signature 'v' value\");\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature` or error string. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n        // Check the signature length\n        // - case 65: r,s,v signature (standard)\n        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            /// @solidity memory-safe-assembly\n            assembly {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else if (signature.length == 64) {\n            bytes32 r;\n            bytes32 vs;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            /// @solidity memory-safe-assembly\n            assembly {\n                r := mload(add(signature, 0x20))\n                vs := mload(add(signature, 0x40))\n            }\n            return tryRecover(hash, r, vs);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength);\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, signature);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address, RecoverError) {\n        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n        uint8 v = uint8((uint256(vs) >> 255) + 27);\n        return tryRecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     *\n     * _Available since v4.2._\n     */\n    function recover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address, RecoverError) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS);\n        }\n        if (v != 27 && v != 28) {\n            return (address(0), RecoverError.InvalidSignatureV);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature);\n        }\n\n        return (signer, RecoverError.NoError);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from `s`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", StringsUpgradeable.toString(s.length), s));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Typed Data, created from a\n     * `domainSeparator` and a `structHash`. This produces hash corresponding\n     * to the one signed with the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n     * JSON-RPC method as part of EIP-712.\n     *\n     * See {recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n    }\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n            value /= 10;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        if (value == 0) {\n            return \"0x00\";\n        }\n        uint256 temp = value;\n        uint256 length = 0;\n        while (temp != 0) {\n            length++;\n            temp >>= 8;\n        }\n        return toHexString(value, length);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _HEX_SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n}\n"
    },
    "contracts/mock/MockSlasher.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../slasher/Slasher.sol';\n\ncontract MockSlasher is Slasher {\n\n\tfunction init(\n\t\taddress newOwner,\n\t\taddress _governance,\n\t\tICandidateSlash _candidateSlash,\n\t\tIMajorCandidates _majorCandidates,\n\t\tuint256 _defaultSlashAmount,\n\t\tuint256 _publicNoticePeriod,\n\t\tuint64 maxCoef,\n\t\tuint64 _drafterCoef,\n\t\tuint64 _validatorCoef,\n\t\tuint64 _executorCoef\n\t) external {\n\t\t_transferOwnership(newOwner);\n\t\t_initNonce();\n\t\t_setGovernance(_governance);\n\t\t_setCandidateSlash(_candidateSlash);\n\t\t_setMajorCandidates(_majorCandidates);\n\t\t_setDefaultSlashAmount(_defaultSlashAmount);\n\t\t_setPublicNoticePeriod(_publicNoticePeriod);\n\t\t_setMaxCoef(maxCoef);\n\t\t_setDrafterCoef(_drafterCoef);\n\t\t_setValidatorCoef(_validatorCoef);\n\t\t_setExecutorCoef(_executorCoef);\n\t}\n\n}"
    },
    "contracts/election/MajorCandidates.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\nimport '../interfaces/IMajorCandidates.sol';\n\ncontract MajorCandidates is IMajorCandidates, Initializable {\n\n\tstruct Candidate {\n\t\taddress prev;\n\t\taddress next;\n\t\tuint256 amount;\n\t}\n\n\tICandidateElection public override candidateElection;\n\n\tIElection public override election;\n\n\taddress public headCandidate;\n\n\taddress public tailCandidate;\n\n\tuint256 public totalCandidates;\n\n\tmapping(address => Candidate) public candidates;\n\n\tuint256 public override MAX_MAJOR_CANDIDATES;\n\n\tmodifier onlyCandidateElection() {\n\t\trequire(msg.sender == address(candidateElection), 'MajorCandidates: caller must be CandidateElection contract');\n\t\t_;\n\t}\n\n\tmodifier onlyElection() {\n\t\trequire(msg.sender == address(election), 'MajorCandidates: caller must be Election contract');\n\t\t_;\n\t}\n\n\tfunction initialize(\n\t\tICandidateElection _candidateElection,\n\t\tIElection _election\n\t) external initializer {\n\t\t_setCandidateElection(_candidateElection);\n\t\t_setElection(_election);\n\t\t_setMaxMajorLength(9);\n\t}\n\n\tfunction existsInMajor(address candidate) public view override returns(bool existed) {\n\t\tif (headCandidate != address(0)) {\n\t\t\taddress from = headCandidate;\n\t\t\tfor (uint256 i = 0; i < MAX_MAJOR_CANDIDATES; i++) {\n\t\t\t\tif (from == candidate) {\n\t\t\t\t\texisted = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tfrom = candidates[from].next;\n\t\t\t\tif (from == address(0)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction majorCandidateList() public view override returns(address[] memory majors) {\n\t\tuint256 limit = totalCandidates > MAX_MAJOR_CANDIDATES? MAX_MAJOR_CANDIDATES : totalCandidates;\n\t\tif (headCandidate != address(0)) {\n\t\t\tmajors = new address[](limit);\n\t\t\taddress candidate = headCandidate;\n\t\t\tfor (uint256 i = 0; i < limit; i++) {\n\t\t\t\tmajors[i] = candidate;\n\t\t\t\tcandidate = candidates[candidate].next;\n\t\t\t\tif (candidate == address(0)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction upset(address candidate, uint256 amount, address prev, address next) external override onlyElection {\n\t\t_massDowngrade();\n\t\tif (!exists(candidate)) {\n\t\t\t_addCandidate(candidate, amount, prev, next);\n\t\t} else {\n\t\t\tif (amount == 0) {\n\t\t\t\t_removeCandidate(candidate);\n\t\t\t} else {\n\t\t\t\t_updateCandidate(candidate, amount, prev, next);\n\t\t\t}\n\t\t}\n\t\t_massUpgrade();\n\t}\n\n\tfunction _massDowngrade() internal {\n\t\tuint256 limit = totalCandidates > MAX_MAJOR_CANDIDATES? MAX_MAJOR_CANDIDATES : totalCandidates;\n\t\tif (headCandidate != address(0)) {\n\t\t\taddress candidate = headCandidate;\n\t\t\tfor (uint256 i = 0; i < limit; i++) {\n\t\t\t\tcandidateElection.downgrade(candidate);\n\t\t\t\tcandidate = candidates[candidate].next;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction _massUpgrade() internal {\n\t\tuint256 limit = totalCandidates > MAX_MAJOR_CANDIDATES? MAX_MAJOR_CANDIDATES : totalCandidates;\n\t\tif (headCandidate != address(0)) {\n\t\t\taddress candidate = headCandidate;\n\t\t\tfor (uint256 i = 0; i < limit; i++) {\n\t\t\t\tcandidateElection.upgrade(candidate);\n\t\t\t\tcandidate = candidates[candidate].next;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction _addCandidate(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress prev,\n\t\taddress next\n\t) internal {\n\t\trequire(!exists(candidate), 'MajorCandidates: candidate exists');\n\t\tif (headCandidate != address(0)) {\n\t\t\t// insert into head\n\t\t\tif (prev == address(0)) {\n\t\t\t\trequire(next == headCandidate, 'MajorCandidates: next must be current head candidte');\n\t\t\t\trequire(candidates[next].amount < amount, 'MajorCandidates: amount is less than current head candidate');\n\t\t\t\tcandidates[next].prev = candidate;\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t\theadCandidate = candidate;\n\t\t\t} else {\n\t\t\t\t// insert into tail\n\t\t\t\tif (next == address(0)) {\n\t\t\t\t\trequire(candidates[prev].next == address(0), 'MajorCandidates: prev must be current tail candidate');\n\t\t\t\t\trequire(candidates[prev].amount > amount, 'MajorCandidates: amount is larger than current tail candidate');\n\t\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\t\tcandidates[prev].next = candidate;\n\t\t\t\t\ttailCandidate = candidate;\n\t\t\t\t} else {\n\t\t\t\t\t// insert into body\n\t\t\t\t\trequire(candidates[prev].next == next, 'MajorCandidates: the next of the prev must be the next');\n\t\t\t\t\trequire(candidates[next].prev == prev, 'MajorCandidates: the prev of the next must be the prev');\n\t\t\t\t\trequire(amount < candidates[prev].amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\t\trequire(amount > candidates[next].amount, 'MajorCandidates: amount is less than next amount');\n\t\t\t\t\tcandidates[prev].next = candidate;\n\t\t\t\t\tcandidates[next].prev = candidate;\n\t\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\t\tcandidates[candidate].next = next;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\theadCandidate = candidate;\n\t\t}\n\t\tcandidates[candidate].amount = amount;\n\t\ttotalCandidates++;\n\t\temit AddCandidate(candidate, amount, prev, next);\n\t}\n\n\tfunction _updateCandidate(\n\t\taddress candidate,\n\t\tuint256 amount,\n\t\taddress prev,\n\t\taddress next\n\t) internal {\n\t\trequire(exists(candidate), 'MajorCandidates: nonexistent candidate');\n\t\taddress curPrev = candidates[candidate].prev;\n\t\taddress curNext = candidates[candidate].next;\n\t\t// head candidate\n\t\tif (curPrev == address(0)) {\n\t\t\tif (prev == address(0)) {\n\t\t\t\t// head -> head\n\t\t\t\trequire(next == curNext, 'MajorCandidates: invalid next');\n\t\t\t\tif (curNext != address(0)) {\n\t\t\t\t\trequire(amount > candidates[curNext].amount, 'MajorCandidates: amount is less than the next');\n\t\t\t\t}\n\t\t\t} else if (next == address(0)) {\n\t\t\t\t// head -> tail\n\t\t\t\trequire(candidates[prev].next == address(0), 'MajorCandidates: the prev must be current tail candidate');\n\t\t\t\trequire(candidates[prev].amount > amount, 'MajorCandidates: the amount is larger than current tail candidate amount');\n\t\t\t\theadCandidate = curNext;\n\t\t\t\tcandidates[curNext].prev = address(0);\n\t\t\t\tcandidates[prev].next = candidate;\n\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\tcandidates[candidate].next = address(0);\n\t\t\t\ttailCandidate = candidate;\n\t\t\t} else {\n\t\t\t\t// head -> body\n\t\t\t\trequire(candidates[prev].next == next, 'MajorCandidates: the next of the prev must be the next');\n\t\t\t\trequire(candidates[next].prev == prev, 'MajorCandidates: the prev of the next must be the prev');\n\t\t\t\trequire(amount < candidates[prev].amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\trequire(amount > candidates[next].amount, 'MajorCandidates: amount is less than next amount');\n\t\t\t\theadCandidate = curNext;\n\t\t\t\tcandidates[curNext].prev = address(0);\n\t\t\t\tcandidates[prev].next == candidate;\n\t\t\t\tcandidates[next].prev == candidate;\n\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t}\n\t\t} else if (curNext == address(0)) {\n\t\t\tif (prev == address(0)) {\n\t\t\t\t// tail -> head\n\t\t\t\trequire(next == headCandidate, 'MajorCandidates: next must be head candidate');\n\t\t\t\trequire(amount > candidates[headCandidate].amount, 'MajorCandidates: amount is less than the head candidate amount');\n\t\t\t\tcandidates[next].prev = candidate;\n\t\t\t\tcandidates[candidate].prev = address(0);\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t\theadCandidate = candidate;\n\t\t\t} else if (next == address(0)) {\n\t\t\t\t// tail -> tail\n\t\t\t\trequire(candidates[candidate].prev == prev, 'MajorCandidates: the prev must be current tail candidate prev');\n\t\t\t\trequire(candidates[prev].amount > amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\ttailCandidate = candidate;\n\t\t\t} else {\n\t\t\t\t// tail -> body\n\t\t\t\trequire(candidates[prev].next == next, 'MajorCandidates: the next of the prev must be the next');\n\t\t\t\trequire(candidates[next].prev == prev, 'MajorCandidates: the prev of the next must be the prev');\n\t\t\t\trequire(amount < candidates[prev].amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\trequire(amount > candidates[next].amount, 'MajorCandidates: amount is less than next amount');\n\t\t\t\tcandidates[curPrev].next = address(0);\n\t\t\t\tcandidates[prev].next == candidate;\n\t\t\t\tcandidates[next].prev == candidate;\n\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t}\n\t\t} else {\n\t\t\tif (prev == address(0)) {\n\t\t\t\t// body -> head\n\t\t\t\trequire(next == headCandidate, 'MajorCandidates: next must be head candidate');\n\t\t\t\trequire(amount > candidates[headCandidate].amount, 'MajorCandidates: amount is less than the head candidate amount');\n\t\t\t\tcandidates[next].prev = candidate;\n\t\t\t\tcandidates[candidate].prev = address(0);\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t\tcandidates[curPrev].next = curNext;\n\t\t\t\tcandidates[curNext].prev = curPrev;\n\t\t\t\theadCandidate = candidate;\n\t\t\t} else if (next == address(0)) {\n\t\t\t\t// body -> tail\n\t\t\t\trequire(candidates[prev].next == address(0), 'MajorCandidates: the prev must be current tail candidate');\n\t\t\t\trequire(candidates[prev].amount > amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\ttailCandidate = candidate;\n\t\t\t\tcandidates[curPrev].next = curNext;\n\t\t\t\tcandidates[curNext].prev = curPrev;\n\t\t\t\tcandidates[prev].next = candidate;\n\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\tcandidates[candidate].next = address(0);\n\t\t\t\ttailCandidate = candidate;\n\t\t\t} else {\n\t\t\t\t// body -> body\n\t\t\t\trequire(candidates[prev].next == next, 'MajorCandidates: the next of the prev must be the next');\n\t\t\t\trequire(candidates[next].prev == prev, 'MajorCandidates: the prev of the next must be the prev');\n\t\t\t\trequire(amount < candidates[prev].amount, 'MajorCandidates: amount is larger than prev amount');\n\t\t\t\trequire(amount > candidates[next].amount, 'MajorCandidates: amount is less than next amount');\n\t\t\t\tcandidates[curPrev].next = curNext;\n\t\t\t\tcandidates[curNext].prev = curPrev;\n\t\t\t\tcandidates[candidate].prev = prev;\n\t\t\t\tcandidates[candidate].next = next;\n\t\t\t\tcandidates[prev].next = candidate;\n\t\t\t\tcandidates[next].prev = candidate;\n\t\t\t}\n\t\t}\n\t\tcandidates[candidate].amount = amount;\n\t\temit UpdateCandidate(candidate, amount, prev, next);\n\t}\n\n\tfunction slipUpdate(address candidate, uint256 amount, uint256 slippage) external override onlyElection {\n\t\t_massDowngrade();\n\t\t_slipUpdateCandidate(candidate, amount, slippage);\n\t\t_massUpgrade();\n\t}\n\n\tfunction _slipUpdateCandidate(address candidate, uint256 amount, uint256 slippage) internal {\n\t\trequire(exists(candidate), 'MajorCandidates: nonexistent candidate');\n\t\tif (amount == 0) {\n\t\t\treturn _removeCandidate(candidate);\n\t\t}\n\t\tuint256 curAmount = candidates[candidate].amount;\n\t\tif (curAmount < amount) {\n\t\t\tfor (uint256 i = 0; i < slippage; i++) {\n\t\t\t\taddress curPrev = candidates[candidate].prev;\n\t\t\t\tif (curPrev == address(0)) {\n\t\t\t\t\t// head candidate\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tuint256 prevAmount = candidates[curPrev].amount;\n\t\t\t\tif (prevAmount > amount) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\taddress curNext = candidates[candidate].next;\n\t\t\t\taddress prevDouble = candidates[curPrev].prev;\n\t\t\t\tcandidates[curPrev].next = curNext;\n\t\t\t\tcandidates[curPrev].prev = candidate;\n\t\t\t\tcandidates[curNext].prev = curPrev;\n\t\t\t\tcandidates[candidate].prev = prevDouble;\n\t\t\t\tcandidates[candidate].next = curPrev;\n\t\t\t\tif (prevDouble != address(0)) {\n\t\t\t\t\t// cur prev is not head candidate\n\t\t\t\t\tcandidates[prevDouble].next = candidate;\n\t\t\t\t} else {\n\t\t\t\t\theadCandidate = candidate;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (curAmount > amount) {\n\t\t\tfor (uint256 i = 0; i < slippage; i++) {\n\t\t\t\taddress curNext = candidates[candidate].next;\n\t\t\t\tif (curNext == address(0)) {\n\t\t\t\t\t// tail candidate\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tuint256 nextAmount = candidates[curNext].amount;\n\t\t\t\tif (nextAmount < amount) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\taddress curPrev = candidates[candidate].prev;\n\t\t\t\taddress nextDouble = candidates[curNext].next;\n\t\t\t\tcandidates[curNext].next = candidate;\n\t\t\t\tcandidates[curNext].prev = curPrev;\n\t\t\t\tcandidates[curPrev].next = curNext;\n\t\t\t\tcandidates[candidate].prev = curNext;\n\t\t\t\tcandidates[candidate].next = nextDouble;\n\t\t\t\tif (nextDouble != address(0)) {\n\t\t\t\t\t// cur next is not tail candidate\n\t\t\t\t\tcandidates[nextDouble].prev = candidate;\n\t\t\t\t} else {\n\t\t\t\t\ttailCandidate = candidate;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\taddress prev = candidates[candidate].prev;\n\t\taddress next = candidates[candidate].next;\n\t\tif (prev != address(0) && next != address(0)) {\n\t\t\trequire(candidates[next].amount < amount && candidates[prev].amount > amount, 'MajorCandidates: invalid candidate order');\n\t\t}\n\t\tcandidates[candidate].amount = amount;\n\t\temit UpdateCandidate(candidate, amount, prev, next);\n\t}\n\n\tfunction remove(address candidate) external override onlyCandidateElection {\n\t\t_removeCandidate(candidate);\n\t}\n\n\tfunction _removeCandidate(address candidate) internal {\n\t\trequire(exists(candidate), 'MajorCandidates: nonexistent candidate');\n\t\taddress curPrev = candidates[candidate].prev;\n\t\taddress curNext = candidates[candidate].next;\n\t\tif (curPrev == address(0)) {\n\t\t\t// remove head\n\t\t\tif (curNext == address(0)) {\n\t\t\t\theadCandidate = address(0);\n\t\t\t} else {\n\t\t\t\tcandidates[curNext].prev = address(0);\n\t\t\t\theadCandidate = curNext;\n\t\t\t}\n\t\t} else if (curNext == address(0)){\n\t\t\t// remove tail\n\t\t\tcandidates[curPrev].next = address(0);\n\t\t\ttailCandidate = curPrev;\n\t\t} else {\n\t\t\t// remove body\n\t\t\tcandidates[curPrev].next = curNext;\n\t\t\tcandidates[curNext].prev = curPrev;\n\t\t}\n\t\tdelete candidates[candidate];\n\t\ttotalCandidates--;\n\t\temit RemoveCandidate(candidate);\n\t}\n\n\tfunction exists(address candidate) public view override returns (bool) {\n\t\treturn candidates[candidate].amount > 0;\n\t}\n\n\tfunction _setCandidateElection(ICandidateElection _candidateElection) internal {\n\t\tcandidateElection = _candidateElection;\n\t\temit CandidateElectionUpdated(_candidateElection);\n\t}\n\n\tfunction _setElection(IElection _election) internal {\n\t\telection = _election;\n\t\temit ElectionUpdated(_election);\n\t}\n\n\tfunction _setMaxMajorLength(uint256 length) internal {\n\t\tMAX_MAJOR_CANDIDATES = length;\n\t\temit MaxNodesLengthUpdated(length);\n\t}\n}\n"
    },
    "contracts/mock/MockMajorCandidates.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../election/MajorCandidates.sol';\n\ncontract MockMajorCandidates is MajorCandidates {\n\n\tfunction init(ICandidateElection _candidateElection, IElection _election) external {\n\t\t_setCandidateElection(_candidateElection);\n\t\t_setElection(_election);\n\t\t_setMaxMajorLength(9);\n\t}\n\n}"
    },
    "contracts/mock/MockStake.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../stake/Stake.sol';\n\ncontract MockStake is Stake {\n\n\tfunction init(\n\t\tIERC20 token,\n\t\tIRewarder rewarder,\n\t\tIElection election,\n\t\tIMajorCandidates majorCandidates,\n\t\tISlasher slasher,\n\t\tuint256 stakeFrozenPeriod,\n\t\tuint256 mintStake,\n\t\tuint256 rewardPerSecond\n\t) external {\n\t\t_setToken(token);\n\t\t_setRewarder(rewarder);\n\t\t_setElection(election);\n\t\t_setMajorCandidates(majorCandidates);\n\t\t_setSlasher(slasher);\n\t\t_setStakeFrozenPeriod(stakeFrozenPeriod);\n\t\t_setMinStake(mintStake);\n\t\t_setRewardPerSecond(rewardPerSecond);\n\t\t_setMaxCoef(1e6);\n\t\t_setAccPrecision(1e12);\n\t\t_addPool(Types.Grade.Major, 750);\n\t\t_addPool(Types.Grade.Secondary, 250);\n\t}\n\n}"
    },
    "contracts/stake/Rewarder.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\nimport '../interfaces/IRewarder.sol';\n\ncontract Rewarder is IRewarder, Initializable {\n\n\tIERC20Upgradeable public override token;\n\n\taddress public stake;\n\n\tmodifier onlyStake() {\n\t\trequire(msg.sender == stake, 'Rewarder: caller is not stake contract');\n\t\t_;\n\t}\n\n\tfunction initialize(IERC20Upgradeable _token, address _stake) external initializer {\n\t\t_setToken(_token);\n\t\t_setStake(_stake);\n\t}\n\n\tfunction _setToken(IERC20Upgradeable _token) internal {\n\t\ttoken = _token;\n\t\temit TokenUpdated(token);\n\t}\n\n\tfunction _setStake(address _stake) internal {\n\t\tstake = _stake;\n\t\temit StakeUpdated(stake);\n\t}\n\n\tfunction sendReward(address to, uint256 amount) external override onlyStake {\n\t\ttoken.transfer(to, amount);\n\t\temit SendReward(to, amount);\n\t}\n\n}\n"
    },
    "contracts/mock/MockRewarder.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity >=0.8.0;\n\nimport '../stake/Rewarder.sol';\n\ncontract MockRewarder is Rewarder {\n\n\tfunction init(IERC20Upgradeable _token, address _stake) external {\n\t\t_setToken(_token);\n\t\t_setStake(_stake);\n\t}\n\n}"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200,
      "details": {
        "yul": false
      }
    },
    "outputSelection": {
      "*": {
        "*": [
          "storageLayout",
          "abi",
          "evm.bytecode",
          "evm.deployedBytecode",
          "evm.methodIdentifiers",
          "metadata",
          "devdoc",
          "userdoc",
          "evm.gasEstimates"
        ],
        "": [
          "ast"
        ]
      }
    },
    "metadata": {
      "useLiteralContent": true
    }
  }
}