ETH Price: $2,564.67 (-3.09%)

Transaction Decoder

Block:
21313912 at Dec-02-2024 09:24:35 AM +UTC
Transaction Fee:
0.002034089046343101 ETH $5.22
Gas Used:
129,151 Gas / 15.749696451 Gwei

Emitted Events:

80 PolygonEcosystemToken.Transfer( from=StakeManagerProxy, to=[Sender] 0xd0c0e4176630f123218fd552eeb1dfcb1d4d4d97, value=1356820000000000000000 )
81 EventsHubProxy.0x7beb9bef91040fcf7607c78d4fc668370a9036788d7e6f202a4a2db5b0c28c80( 0x7beb9bef91040fcf7607c78d4fc668370a9036788d7e6f202a4a2db5b0c28c80, 0x0000000000000000000000000000000000000000000000000000000000000076, 0x000000000000000000000000d0c0e4176630f123218fd552eeb1dfcb1d4d4d97, 0000000000000000000000000000000000000000000000498da8f94271820000, 0000000000000000000000000000000000000000000000000000000000000001 )

Account State Difference:

  Address   Before After State Difference Code
0x3EDBF7E0...409364269
0x455e53CB...44aFFC3F6
(beaverbuild)
6.13903678020805008 Eth6.13935965770805008 Eth0.0003228775
0xd0c0e417...B1d4D4D97
1.184000924922722132 Eth
Nonce: 4
1.181966835876379031 Eth
Nonce: 5
0.002034089046343101

Execution Trace

ValidatorShareProxy.8759c234( )
  • Registry.STATICCALL( )
  • ValidatorShare.unstakeClaimTokens_newPOL( unbondNonce=1 )
    • StakeManagerProxy.STATICCALL( )
      • StakeManager.DELEGATECALL( )
      • StakeManagerProxy.STATICCALL( )
        • StakeManager.DELEGATECALL( )
        • StakeManagerProxy.c7f067cb( )
          • StakeManager.transferFundsPOL( validatorId=118, amount=1356820000000000000000, delegator=0xd0c0e4176630F123218fD552EeB1dfcB1d4D4D97 ) => ( True )
            • PolygonEcosystemToken.transfer( to=0xd0c0e4176630F123218fD552EeB1dfcB1d4D4D97, amount=1356820000000000000000 ) => ( True )
            • EventsHubProxy.6e699d87( )
              • EventsHub.logDelegatorUnstakedWithId( validatorId=118, user=0xd0c0e4176630F123218fD552EeB1dfcB1d4D4D97, amount=1356820000000000000000, nonce=1 )
                • Registry.STATICCALL( )
                • StakeManagerProxy.35aa2e44( )
                  • StakeManager.validators( 118 ) => ( amount=2550000000000000000000, reward=11339326979298524117723, activationEpoch=11448, deactivationEpoch=0, jailTime=0, signer=0x5fFD4EFfD8E476C72FddC75BcD31f421001F9Ce6, contractAddress=0x3EDBF7E027D280BCd8126a87f382941409364269, status=1, commissionRate=3, lastCommissionUpdate=40943, delegatorsReward=1, delegatedAmount=1323598700637260488613613, initialRewardPerStake=2976552080362514459518977 )
                    File 1 of 8: ValidatorShareProxy
                    // File: openzeppelin-solidity/contracts/ownership/Ownable.sol
                    
                    pragma solidity ^0.5.2;
                    
                    /**
                     * @title Ownable
                     * @dev The Ownable contract has an owner address, and provides basic authorization control
                     * functions, this simplifies the implementation of "user permissions".
                     */
                    contract Ownable {
                        address private _owner;
                    
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    
                        /**
                         * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                         * account.
                         */
                        constructor () internal {
                            _owner = msg.sender;
                            emit OwnershipTransferred(address(0), _owner);
                        }
                    
                        /**
                         * @return the address of the owner.
                         */
                        function owner() public view returns (address) {
                            return _owner;
                        }
                    
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(isOwner());
                            _;
                        }
                    
                        /**
                         * @return true if `msg.sender` is the owner of the contract.
                         */
                        function isOwner() public view returns (bool) {
                            return msg.sender == _owner;
                        }
                    
                        /**
                         * @dev Allows the current owner to relinquish control of the contract.
                         * It will not be possible to call the functions with the `onlyOwner`
                         * modifier anymore.
                         * @notice Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                    
                        /**
                         * @dev Allows the current owner to transfer control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function transferOwnership(address newOwner) public onlyOwner {
                            _transferOwnership(newOwner);
                        }
                    
                        /**
                         * @dev Transfers control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function _transferOwnership(address newOwner) internal {
                            require(newOwner != address(0));
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    
                    // File: contracts/common/misc/ProxyStorage.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract ProxyStorage is Ownable {
                        address internal proxyTo;
                    }
                    
                    // File: contracts/common/misc/ERCProxy.sol
                    
                    /*
                     * SPDX-License-Identitifer:    MIT
                     */
                    
                    pragma solidity ^0.5.2;
                    
                    // See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md
                    
                    interface ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId);
                        function implementation() external view returns (address codeAddr);
                    }
                    
                    // File: contracts/common/misc/DelegateProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    contract DelegateProxy is ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId) {
                            // Upgradeable proxy
                            proxyTypeId = 2;
                        }
                    
                        function implementation() external view returns (address);
                    
                        function delegatedFwd(address _dst, bytes memory _calldata) internal {
                            // solium-disable-next-line security/no-inline-assembly
                            assembly {
                                let result := delegatecall(
                                    sub(gas, 10000),
                                    _dst,
                                    add(_calldata, 0x20),
                                    mload(_calldata),
                                    0,
                                    0
                                )
                                let size := returndatasize
                    
                                let ptr := mload(0x40)
                                returndatacopy(ptr, 0, size)
                    
                                // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                // if the call returned error data, forward it
                                switch result
                                    case 0 {
                                        revert(ptr, size)
                                    }
                                    default {
                                        return(ptr, size)
                                    }
                            }
                        }
                    }
                    
                    // File: contracts/common/misc/UpgradableProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract UpgradableProxy is DelegateProxy {
                        event ProxyUpdated(address indexed _new, address indexed _old);
                        event OwnerUpdate(address _new, address _old);
                    
                        bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation");
                        bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner");
                    
                        constructor(address _proxyTo) public {
                            setOwner(msg.sender);
                            setImplementation(_proxyTo);
                        }
                    
                        function() external payable {
                            // require(currentContract != 0, "If app code has not been set yet, do not call");
                            // Todo: filter out some calls or handle in the end fallback
                            delegatedFwd(loadImplementation(), msg.data);
                        }
                    
                        modifier onlyProxyOwner() {
                            require(loadOwner() == msg.sender, "NOT_OWNER");
                            _;
                        }
                    
                        function owner() external view returns(address) {
                            return loadOwner();
                        }
                    
                        function loadOwner() internal view returns(address) {
                            address _owner;
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                _owner := sload(position)
                            }
                            return _owner;
                        }
                    
                        function implementation() external view returns (address) {
                            return loadImplementation();
                        }
                    
                        function loadImplementation() internal view returns(address) {
                            address _impl;
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                _impl := sload(position)
                            }
                            return _impl;
                        }
                    
                        function transferOwnership(address newOwner) public onlyProxyOwner {
                            require(newOwner != address(0), "ZERO_ADDRESS");
                            emit OwnerUpdate(newOwner, loadOwner());
                            setOwner(newOwner);
                        }
                    
                        function setOwner(address newOwner) private {
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                sstore(position, newOwner)
                            }
                        }
                    
                        function updateImplementation(address _newProxyTo) public onlyProxyOwner {
                            require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS");
                            require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT");
                    
                            emit ProxyUpdated(_newProxyTo, loadImplementation());
                            
                            setImplementation(_newProxyTo);
                        }
                    
                        function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner {
                            updateImplementation(_newProxyTo);
                    
                            (bool success, bytes memory returnData) = address(this).call.value(msg.value)(data);
                            require(success, string(returnData));
                        }
                    
                        function setImplementation(address _newProxyTo) private {
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                sstore(position, _newProxyTo)
                            }
                        }
                        
                        function isContract(address _target) internal view returns (bool) {
                            if (_target == address(0)) {
                                return false;
                            }
                    
                            uint256 size;
                            assembly {
                                size := extcodesize(_target)
                            }
                            return size > 0;
                        }
                    }
                    
                    // File: contracts/common/governance/IGovernance.sol
                    
                    pragma solidity ^0.5.2;
                    
                    interface IGovernance {
                        function update(address target, bytes calldata data) external;
                    }
                    
                    // File: contracts/common/governance/Governable.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract Governable {
                        IGovernance public governance;
                    
                        constructor(address _governance) public {
                            governance = IGovernance(_governance);
                        }
                    
                        modifier onlyGovernance() {
                            require(
                                msg.sender == address(governance),
                                "Only governance contract is authorized"
                            );
                            _;
                        }
                    }
                    
                    // File: contracts/root/withdrawManager/IWithdrawManager.sol
                    
                    pragma solidity ^0.5.2;
                    
                    contract IWithdrawManager {
                        function createExitQueue(address token) external;
                    
                        function verifyInclusion(
                            bytes calldata data,
                            uint8 offset,
                            bool verifyTxInclusion
                        ) external view returns (uint256 age);
                    
                        function addExitToQueue(
                            address exitor,
                            address childToken,
                            address rootToken,
                            uint256 exitAmountOrTokenId,
                            bytes32 txHash,
                            bool isRegularExit,
                            uint256 priority
                        ) external;
                    
                        function addInput(
                            uint256 exitId,
                            uint256 age,
                            address utxoOwner,
                            address token
                        ) external;
                    
                        function challengeExit(
                            uint256 exitId,
                            uint256 inputId,
                            bytes calldata challengeData,
                            address adjudicatorPredicate
                        ) external;
                    }
                    
                    // File: contracts/common/Registry.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    
                    contract Registry is Governable {
                        // @todo hardcode constants
                        bytes32 private constant WETH_TOKEN = keccak256("wethToken");
                        bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
                        bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
                        bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
                        bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
                        bytes32 private constant CHILD_CHAIN = keccak256("childChain");
                        bytes32 private constant STATE_SENDER = keccak256("stateSender");
                        bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
                    
                        address public erc20Predicate;
                        address public erc721Predicate;
                    
                        mapping(bytes32 => address) public contractMap;
                        mapping(address => address) public rootToChildToken;
                        mapping(address => address) public childToRootToken;
                        mapping(address => bool) public proofValidatorContracts;
                        mapping(address => bool) public isERC721;
                    
                        enum Type {Invalid, ERC20, ERC721, Custom}
                        struct Predicate {
                            Type _type;
                        }
                        mapping(address => Predicate) public predicates;
                    
                        event TokenMapped(address indexed rootToken, address indexed childToken);
                        event ProofValidatorAdded(address indexed validator, address indexed from);
                        event ProofValidatorRemoved(address indexed validator, address indexed from);
                        event PredicateAdded(address indexed predicate, address indexed from);
                        event PredicateRemoved(address indexed predicate, address indexed from);
                        event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
                    
                        constructor(address _governance) public Governable(_governance) {}
                    
                        function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
                            emit ContractMapUpdated(_key, contractMap[_key], _address);
                            contractMap[_key] = _address;
                        }
                    
                        /**
                         * @dev Map root token to child token
                         * @param _rootToken Token address on the root chain
                         * @param _childToken Token address on the child chain
                         * @param _isERC721 Is the token being mapped ERC721
                         */
                        function mapToken(
                            address _rootToken,
                            address _childToken,
                            bool _isERC721
                        ) external onlyGovernance {
                            require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
                            rootToChildToken[_rootToken] = _childToken;
                            childToRootToken[_childToken] = _rootToken;
                            isERC721[_rootToken] = _isERC721;
                            IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
                            emit TokenMapped(_rootToken, _childToken);
                        }
                    
                        function addErc20Predicate(address predicate) public onlyGovernance {
                            require(predicate != address(0x0), "Can not add null address as predicate");
                            erc20Predicate = predicate;
                            addPredicate(predicate, Type.ERC20);
                        }
                    
                        function addErc721Predicate(address predicate) public onlyGovernance {
                            erc721Predicate = predicate;
                            addPredicate(predicate, Type.ERC721);
                        }
                    
                        function addPredicate(address predicate, Type _type) public onlyGovernance {
                            require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
                            predicates[predicate]._type = _type;
                            emit PredicateAdded(predicate, msg.sender);
                        }
                    
                        function removePredicate(address predicate) public onlyGovernance {
                            require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
                            delete predicates[predicate];
                            emit PredicateRemoved(predicate, msg.sender);
                        }
                    
                        function getValidatorShareAddress() public view returns (address) {
                            return contractMap[VALIDATOR_SHARE];
                        }
                    
                        function getWethTokenAddress() public view returns (address) {
                            return contractMap[WETH_TOKEN];
                        }
                    
                        function getDepositManagerAddress() public view returns (address) {
                            return contractMap[DEPOSIT_MANAGER];
                        }
                    
                        function getStakeManagerAddress() public view returns (address) {
                            return contractMap[STAKE_MANAGER];
                        }
                    
                        function getSlashingManagerAddress() public view returns (address) {
                            return contractMap[SLASHING_MANAGER];
                        }
                    
                        function getWithdrawManagerAddress() public view returns (address) {
                            return contractMap[WITHDRAW_MANAGER];
                        }
                    
                        function getChildChainAndStateSender() public view returns (address, address) {
                            return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
                        }
                    
                        function isTokenMapped(address _token) public view returns (bool) {
                            return rootToChildToken[_token] != address(0x0);
                        }
                    
                        function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
                            require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
                            return isERC721[_token];
                        }
                    
                        function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
                            if (isTokenMappedAndIsErc721(_token)) {
                                return erc721Predicate;
                            }
                            return erc20Predicate;
                        }
                    
                        function isChildTokenErc721(address childToken) public view returns (bool) {
                            address rootToken = childToRootToken[childToken];
                            require(rootToken != address(0x0), "Child token is not mapped");
                            return isERC721[rootToken];
                        }
                    }
                    
                    // File: contracts/staking/validatorShare/ValidatorShareProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    contract ValidatorShareProxy is UpgradableProxy {
                        constructor(address _registry) public UpgradableProxy(_registry) {}
                    
                        function loadImplementation() internal view returns (address) {
                            return Registry(super.loadImplementation()).getValidatorShareAddress();
                        }
                    }

                    File 2 of 8: StakeManagerProxy
                    // File: openzeppelin-solidity/contracts/ownership/Ownable.sol
                    
                    pragma solidity ^0.5.2;
                    
                    /**
                     * @title Ownable
                     * @dev The Ownable contract has an owner address, and provides basic authorization control
                     * functions, this simplifies the implementation of "user permissions".
                     */
                    contract Ownable {
                        address private _owner;
                    
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    
                        /**
                         * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                         * account.
                         */
                        constructor () internal {
                            _owner = msg.sender;
                            emit OwnershipTransferred(address(0), _owner);
                        }
                    
                        /**
                         * @return the address of the owner.
                         */
                        function owner() public view returns (address) {
                            return _owner;
                        }
                    
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(isOwner());
                            _;
                        }
                    
                        /**
                         * @return true if `msg.sender` is the owner of the contract.
                         */
                        function isOwner() public view returns (bool) {
                            return msg.sender == _owner;
                        }
                    
                        /**
                         * @dev Allows the current owner to relinquish control of the contract.
                         * It will not be possible to call the functions with the `onlyOwner`
                         * modifier anymore.
                         * @notice Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                    
                        /**
                         * @dev Allows the current owner to transfer control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function transferOwnership(address newOwner) public onlyOwner {
                            _transferOwnership(newOwner);
                        }
                    
                        /**
                         * @dev Transfers control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function _transferOwnership(address newOwner) internal {
                            require(newOwner != address(0));
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    // File: contracts/common/misc/ERCProxy.sol
                    
                    /*
                     * SPDX-License-Identitifer:    MIT
                     */
                    
                    pragma solidity ^0.5.2;
                    
                    // See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md
                    
                    interface ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId);
                        function implementation() external view returns (address codeAddr);
                    }
                    
                    // File: contracts/common/misc/DelegateProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    contract DelegateProxy is ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId) {
                            // Upgradeable proxy
                            proxyTypeId = 2;
                        }
                    
                        function implementation() external view returns (address);
                    
                        function delegatedFwd(address _dst, bytes memory _calldata) internal {
                            // solium-disable-next-line security/no-inline-assembly
                            assembly {
                                let result := delegatecall(
                                    sub(gas, 10000),
                                    _dst,
                                    add(_calldata, 0x20),
                                    mload(_calldata),
                                    0,
                                    0
                                )
                                let size := returndatasize
                    
                                let ptr := mload(0x40)
                                returndatacopy(ptr, 0, size)
                    
                                // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                // if the call returned error data, forward it
                                switch result
                                    case 0 {
                                        revert(ptr, size)
                                    }
                                    default {
                                        return(ptr, size)
                                    }
                            }
                        }
                    }
                    
                    // File: contracts/common/misc/UpgradableProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract UpgradableProxy is DelegateProxy {
                        event ProxyUpdated(address indexed _new, address indexed _old);
                        event OwnerUpdate(address _new, address _old);
                    
                        bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation");
                        bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner");
                    
                        constructor(address _proxyTo) public {
                            setOwner(msg.sender);
                            setImplementation(_proxyTo);
                        }
                    
                        function() external payable {
                            // require(currentContract != 0, "If app code has not been set yet, do not call");
                            // Todo: filter out some calls or handle in the end fallback
                            delegatedFwd(loadImplementation(), msg.data);
                        }
                    
                        modifier onlyProxyOwner() {
                            require(loadOwner() == msg.sender, "NOT_OWNER");
                            _;
                        }
                    
                        function owner() external view returns(address) {
                            return loadOwner();
                        }
                    
                        function loadOwner() internal view returns(address) {
                            address _owner;
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                _owner := sload(position)
                            }
                            return _owner;
                        }
                    
                        function implementation() external view returns (address) {
                            return loadImplementation();
                        }
                    
                        function loadImplementation() internal view returns(address) {
                            address _impl;
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                _impl := sload(position)
                            }
                            return _impl;
                        }
                    
                        function transferOwnership(address newOwner) public onlyProxyOwner {
                            require(newOwner != address(0), "ZERO_ADDRESS");
                            emit OwnerUpdate(newOwner, loadOwner());
                            setOwner(newOwner);
                        }
                    
                        function setOwner(address newOwner) private {
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                sstore(position, newOwner)
                            }
                        }
                    
                        function updateImplementation(address _newProxyTo) public onlyProxyOwner {
                            require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS");
                            require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT");
                    
                            emit ProxyUpdated(_newProxyTo, loadImplementation());
                            
                            setImplementation(_newProxyTo);
                        }
                    
                        function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner {
                            updateImplementation(_newProxyTo);
                    
                            (bool success, bytes memory returnData) = address(this).call.value(msg.value)(data);
                            require(success, string(returnData));
                        }
                    
                        function setImplementation(address _newProxyTo) private {
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                sstore(position, _newProxyTo)
                            }
                        }
                        
                        function isContract(address _target) internal view returns (bool) {
                            if (_target == address(0)) {
                                return false;
                            }
                    
                            uint256 size;
                            assembly {
                                size := extcodesize(_target)
                            }
                            return size > 0;
                        }
                    }
                    
                    // File: contracts/staking/stakeManager/StakeManagerProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract StakeManagerProxy is UpgradableProxy {
                        constructor(address _proxyTo) public UpgradableProxy(_proxyTo) {}
                    }

                    File 3 of 8: PolygonEcosystemToken
                    // SPDX-License-Identifier: MIT
                    pragma solidity 0.8.21;
                    import {ERC20, ERC20Permit, IERC20} from "openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol";
                    import {AccessControlEnumerable} from "openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol";
                    import {IPolygonEcosystemToken} from "./interfaces/IPolygonEcosystemToken.sol";
                    /// @title Polygon ERC20 token
                    /// @author Polygon Labs (@DhairyaSethi, @gretzke, @qedk, @simonDos)
                    /// @notice This is the Polygon ERC20 token contract on Ethereum L1
                    /// @dev The contract allows for a 1-to-1 representation between $POL and $MATIC and allows for additional emission based on hub and treasury requirements
                    /// @custom:security-contact [email protected]
                    contract PolygonEcosystemToken is ERC20Permit, AccessControlEnumerable, IPolygonEcosystemToken {
                        bytes32 public constant EMISSION_ROLE = keccak256("EMISSION_ROLE");
                        bytes32 public constant CAP_MANAGER_ROLE = keccak256("CAP_MANAGER_ROLE");
                        bytes32 public constant PERMIT2_REVOKER_ROLE = keccak256("PERMIT2_REVOKER_ROLE");
                        address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                        uint256 public mintPerSecondCap = 13.37e18;
                        uint256 public lastMint;
                        bool public permit2Enabled;
                        constructor(
                            address migration,
                            address emissionManager,
                            address protocolCouncil,
                            address emergencyCouncil
                        ) ERC20("Polygon Ecosystem Token", "POL") ERC20Permit("Polygon Ecosystem Token") {
                            if (
                                migration == address(0) ||
                                emissionManager == address(0) ||
                                protocolCouncil == address(0) ||
                                emergencyCouncil == address(0)
                            ) revert InvalidAddress();
                            _grantRole(DEFAULT_ADMIN_ROLE, protocolCouncil);
                            _grantRole(EMISSION_ROLE, emissionManager);
                            _grantRole(CAP_MANAGER_ROLE, protocolCouncil);
                            _grantRole(PERMIT2_REVOKER_ROLE, protocolCouncil);
                            _grantRole(PERMIT2_REVOKER_ROLE, emergencyCouncil);
                            _mint(migration, 10_000_000_000e18);
                            // we can safely set lastMint here since the emission manager is initialised after the token and won't hit the cap.
                            lastMint = block.timestamp;
                            _updatePermit2Allowance(true);
                        }
                        /// @inheritdoc IPolygonEcosystemToken
                        function mint(address to, uint256 amount) external onlyRole(EMISSION_ROLE) {
                            uint256 timeElapsedSinceLastMint = block.timestamp - lastMint;
                            uint256 maxMint = timeElapsedSinceLastMint * mintPerSecondCap;
                            if (amount > maxMint) revert MaxMintExceeded(maxMint, amount);
                            lastMint = block.timestamp;
                            _mint(to, amount);
                        }
                        /// @inheritdoc IPolygonEcosystemToken
                        function updateMintCap(uint256 newCap) external onlyRole(CAP_MANAGER_ROLE) {
                            emit MintCapUpdated(mintPerSecondCap, newCap);
                            mintPerSecondCap = newCap;
                        }
                        /// @inheritdoc IPolygonEcosystemToken
                        function updatePermit2Allowance(bool enabled) external onlyRole(PERMIT2_REVOKER_ROLE) {
                            _updatePermit2Allowance(enabled);
                        }
                        /// @dev The permit2 contract has full approval by default. If the approval is revoked, it can still be manually approved.
                        function allowance(address owner, address spender) public view override(ERC20, IERC20) returns (uint256) {
                            if (spender == PERMIT2 && permit2Enabled) return type(uint256).max;
                            return super.allowance(owner, spender);
                        }
                        /// @inheritdoc IPolygonEcosystemToken
                        function version() external pure returns (string memory) {
                            return "1.1.0";
                        }
                        function _updatePermit2Allowance(bool enabled) private {
                            emit Permit2AllowanceUpdated(enabled);
                            permit2Enabled = enabled;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)
                    pragma solidity ^0.8.0;
                    import "./IERC20Permit.sol";
                    import "../ERC20.sol";
                    import "../../../utils/cryptography/ECDSA.sol";
                    import "../../../utils/cryptography/EIP712.sol";
                    import "../../../utils/Counters.sol";
                    /**
                     * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                     *
                     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                     * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
                     * need to send a transaction, and thus is not required to hold Ether at all.
                     *
                     * _Available since v3.4._
                     */
                    abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
                        using Counters for Counters.Counter;
                        mapping(address => Counters.Counter) private _nonces;
                        // solhint-disable-next-line var-name-mixedcase
                        bytes32 private constant _PERMIT_TYPEHASH =
                            keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                        /**
                         * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
                         * However, to ensure consistency with the upgradeable transpiler, we will continue
                         * to reserve a slot.
                         * @custom:oz-renamed-from _PERMIT_TYPEHASH
                         */
                        // solhint-disable-next-line var-name-mixedcase
                        bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
                        /**
                         * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
                         *
                         * It's a good idea to use the same `name` that is defined as the ERC20 token name.
                         */
                        constructor(string memory name) EIP712(name, "1") {}
                        /**
                         * @dev See {IERC20Permit-permit}.
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public virtual override {
                            require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
                            bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
                            bytes32 hash = _hashTypedDataV4(structHash);
                            address signer = ECDSA.recover(hash, v, r, s);
                            require(signer == owner, "ERC20Permit: invalid signature");
                            _approve(owner, spender, value);
                        }
                        /**
                         * @dev See {IERC20Permit-nonces}.
                         */
                        function nonces(address owner) public view virtual override returns (uint256) {
                            return _nonces[owner].current();
                        }
                        /**
                         * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
                         */
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view override returns (bytes32) {
                            return _domainSeparatorV4();
                        }
                        /**
                         * @dev "Consume a nonce": return the current value and increment.
                         *
                         * _Available since v4.1._
                         */
                        function _useNonce(address owner) internal virtual returns (uint256 current) {
                            Counters.Counter storage nonce = _nonces[owner];
                            current = nonce.current();
                            nonce.increment();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
                    pragma solidity ^0.8.0;
                    import "./IAccessControlEnumerable.sol";
                    import "./AccessControl.sol";
                    import "../utils/structs/EnumerableSet.sol";
                    /**
                     * @dev Extension of {AccessControl} that allows enumerating the members of each role.
                     */
                    abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
                        using EnumerableSet for EnumerableSet.AddressSet;
                        mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
                        /**
                         * @dev See {IERC165-supportsInterface}.
                         */
                        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                            return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
                        }
                        /**
                         * @dev Returns one of the accounts that have `role`. `index` must be a
                         * value between 0 and {getRoleMemberCount}, non-inclusive.
                         *
                         * Role bearers are not sorted in any particular way, and their ordering may
                         * change at any point.
                         *
                         * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                         * you perform all queries on the same block. See the following
                         * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                         * for more information.
                         */
                        function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
                            return _roleMembers[role].at(index);
                        }
                        /**
                         * @dev Returns the number of accounts that have `role`. Can be used
                         * together with {getRoleMember} to enumerate all bearers of a role.
                         */
                        function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
                            return _roleMembers[role].length();
                        }
                        /**
                         * @dev Overload {_grantRole} to track enumerable memberships
                         */
                        function _grantRole(bytes32 role, address account) internal virtual override {
                            super._grantRole(role, account);
                            _roleMembers[role].add(account);
                        }
                        /**
                         * @dev Overload {_revokeRole} to track enumerable memberships
                         */
                        function _revokeRole(bytes32 role, address account) internal virtual override {
                            super._revokeRole(role, account);
                            _roleMembers[role].remove(account);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity 0.8.21;
                    import {IERC20Permit} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol";
                    import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
                    import {IAccessControlEnumerable} from "openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol";
                    /// @title Polygon ERC20 token
                    /// @author Polygon Labs (@DhairyaSethi, @gretzke, @qedk, @simonDos)
                    /// @notice This is the Polygon ERC20 token contract on Ethereum L1
                    /// @dev The contract allows for a 1-to-1 representation between $POL and $MATIC and allows for additional emission based on hub and treasury requirements
                    /// @custom:security-contact [email protected]
                    interface IPolygonEcosystemToken is IERC20, IERC20Permit, IAccessControlEnumerable {
                        /// @notice emitted when the mint cap is updated
                        /// @param oldCap the old mint cap
                        /// @param newCap the new mint cap
                        event MintCapUpdated(uint256 oldCap, uint256 newCap);
                        /// @notice emitted when the permit2 integration is enabled/disabled
                        /// @param enabled whether the permit2 integration is enabled or not
                        event Permit2AllowanceUpdated(bool enabled);
                        /// @notice thrown when a zero address is supplied during deployment
                        error InvalidAddress();
                        /// @notice thrown when the mint cap is exceeded
                        /// @param maxMint the maximum amount of tokens that can be minted
                        /// @param mintRequested the amount of tokens that were requested to be minted
                        error MaxMintExceeded(uint256 maxMint, uint256 mintRequested);
                        /// @notice mint token entrypoint for the emission manager contract
                        /// @param to address to mint to
                        /// @param amount amount to mint
                        /// @dev The function only validates the sender, the emission manager is responsible for correctness
                        function mint(address to, uint256 amount) external;
                        /// @notice update the limit of tokens that can be minted per second
                        /// @param newCap the amount of tokens in 18 decimals as an absolute value
                        function updateMintCap(uint256 newCap) external;
                        /// @notice manages the default max approval to the permit2 contract
                        /// @param enabled If true, the permit2 contract has full approval by default, if false, it has no approval by default
                        function updatePermit2Allowance(bool enabled) external;
                        /// @return the role that allows minting of tokens
                        function EMISSION_ROLE() external view returns (bytes32);
                        /// @return the role that allows updating the mint cap
                        function CAP_MANAGER_ROLE() external view returns (bytes32);
                        /// @return the role that allows revoking the permit2 approval
                        function PERMIT2_REVOKER_ROLE() external view returns (bytes32);
                        /// @return the address of the permit2 contract
                        function PERMIT2() external view returns (address);
                        /// @return currentMintPerSecondCap the current amount of tokens that can be minted per second
                        /// @dev 13.37 POL tokens per second. will limit emission in ~12 years
                        function mintPerSecondCap() external view returns (uint256 currentMintPerSecondCap);
                        /// @return lastMintTimestamp the timestamp of the last mint
                        function lastMint() external view returns (uint256 lastMintTimestamp);
                        /// @return isPermit2Enabled whether the permit2 default approval is currently active
                        function permit2Enabled() external view returns (bool isPermit2Enabled);
                        /// @notice returns the version of the contract
                        /// @return version version string
                        /// @dev this is to support our dev pipeline, and is present despite this contract not being behind a proxy
                        function version() external pure returns (string memory version);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                     *
                     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                     * need to send a transaction, and thus is not required to hold Ether at all.
                     */
                    interface IERC20Permit {
                        /**
                         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                         * given ``owner``'s signed approval.
                         *
                         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                         * ordering also apply here.
                         *
                         * Emits an {Approval} event.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         * - `deadline` must be a timestamp in the future.
                         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                         * over the EIP712-formatted function arguments.
                         * - the signature must use ``owner``'s current nonce (see {nonces}).
                         *
                         * For more information on the signature format, see the
                         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                         * section].
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                        /**
                         * @dev Returns the current nonce for `owner`. This value must be
                         * included whenever a signature is generated for {permit}.
                         *
                         * Every successful call to {permit} increases ``owner``'s nonce by one. This
                         * prevents a signature from being used multiple times.
                         */
                        function nonces(address owner) external view returns (uint256);
                        /**
                         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                         */
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
                    pragma solidity ^0.8.0;
                    import "./IERC20.sol";
                    import "./extensions/IERC20Metadata.sol";
                    import "../../utils/Context.sol";
                    /**
                     * @dev Implementation of the {IERC20} interface.
                     *
                     * This implementation is agnostic to the way tokens are created. This means
                     * that a supply mechanism has to be added in a derived contract using {_mint}.
                     * For a generic mechanism see {ERC20PresetMinterPauser}.
                     *
                     * TIP: For a detailed writeup see our guide
                     * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                     * to implement supply mechanisms].
                     *
                     * The default value of {decimals} is 18. To change this, you should override
                     * this function so it returns a different value.
                     *
                     * We have followed general OpenZeppelin Contracts guidelines: functions revert
                     * instead returning `false` on failure. This behavior is nonetheless
                     * conventional and does not conflict with the expectations of ERC20
                     * applications.
                     *
                     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                     * This allows applications to reconstruct the allowance for all accounts just
                     * by listening to said events. Other implementations of the EIP may not emit
                     * these events, as it isn't required by the specification.
                     *
                     * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                     * functions have been added to mitigate the well-known issues around setting
                     * allowances. See {IERC20-approve}.
                     */
                    contract ERC20 is Context, IERC20, IERC20Metadata {
                        mapping(address => uint256) private _balances;
                        mapping(address => mapping(address => uint256)) private _allowances;
                        uint256 private _totalSupply;
                        string private _name;
                        string private _symbol;
                        /**
                         * @dev Sets the values for {name} and {symbol}.
                         *
                         * All two of these values are immutable: they can only be set once during
                         * construction.
                         */
                        constructor(string memory name_, string memory symbol_) {
                            _name = name_;
                            _symbol = symbol_;
                        }
                        /**
                         * @dev Returns the name of the token.
                         */
                        function name() public view virtual override returns (string memory) {
                            return _name;
                        }
                        /**
                         * @dev Returns the symbol of the token, usually a shorter version of the
                         * name.
                         */
                        function symbol() public view virtual override returns (string memory) {
                            return _symbol;
                        }
                        /**
                         * @dev Returns the number of decimals used to get its user representation.
                         * For example, if `decimals` equals `2`, a balance of `505` tokens should
                         * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                         *
                         * Tokens usually opt for a value of 18, imitating the relationship between
                         * Ether and Wei. This is the default value returned by this function, unless
                         * it's overridden.
                         *
                         * NOTE: This information is only used for _display_ purposes: it in
                         * no way affects any of the arithmetic of the contract, including
                         * {IERC20-balanceOf} and {IERC20-transfer}.
                         */
                        function decimals() public view virtual override returns (uint8) {
                            return 18;
                        }
                        /**
                         * @dev See {IERC20-totalSupply}.
                         */
                        function totalSupply() public view virtual override returns (uint256) {
                            return _totalSupply;
                        }
                        /**
                         * @dev See {IERC20-balanceOf}.
                         */
                        function balanceOf(address account) public view virtual override returns (uint256) {
                            return _balances[account];
                        }
                        /**
                         * @dev See {IERC20-transfer}.
                         *
                         * Requirements:
                         *
                         * - `to` cannot be the zero address.
                         * - the caller must have a balance of at least `amount`.
                         */
                        function transfer(address to, uint256 amount) public virtual override returns (bool) {
                            address owner = _msgSender();
                            _transfer(owner, to, amount);
                            return true;
                        }
                        /**
                         * @dev See {IERC20-allowance}.
                         */
                        function allowance(address owner, address spender) public view virtual override returns (uint256) {
                            return _allowances[owner][spender];
                        }
                        /**
                         * @dev See {IERC20-approve}.
                         *
                         * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                         * `transferFrom`. This is semantically equivalent to an infinite approval.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         */
                        function approve(address spender, uint256 amount) public virtual override returns (bool) {
                            address owner = _msgSender();
                            _approve(owner, spender, amount);
                            return true;
                        }
                        /**
                         * @dev See {IERC20-transferFrom}.
                         *
                         * Emits an {Approval} event indicating the updated allowance. This is not
                         * required by the EIP. See the note at the beginning of {ERC20}.
                         *
                         * NOTE: Does not update the allowance if the current allowance
                         * is the maximum `uint256`.
                         *
                         * Requirements:
                         *
                         * - `from` and `to` cannot be the zero address.
                         * - `from` must have a balance of at least `amount`.
                         * - the caller must have allowance for ``from``'s tokens of at least
                         * `amount`.
                         */
                        function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
                            address spender = _msgSender();
                            _spendAllowance(from, spender, amount);
                            _transfer(from, to, amount);
                            return true;
                        }
                        /**
                         * @dev Atomically increases the allowance granted to `spender` by the caller.
                         *
                         * This is an alternative to {approve} that can be used as a mitigation for
                         * problems described in {IERC20-approve}.
                         *
                         * Emits an {Approval} event indicating the updated allowance.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         */
                        function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                            address owner = _msgSender();
                            _approve(owner, spender, allowance(owner, spender) + addedValue);
                            return true;
                        }
                        /**
                         * @dev Atomically decreases the allowance granted to `spender` by the caller.
                         *
                         * This is an alternative to {approve} that can be used as a mitigation for
                         * problems described in {IERC20-approve}.
                         *
                         * Emits an {Approval} event indicating the updated allowance.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         * - `spender` must have allowance for the caller of at least
                         * `subtractedValue`.
                         */
                        function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                            address owner = _msgSender();
                            uint256 currentAllowance = allowance(owner, spender);
                            require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                            unchecked {
                                _approve(owner, spender, currentAllowance - subtractedValue);
                            }
                            return true;
                        }
                        /**
                         * @dev Moves `amount` of tokens from `from` to `to`.
                         *
                         * This internal function is equivalent to {transfer}, and can be used to
                         * e.g. implement automatic token fees, slashing mechanisms, etc.
                         *
                         * Emits a {Transfer} event.
                         *
                         * Requirements:
                         *
                         * - `from` cannot be the zero address.
                         * - `to` cannot be the zero address.
                         * - `from` must have a balance of at least `amount`.
                         */
                        function _transfer(address from, address to, uint256 amount) internal virtual {
                            require(from != address(0), "ERC20: transfer from the zero address");
                            require(to != address(0), "ERC20: transfer to the zero address");
                            _beforeTokenTransfer(from, to, amount);
                            uint256 fromBalance = _balances[from];
                            require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                            unchecked {
                                _balances[from] = fromBalance - amount;
                                // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                                // decrementing then incrementing.
                                _balances[to] += amount;
                            }
                            emit Transfer(from, to, amount);
                            _afterTokenTransfer(from, to, amount);
                        }
                        /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                         * the total supply.
                         *
                         * Emits a {Transfer} event with `from` set to the zero address.
                         *
                         * Requirements:
                         *
                         * - `account` cannot be the zero address.
                         */
                        function _mint(address account, uint256 amount) internal virtual {
                            require(account != address(0), "ERC20: mint to the zero address");
                            _beforeTokenTransfer(address(0), account, amount);
                            _totalSupply += amount;
                            unchecked {
                                // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                                _balances[account] += amount;
                            }
                            emit Transfer(address(0), account, amount);
                            _afterTokenTransfer(address(0), account, amount);
                        }
                        /**
                         * @dev Destroys `amount` tokens from `account`, reducing the
                         * total supply.
                         *
                         * Emits a {Transfer} event with `to` set to the zero address.
                         *
                         * Requirements:
                         *
                         * - `account` cannot be the zero address.
                         * - `account` must have at least `amount` tokens.
                         */
                        function _burn(address account, uint256 amount) internal virtual {
                            require(account != address(0), "ERC20: burn from the zero address");
                            _beforeTokenTransfer(account, address(0), amount);
                            uint256 accountBalance = _balances[account];
                            require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                            unchecked {
                                _balances[account] = accountBalance - amount;
                                // Overflow not possible: amount <= accountBalance <= totalSupply.
                                _totalSupply -= amount;
                            }
                            emit Transfer(account, address(0), amount);
                            _afterTokenTransfer(account, address(0), amount);
                        }
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                         *
                         * This internal function is equivalent to `approve`, and can be used to
                         * e.g. set automatic allowances for certain subsystems, etc.
                         *
                         * Emits an {Approval} event.
                         *
                         * Requirements:
                         *
                         * - `owner` cannot be the zero address.
                         * - `spender` cannot be the zero address.
                         */
                        function _approve(address owner, address spender, uint256 amount) internal virtual {
                            require(owner != address(0), "ERC20: approve from the zero address");
                            require(spender != address(0), "ERC20: approve to the zero address");
                            _allowances[owner][spender] = amount;
                            emit Approval(owner, spender, amount);
                        }
                        /**
                         * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                         *
                         * Does not update the allowance amount in case of infinite allowance.
                         * Revert if not enough allowance is available.
                         *
                         * Might emit an {Approval} event.
                         */
                        function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                            uint256 currentAllowance = allowance(owner, spender);
                            if (currentAllowance != type(uint256).max) {
                                require(currentAllowance >= amount, "ERC20: insufficient allowance");
                                unchecked {
                                    _approve(owner, spender, currentAllowance - amount);
                                }
                            }
                        }
                        /**
                         * @dev Hook that is called before any transfer of tokens. This includes
                         * minting and burning.
                         *
                         * Calling conditions:
                         *
                         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                         * will be transferred to `to`.
                         * - when `from` is zero, `amount` tokens will be minted for `to`.
                         * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                         * - `from` and `to` are never both zero.
                         *
                         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                         */
                        function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                        /**
                         * @dev Hook that is called after any transfer of tokens. This includes
                         * minting and burning.
                         *
                         * Calling conditions:
                         *
                         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                         * has been transferred to `to`.
                         * - when `from` is zero, `amount` tokens have been minted for `to`.
                         * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                         * - `from` and `to` are never both zero.
                         *
                         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                         */
                        function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
                    pragma solidity ^0.8.0;
                    import "../Strings.sol";
                    /**
                     * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
                     *
                     * These functions can be used to verify that a message was signed by the holder
                     * of the private keys of a given address.
                     */
                    library ECDSA {
                        enum RecoverError {
                            NoError,
                            InvalidSignature,
                            InvalidSignatureLength,
                            InvalidSignatureS,
                            InvalidSignatureV // Deprecated in v4.8
                        }
                        function _throwError(RecoverError error) private pure {
                            if (error == RecoverError.NoError) {
                                return; // no error: do nothing
                            } else if (error == RecoverError.InvalidSignature) {
                                revert("ECDSA: invalid signature");
                            } else if (error == RecoverError.InvalidSignatureLength) {
                                revert("ECDSA: invalid signature length");
                            } else if (error == RecoverError.InvalidSignatureS) {
                                revert("ECDSA: invalid signature 's' value");
                            }
                        }
                        /**
                         * @dev Returns the address that signed a hashed message (`hash`) with
                         * `signature` or error string. This address can then be used for verification purposes.
                         *
                         * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                         * this function rejects them by requiring the `s` value to be in the lower
                         * half order, and the `v` value to be either 27 or 28.
                         *
                         * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                         * verification to be secure: it is possible to craft signatures that
                         * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                         * this is by receiving a hash of the original message (which may otherwise
                         * be too long), and then calling {toEthSignedMessageHash} on it.
                         *
                         * Documentation for signature generation:
                         * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
                         * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                            if (signature.length == 65) {
                                bytes32 r;
                                bytes32 s;
                                uint8 v;
                                // ecrecover takes the signature parameters, and the only way to get them
                                // currently is to use assembly.
                                /// @solidity memory-safe-assembly
                                assembly {
                                    r := mload(add(signature, 0x20))
                                    s := mload(add(signature, 0x40))
                                    v := byte(0, mload(add(signature, 0x60)))
                                }
                                return tryRecover(hash, v, r, s);
                            } else {
                                return (address(0), RecoverError.InvalidSignatureLength);
                            }
                        }
                        /**
                         * @dev Returns the address that signed a hashed message (`hash`) with
                         * `signature`. This address can then be used for verification purposes.
                         *
                         * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                         * this function rejects them by requiring the `s` value to be in the lower
                         * half order, and the `v` value to be either 27 or 28.
                         *
                         * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                         * verification to be secure: it is possible to craft signatures that
                         * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                         * this is by receiving a hash of the original message (which may otherwise
                         * be too long), and then calling {toEthSignedMessageHash} on it.
                         */
                        function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, signature);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
                         *
                         * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
                            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                            uint8 v = uint8((uint256(vs) >> 255) + 27);
                            return tryRecover(hash, v, r, s);
                        }
                        /**
                         * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
                         *
                         * _Available since v4.2._
                         */
                        function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
                         * `r` and `s` signature fields separately.
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
                            // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                            // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                            // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                            // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                            //
                            // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                            // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                            // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                            // these malleable signatures as well.
                            if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                                return (address(0), RecoverError.InvalidSignatureS);
                            }
                            // If the signature is valid (and not malleable), return the signer address
                            address signer = ecrecover(hash, v, r, s);
                            if (signer == address(0)) {
                                return (address(0), RecoverError.InvalidSignature);
                            }
                            return (signer, RecoverError.NoError);
                        }
                        /**
                         * @dev Overload of {ECDSA-recover} that receives the `v`,
                         * `r` and `s` signature fields separately.
                         */
                        function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Returns an Ethereum Signed Message, created from a `hash`. This
                         * produces hash corresponding to the one signed with the
                         * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
                         * JSON-RPC method as part of EIP-191.
                         *
                         * See {recover}.
                         */
                        function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
                            // 32 is the length in bytes of hash,
                            // enforced by the type signature above
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, "\\x19Ethereum Signed Message:\
                    32")
                                mstore(0x1c, hash)
                                message := keccak256(0x00, 0x3c)
                            }
                        }
                        /**
                         * @dev Returns an Ethereum Signed Message, created from `s`. This
                         * produces hash corresponding to the one signed with the
                         * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
                         * JSON-RPC method as part of EIP-191.
                         *
                         * See {recover}.
                         */
                        function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                            return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                    ", Strings.toString(s.length), s));
                        }
                        /**
                         * @dev Returns an Ethereum Signed Typed Data, created from a
                         * `domainSeparator` and a `structHash`. This produces hash corresponding
                         * to the one signed with the
                         * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
                         * JSON-RPC method as part of EIP-712.
                         *
                         * See {recover}.
                         */
                        function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let ptr := mload(0x40)
                                mstore(ptr, "\\x19\\x01")
                                mstore(add(ptr, 0x02), domainSeparator)
                                mstore(add(ptr, 0x22), structHash)
                                data := keccak256(ptr, 0x42)
                            }
                        }
                        /**
                         * @dev Returns an Ethereum Signed Data with intended validator, created from a
                         * `validator` and `data` according to the version 0 of EIP-191.
                         *
                         * See {recover}.
                         */
                        function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                            return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
                    pragma solidity ^0.8.8;
                    import "./ECDSA.sol";
                    import "../ShortStrings.sol";
                    import "../../interfaces/IERC5267.sol";
                    /**
                     * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
                     *
                     * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
                     * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
                     * they need in their contracts using a combination of `abi.encode` and `keccak256`.
                     *
                     * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
                     * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
                     * ({_hashTypedDataV4}).
                     *
                     * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
                     * the chain id to protect against replay attacks on an eventual fork of the chain.
                     *
                     * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
                     * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
                     *
                     * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
                     * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
                     * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
                     *
                     * _Available since v3.4._
                     *
                     * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
                     */
                    abstract contract EIP712 is IERC5267 {
                        using ShortStrings for *;
                        bytes32 private constant _TYPE_HASH =
                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
                        // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
                        // invalidate the cached domain separator if the chain id changes.
                        bytes32 private immutable _cachedDomainSeparator;
                        uint256 private immutable _cachedChainId;
                        address private immutable _cachedThis;
                        bytes32 private immutable _hashedName;
                        bytes32 private immutable _hashedVersion;
                        ShortString private immutable _name;
                        ShortString private immutable _version;
                        string private _nameFallback;
                        string private _versionFallback;
                        /**
                         * @dev Initializes the domain separator and parameter caches.
                         *
                         * The meaning of `name` and `version` is specified in
                         * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                         *
                         * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                         * - `version`: the current major version of the signing domain.
                         *
                         * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                         * contract upgrade].
                         */
                        constructor(string memory name, string memory version) {
                            _name = name.toShortStringWithFallback(_nameFallback);
                            _version = version.toShortStringWithFallback(_versionFallback);
                            _hashedName = keccak256(bytes(name));
                            _hashedVersion = keccak256(bytes(version));
                            _cachedChainId = block.chainid;
                            _cachedDomainSeparator = _buildDomainSeparator();
                            _cachedThis = address(this);
                        }
                        /**
                         * @dev Returns the domain separator for the current chain.
                         */
                        function _domainSeparatorV4() internal view returns (bytes32) {
                            if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                                return _cachedDomainSeparator;
                            } else {
                                return _buildDomainSeparator();
                            }
                        }
                        function _buildDomainSeparator() private view returns (bytes32) {
                            return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
                        }
                        /**
                         * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                         * function returns the hash of the fully encoded EIP712 message for this domain.
                         *
                         * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                         *
                         * ```solidity
                         * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
                         *     keccak256("Mail(address to,string contents)"),
                         *     mailTo,
                         *     keccak256(bytes(mailContents))
                         * )));
                         * address signer = ECDSA.recover(digest, signature);
                         * ```
                         */
                        function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                            return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
                        }
                        /**
                         * @dev See {EIP-5267}.
                         *
                         * _Available since v4.9._
                         */
                        function eip712Domain()
                            public
                            view
                            virtual
                            override
                            returns (
                                bytes1 fields,
                                string memory name,
                                string memory version,
                                uint256 chainId,
                                address verifyingContract,
                                bytes32 salt,
                                uint256[] memory extensions
                            )
                        {
                            return (
                                hex"0f", // 01111
                                _name.toStringWithFallback(_nameFallback),
                                _version.toStringWithFallback(_versionFallback),
                                block.chainid,
                                address(this),
                                bytes32(0),
                                new uint256[](0)
                            );
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @title Counters
                     * @author Matt Condon (@shrugs)
                     * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
                     * of elements in a mapping, issuing ERC721 ids, or counting request ids.
                     *
                     * Include with `using Counters for Counters.Counter;`
                     */
                    library Counters {
                        struct Counter {
                            // This variable should never be directly accessed by users of the library: interactions must be restricted to
                            // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                            // this feature: see https://github.com/ethereum/solidity/issues/4637
                            uint256 _value; // default: 0
                        }
                        function current(Counter storage counter) internal view returns (uint256) {
                            return counter._value;
                        }
                        function increment(Counter storage counter) internal {
                            unchecked {
                                counter._value += 1;
                            }
                        }
                        function decrement(Counter storage counter) internal {
                            uint256 value = counter._value;
                            require(value > 0, "Counter: decrement overflow");
                            unchecked {
                                counter._value = value - 1;
                            }
                        }
                        function reset(Counter storage counter) internal {
                            counter._value = 0;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
                    pragma solidity ^0.8.0;
                    import "./IAccessControl.sol";
                    /**
                     * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
                     */
                    interface IAccessControlEnumerable is IAccessControl {
                        /**
                         * @dev Returns one of the accounts that have `role`. `index` must be a
                         * value between 0 and {getRoleMemberCount}, non-inclusive.
                         *
                         * Role bearers are not sorted in any particular way, and their ordering may
                         * change at any point.
                         *
                         * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                         * you perform all queries on the same block. See the following
                         * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                         * for more information.
                         */
                        function getRoleMember(bytes32 role, uint256 index) external view returns (address);
                        /**
                         * @dev Returns the number of accounts that have `role`. Can be used
                         * together with {getRoleMember} to enumerate all bearers of a role.
                         */
                        function getRoleMemberCount(bytes32 role) external view returns (uint256);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
                    pragma solidity ^0.8.0;
                    import "./IAccessControl.sol";
                    import "../utils/Context.sol";
                    import "../utils/Strings.sol";
                    import "../utils/introspection/ERC165.sol";
                    /**
                     * @dev Contract module that allows children to implement role-based access
                     * control mechanisms. This is a lightweight version that doesn't allow enumerating role
                     * members except through off-chain means by accessing the contract event logs. Some
                     * applications may benefit from on-chain enumerability, for those cases see
                     * {AccessControlEnumerable}.
                     *
                     * Roles are referred to by their `bytes32` identifier. These should be exposed
                     * in the external API and be unique. The best way to achieve this is by
                     * using `public constant` hash digests:
                     *
                     * ```solidity
                     * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
                     * ```
                     *
                     * Roles can be used to represent a set of permissions. To restrict access to a
                     * function call, use {hasRole}:
                     *
                     * ```solidity
                     * function foo() public {
                     *     require(hasRole(MY_ROLE, msg.sender));
                     *     ...
                     * }
                     * ```
                     *
                     * Roles can be granted and revoked dynamically via the {grantRole} and
                     * {revokeRole} functions. Each role has an associated admin role, and only
                     * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
                     *
                     * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
                     * that only accounts with this role will be able to grant or revoke other
                     * roles. More complex role relationships can be created by using
                     * {_setRoleAdmin}.
                     *
                     * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
                     * grant and revoke this role. Extra precautions should be taken to secure
                     * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
                     * to enforce additional security measures for this role.
                     */
                    abstract contract AccessControl is Context, IAccessControl, ERC165 {
                        struct RoleData {
                            mapping(address => bool) members;
                            bytes32 adminRole;
                        }
                        mapping(bytes32 => RoleData) private _roles;
                        bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
                        /**
                         * @dev Modifier that checks that an account has a specific role. Reverts
                         * with a standardized message including the required role.
                         *
                         * The format of the revert reason is given by the following regular expression:
                         *
                         *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                         *
                         * _Available since v4.1._
                         */
                        modifier onlyRole(bytes32 role) {
                            _checkRole(role);
                            _;
                        }
                        /**
                         * @dev See {IERC165-supportsInterface}.
                         */
                        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                            return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
                        }
                        /**
                         * @dev Returns `true` if `account` has been granted `role`.
                         */
                        function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                            return _roles[role].members[account];
                        }
                        /**
                         * @dev Revert with a standard message if `_msgSender()` is missing `role`.
                         * Overriding this function changes the behavior of the {onlyRole} modifier.
                         *
                         * Format of the revert message is described in {_checkRole}.
                         *
                         * _Available since v4.6._
                         */
                        function _checkRole(bytes32 role) internal view virtual {
                            _checkRole(role, _msgSender());
                        }
                        /**
                         * @dev Revert with a standard message if `account` is missing `role`.
                         *
                         * The format of the revert reason is given by the following regular expression:
                         *
                         *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
                         */
                        function _checkRole(bytes32 role, address account) internal view virtual {
                            if (!hasRole(role, account)) {
                                revert(
                                    string(
                                        abi.encodePacked(
                                            "AccessControl: account ",
                                            Strings.toHexString(account),
                                            " is missing role ",
                                            Strings.toHexString(uint256(role), 32)
                                        )
                                    )
                                );
                            }
                        }
                        /**
                         * @dev Returns the admin role that controls `role`. See {grantRole} and
                         * {revokeRole}.
                         *
                         * To change a role's admin, use {_setRoleAdmin}.
                         */
                        function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                            return _roles[role].adminRole;
                        }
                        /**
                         * @dev Grants `role` to `account`.
                         *
                         * If `account` had not been already granted `role`, emits a {RoleGranted}
                         * event.
                         *
                         * Requirements:
                         *
                         * - the caller must have ``role``'s admin role.
                         *
                         * May emit a {RoleGranted} event.
                         */
                        function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                            _grantRole(role, account);
                        }
                        /**
                         * @dev Revokes `role` from `account`.
                         *
                         * If `account` had been granted `role`, emits a {RoleRevoked} event.
                         *
                         * Requirements:
                         *
                         * - the caller must have ``role``'s admin role.
                         *
                         * May emit a {RoleRevoked} event.
                         */
                        function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                            _revokeRole(role, account);
                        }
                        /**
                         * @dev Revokes `role` from the calling account.
                         *
                         * Roles are often managed via {grantRole} and {revokeRole}: this function's
                         * purpose is to provide a mechanism for accounts to lose their privileges
                         * if they are compromised (such as when a trusted device is misplaced).
                         *
                         * If the calling account had been revoked `role`, emits a {RoleRevoked}
                         * event.
                         *
                         * Requirements:
                         *
                         * - the caller must be `account`.
                         *
                         * May emit a {RoleRevoked} event.
                         */
                        function renounceRole(bytes32 role, address account) public virtual override {
                            require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                            _revokeRole(role, account);
                        }
                        /**
                         * @dev Grants `role` to `account`.
                         *
                         * If `account` had not been already granted `role`, emits a {RoleGranted}
                         * event. Note that unlike {grantRole}, this function doesn't perform any
                         * checks on the calling account.
                         *
                         * May emit a {RoleGranted} event.
                         *
                         * [WARNING]
                         * ====
                         * This function should only be called from the constructor when setting
                         * up the initial roles for the system.
                         *
                         * Using this function in any other way is effectively circumventing the admin
                         * system imposed by {AccessControl}.
                         * ====
                         *
                         * NOTE: This function is deprecated in favor of {_grantRole}.
                         */
                        function _setupRole(bytes32 role, address account) internal virtual {
                            _grantRole(role, account);
                        }
                        /**
                         * @dev Sets `adminRole` as ``role``'s admin role.
                         *
                         * Emits a {RoleAdminChanged} event.
                         */
                        function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                            bytes32 previousAdminRole = getRoleAdmin(role);
                            _roles[role].adminRole = adminRole;
                            emit RoleAdminChanged(role, previousAdminRole, adminRole);
                        }
                        /**
                         * @dev Grants `role` to `account`.
                         *
                         * Internal function without access restriction.
                         *
                         * May emit a {RoleGranted} event.
                         */
                        function _grantRole(bytes32 role, address account) internal virtual {
                            if (!hasRole(role, account)) {
                                _roles[role].members[account] = true;
                                emit RoleGranted(role, account, _msgSender());
                            }
                        }
                        /**
                         * @dev Revokes `role` from `account`.
                         *
                         * Internal function without access restriction.
                         *
                         * May emit a {RoleRevoked} event.
                         */
                        function _revokeRole(bytes32 role, address account) internal virtual {
                            if (hasRole(role, account)) {
                                _roles[role].members[account] = false;
                                emit RoleRevoked(role, account, _msgSender());
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
                    // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Library for managing
                     * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
                     * types.
                     *
                     * Sets have the following properties:
                     *
                     * - Elements are added, removed, and checked for existence in constant time
                     * (O(1)).
                     * - Elements are enumerated in O(n). No guarantees are made on the ordering.
                     *
                     * ```solidity
                     * contract Example {
                     *     // Add the library methods
                     *     using EnumerableSet for EnumerableSet.AddressSet;
                     *
                     *     // Declare a set state variable
                     *     EnumerableSet.AddressSet private mySet;
                     * }
                     * ```
                     *
                     * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
                     * and `uint256` (`UintSet`) are supported.
                     *
                     * [WARNING]
                     * ====
                     * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
                     * unusable.
                     * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
                     *
                     * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
                     * array of EnumerableSet.
                     * ====
                     */
                    library EnumerableSet {
                        // To implement this library for multiple types with as little code
                        // repetition as possible, we write it in terms of a generic Set type with
                        // bytes32 values.
                        // The Set implementation uses private functions, and user-facing
                        // implementations (such as AddressSet) are just wrappers around the
                        // underlying Set.
                        // This means that we can only create new EnumerableSets for types that fit
                        // in bytes32.
                        struct Set {
                            // Storage of set values
                            bytes32[] _values;
                            // Position of the value in the `values` array, plus 1 because index 0
                            // means a value is not in the set.
                            mapping(bytes32 => uint256) _indexes;
                        }
                        /**
                         * @dev Add a value to a set. O(1).
                         *
                         * Returns true if the value was added to the set, that is if it was not
                         * already present.
                         */
                        function _add(Set storage set, bytes32 value) private returns (bool) {
                            if (!_contains(set, value)) {
                                set._values.push(value);
                                // The value is stored at length-1, but we add 1 to all indexes
                                // and use 0 as a sentinel value
                                set._indexes[value] = set._values.length;
                                return true;
                            } else {
                                return false;
                            }
                        }
                        /**
                         * @dev Removes a value from a set. O(1).
                         *
                         * Returns true if the value was removed from the set, that is if it was
                         * present.
                         */
                        function _remove(Set storage set, bytes32 value) private returns (bool) {
                            // We read and store the value's index to prevent multiple reads from the same storage slot
                            uint256 valueIndex = set._indexes[value];
                            if (valueIndex != 0) {
                                // Equivalent to contains(set, value)
                                // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                                // the array, and then remove the last element (sometimes called as 'swap and pop').
                                // This modifies the order of the array, as noted in {at}.
                                uint256 toDeleteIndex = valueIndex - 1;
                                uint256 lastIndex = set._values.length - 1;
                                if (lastIndex != toDeleteIndex) {
                                    bytes32 lastValue = set._values[lastIndex];
                                    // Move the last value to the index where the value to delete is
                                    set._values[toDeleteIndex] = lastValue;
                                    // Update the index for the moved value
                                    set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                                }
                                // Delete the slot where the moved value was stored
                                set._values.pop();
                                // Delete the index for the deleted slot
                                delete set._indexes[value];
                                return true;
                            } else {
                                return false;
                            }
                        }
                        /**
                         * @dev Returns true if the value is in the set. O(1).
                         */
                        function _contains(Set storage set, bytes32 value) private view returns (bool) {
                            return set._indexes[value] != 0;
                        }
                        /**
                         * @dev Returns the number of values on the set. O(1).
                         */
                        function _length(Set storage set) private view returns (uint256) {
                            return set._values.length;
                        }
                        /**
                         * @dev Returns the value stored at position `index` in the set. O(1).
                         *
                         * Note that there are no guarantees on the ordering of values inside the
                         * array, and it may change when more values are added or removed.
                         *
                         * Requirements:
                         *
                         * - `index` must be strictly less than {length}.
                         */
                        function _at(Set storage set, uint256 index) private view returns (bytes32) {
                            return set._values[index];
                        }
                        /**
                         * @dev Return the entire set in an array
                         *
                         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                         */
                        function _values(Set storage set) private view returns (bytes32[] memory) {
                            return set._values;
                        }
                        // Bytes32Set
                        struct Bytes32Set {
                            Set _inner;
                        }
                        /**
                         * @dev Add a value to a set. O(1).
                         *
                         * Returns true if the value was added to the set, that is if it was not
                         * already present.
                         */
                        function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                            return _add(set._inner, value);
                        }
                        /**
                         * @dev Removes a value from a set. O(1).
                         *
                         * Returns true if the value was removed from the set, that is if it was
                         * present.
                         */
                        function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                            return _remove(set._inner, value);
                        }
                        /**
                         * @dev Returns true if the value is in the set. O(1).
                         */
                        function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                            return _contains(set._inner, value);
                        }
                        /**
                         * @dev Returns the number of values in the set. O(1).
                         */
                        function length(Bytes32Set storage set) internal view returns (uint256) {
                            return _length(set._inner);
                        }
                        /**
                         * @dev Returns the value stored at position `index` in the set. O(1).
                         *
                         * Note that there are no guarantees on the ordering of values inside the
                         * array, and it may change when more values are added or removed.
                         *
                         * Requirements:
                         *
                         * - `index` must be strictly less than {length}.
                         */
                        function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                            return _at(set._inner, index);
                        }
                        /**
                         * @dev Return the entire set in an array
                         *
                         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                         */
                        function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                            bytes32[] memory store = _values(set._inner);
                            bytes32[] memory result;
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := store
                            }
                            return result;
                        }
                        // AddressSet
                        struct AddressSet {
                            Set _inner;
                        }
                        /**
                         * @dev Add a value to a set. O(1).
                         *
                         * Returns true if the value was added to the set, that is if it was not
                         * already present.
                         */
                        function add(AddressSet storage set, address value) internal returns (bool) {
                            return _add(set._inner, bytes32(uint256(uint160(value))));
                        }
                        /**
                         * @dev Removes a value from a set. O(1).
                         *
                         * Returns true if the value was removed from the set, that is if it was
                         * present.
                         */
                        function remove(AddressSet storage set, address value) internal returns (bool) {
                            return _remove(set._inner, bytes32(uint256(uint160(value))));
                        }
                        /**
                         * @dev Returns true if the value is in the set. O(1).
                         */
                        function contains(AddressSet storage set, address value) internal view returns (bool) {
                            return _contains(set._inner, bytes32(uint256(uint160(value))));
                        }
                        /**
                         * @dev Returns the number of values in the set. O(1).
                         */
                        function length(AddressSet storage set) internal view returns (uint256) {
                            return _length(set._inner);
                        }
                        /**
                         * @dev Returns the value stored at position `index` in the set. O(1).
                         *
                         * Note that there are no guarantees on the ordering of values inside the
                         * array, and it may change when more values are added or removed.
                         *
                         * Requirements:
                         *
                         * - `index` must be strictly less than {length}.
                         */
                        function at(AddressSet storage set, uint256 index) internal view returns (address) {
                            return address(uint160(uint256(_at(set._inner, index))));
                        }
                        /**
                         * @dev Return the entire set in an array
                         *
                         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                         */
                        function values(AddressSet storage set) internal view returns (address[] memory) {
                            bytes32[] memory store = _values(set._inner);
                            address[] memory result;
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := store
                            }
                            return result;
                        }
                        // UintSet
                        struct UintSet {
                            Set _inner;
                        }
                        /**
                         * @dev Add a value to a set. O(1).
                         *
                         * Returns true if the value was added to the set, that is if it was not
                         * already present.
                         */
                        function add(UintSet storage set, uint256 value) internal returns (bool) {
                            return _add(set._inner, bytes32(value));
                        }
                        /**
                         * @dev Removes a value from a set. O(1).
                         *
                         * Returns true if the value was removed from the set, that is if it was
                         * present.
                         */
                        function remove(UintSet storage set, uint256 value) internal returns (bool) {
                            return _remove(set._inner, bytes32(value));
                        }
                        /**
                         * @dev Returns true if the value is in the set. O(1).
                         */
                        function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                            return _contains(set._inner, bytes32(value));
                        }
                        /**
                         * @dev Returns the number of values in the set. O(1).
                         */
                        function length(UintSet storage set) internal view returns (uint256) {
                            return _length(set._inner);
                        }
                        /**
                         * @dev Returns the value stored at position `index` in the set. O(1).
                         *
                         * Note that there are no guarantees on the ordering of values inside the
                         * array, and it may change when more values are added or removed.
                         *
                         * Requirements:
                         *
                         * - `index` must be strictly less than {length}.
                         */
                        function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                            return uint256(_at(set._inner, index));
                        }
                        /**
                         * @dev Return the entire set in an array
                         *
                         * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                         * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                         * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                         * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                         */
                        function values(UintSet storage set) internal view returns (uint256[] memory) {
                            bytes32[] memory store = _values(set._inner);
                            uint256[] memory result;
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := store
                            }
                            return result;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Emitted when `value` tokens are moved from one account (`from`) to
                         * another (`to`).
                         *
                         * Note that `value` may be zero.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /**
                         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                         * a call to {approve}. `value` is the new allowance.
                         */
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `to`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address to, uint256 amount) external returns (bool);
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                        /**
                         * @dev Moves `amount` tokens from `from` to `to` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(address from, address to, uint256 amount) external returns (bool);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                    pragma solidity ^0.8.0;
                    import "../IERC20.sol";
                    /**
                     * @dev Interface for the optional metadata functions from the ERC20 standard.
                     *
                     * _Available since v4.1._
                     */
                    interface IERC20Metadata is IERC20 {
                        /**
                         * @dev Returns the name of the token.
                         */
                        function name() external view returns (string memory);
                        /**
                         * @dev Returns the symbol of the token.
                         */
                        function symbol() external view returns (string memory);
                        /**
                         * @dev Returns the decimals places of the token.
                         */
                        function decimals() external view returns (uint8);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
                    pragma solidity ^0.8.0;
                    import "./math/Math.sol";
                    import "./math/SignedMath.sol";
                    /**
                     * @dev String operations.
                     */
                    library Strings {
                        bytes16 private constant _SYMBOLS = "0123456789abcdef";
                        uint8 private constant _ADDRESS_LENGTH = 20;
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                         */
                        function toString(uint256 value) internal pure returns (string memory) {
                            unchecked {
                                uint256 length = Math.log10(value) + 1;
                                string memory buffer = new string(length);
                                uint256 ptr;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    ptr := add(buffer, add(32, length))
                                }
                                while (true) {
                                    ptr--;
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                                    }
                                    value /= 10;
                                    if (value == 0) break;
                                }
                                return buffer;
                            }
                        }
                        /**
                         * @dev Converts a `int256` to its ASCII `string` decimal representation.
                         */
                        function toString(int256 value) internal pure returns (string memory) {
                            return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
                        }
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                         */
                        function toHexString(uint256 value) internal pure returns (string memory) {
                            unchecked {
                                return toHexString(value, Math.log256(value) + 1);
                            }
                        }
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                         */
                        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                            bytes memory buffer = new bytes(2 * length + 2);
                            buffer[0] = "0";
                            buffer[1] = "x";
                            for (uint256 i = 2 * length + 1; i > 1; --i) {
                                buffer[i] = _SYMBOLS[value & 0xf];
                                value >>= 4;
                            }
                            require(value == 0, "Strings: hex length insufficient");
                            return string(buffer);
                        }
                        /**
                         * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                         */
                        function toHexString(address addr) internal pure returns (string memory) {
                            return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                        }
                        /**
                         * @dev Returns true if the two strings are equal.
                         */
                        function equal(string memory a, string memory b) internal pure returns (bool) {
                            return keccak256(bytes(a)) == keccak256(bytes(b));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
                    pragma solidity ^0.8.8;
                    import "./StorageSlot.sol";
                    // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
                    // | length  | 0x                                                              BB |
                    type ShortString is bytes32;
                    /**
                     * @dev This library provides functions to convert short memory strings
                     * into a `ShortString` type that can be used as an immutable variable.
                     *
                     * Strings of arbitrary length can be optimized using this library if
                     * they are short enough (up to 31 bytes) by packing them with their
                     * length (1 byte) in a single EVM word (32 bytes). Additionally, a
                     * fallback mechanism can be used for every other case.
                     *
                     * Usage example:
                     *
                     * ```solidity
                     * contract Named {
                     *     using ShortStrings for *;
                     *
                     *     ShortString private immutable _name;
                     *     string private _nameFallback;
                     *
                     *     constructor(string memory contractName) {
                     *         _name = contractName.toShortStringWithFallback(_nameFallback);
                     *     }
                     *
                     *     function name() external view returns (string memory) {
                     *         return _name.toStringWithFallback(_nameFallback);
                     *     }
                     * }
                     * ```
                     */
                    library ShortStrings {
                        // Used as an identifier for strings longer than 31 bytes.
                        bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
                        error StringTooLong(string str);
                        error InvalidShortString();
                        /**
                         * @dev Encode a string of at most 31 chars into a `ShortString`.
                         *
                         * This will trigger a `StringTooLong` error is the input string is too long.
                         */
                        function toShortString(string memory str) internal pure returns (ShortString) {
                            bytes memory bstr = bytes(str);
                            if (bstr.length > 31) {
                                revert StringTooLong(str);
                            }
                            return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
                        }
                        /**
                         * @dev Decode a `ShortString` back to a "normal" string.
                         */
                        function toString(ShortString sstr) internal pure returns (string memory) {
                            uint256 len = byteLength(sstr);
                            // using `new string(len)` would work locally but is not memory safe.
                            string memory str = new string(32);
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(str, len)
                                mstore(add(str, 0x20), sstr)
                            }
                            return str;
                        }
                        /**
                         * @dev Return the length of a `ShortString`.
                         */
                        function byteLength(ShortString sstr) internal pure returns (uint256) {
                            uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                            if (result > 31) {
                                revert InvalidShortString();
                            }
                            return result;
                        }
                        /**
                         * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
                         */
                        function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                            if (bytes(value).length < 32) {
                                return toShortString(value);
                            } else {
                                StorageSlot.getStringSlot(store).value = value;
                                return ShortString.wrap(_FALLBACK_SENTINEL);
                            }
                        }
                        /**
                         * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
                         */
                        function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                            if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                                return toString(value);
                            } else {
                                return store;
                            }
                        }
                        /**
                         * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
                         *
                         * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
                         * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
                         */
                        function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                            if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                                return byteLength(value);
                            } else {
                                return bytes(store).length;
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
                    pragma solidity ^0.8.0;
                    interface IERC5267 {
                        /**
                         * @dev MAY be emitted to signal that the domain could have changed.
                         */
                        event EIP712DomainChanged();
                        /**
                         * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
                         * signature.
                         */
                        function eip712Domain()
                            external
                            view
                            returns (
                                bytes1 fields,
                                string memory name,
                                string memory version,
                                uint256 chainId,
                                address verifyingContract,
                                bytes32 salt,
                                uint256[] memory extensions
                            );
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev External interface of AccessControl declared to support ERC165 detection.
                     */
                    interface IAccessControl {
                        /**
                         * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                         *
                         * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                         * {RoleAdminChanged} not being emitted signaling this.
                         *
                         * _Available since v3.1._
                         */
                        event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                        /**
                         * @dev Emitted when `account` is granted `role`.
                         *
                         * `sender` is the account that originated the contract call, an admin role
                         * bearer except when using {AccessControl-_setupRole}.
                         */
                        event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                        /**
                         * @dev Emitted when `account` is revoked `role`.
                         *
                         * `sender` is the account that originated the contract call:
                         *   - if using `revokeRole`, it is the admin role bearer
                         *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                         */
                        event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                        /**
                         * @dev Returns `true` if `account` has been granted `role`.
                         */
                        function hasRole(bytes32 role, address account) external view returns (bool);
                        /**
                         * @dev Returns the admin role that controls `role`. See {grantRole} and
                         * {revokeRole}.
                         *
                         * To change a role's admin, use {AccessControl-_setRoleAdmin}.
                         */
                        function getRoleAdmin(bytes32 role) external view returns (bytes32);
                        /**
                         * @dev Grants `role` to `account`.
                         *
                         * If `account` had not been already granted `role`, emits a {RoleGranted}
                         * event.
                         *
                         * Requirements:
                         *
                         * - the caller must have ``role``'s admin role.
                         */
                        function grantRole(bytes32 role, address account) external;
                        /**
                         * @dev Revokes `role` from `account`.
                         *
                         * If `account` had been granted `role`, emits a {RoleRevoked} event.
                         *
                         * Requirements:
                         *
                         * - the caller must have ``role``'s admin role.
                         */
                        function revokeRole(bytes32 role, address account) external;
                        /**
                         * @dev Revokes `role` from the calling account.
                         *
                         * Roles are often managed via {grantRole} and {revokeRole}: this function's
                         * purpose is to provide a mechanism for accounts to lose their privileges
                         * if they are compromised (such as when a trusted device is misplaced).
                         *
                         * If the calling account had been granted `role`, emits a {RoleRevoked}
                         * event.
                         *
                         * Requirements:
                         *
                         * - the caller must be `account`.
                         */
                        function renounceRole(bytes32 role, address account) external;
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
                    pragma solidity ^0.8.0;
                    import "./IERC165.sol";
                    /**
                     * @dev Implementation of the {IERC165} interface.
                     *
                     * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
                     * for the additional interface id that will be supported. For example:
                     *
                     * ```solidity
                     * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                     *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
                     * }
                     * ```
                     *
                     * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
                     */
                    abstract contract ERC165 is IERC165 {
                        /**
                         * @dev See {IERC165-supportsInterface}.
                         */
                        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                            return interfaceId == type(IERC165).interfaceId;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Standard math utilities missing in the Solidity language.
                     */
                    library Math {
                        enum Rounding {
                            Down, // Toward negative infinity
                            Up, // Toward infinity
                            Zero // Toward zero
                        }
                        /**
                         * @dev Returns the largest of two numbers.
                         */
                        function max(uint256 a, uint256 b) internal pure returns (uint256) {
                            return a > b ? a : b;
                        }
                        /**
                         * @dev Returns the smallest of two numbers.
                         */
                        function min(uint256 a, uint256 b) internal pure returns (uint256) {
                            return a < b ? a : b;
                        }
                        /**
                         * @dev Returns the average of two numbers. The result is rounded towards
                         * zero.
                         */
                        function average(uint256 a, uint256 b) internal pure returns (uint256) {
                            // (a + b) / 2 can overflow.
                            return (a & b) + (a ^ b) / 2;
                        }
                        /**
                         * @dev Returns the ceiling of the division of two numbers.
                         *
                         * This differs from standard division with `/` in that it rounds up instead
                         * of rounding down.
                         */
                        function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                            // (a + b - 1) / b can overflow on addition, so we distribute.
                            return a == 0 ? 0 : (a - 1) / b + 1;
                        }
                        /**
                         * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                         * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                         * with further edits by Uniswap Labs also under MIT license.
                         */
                        function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                            unchecked {
                                // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                // variables such that product = prod1 * 2^256 + prod0.
                                uint256 prod0; // Least significant 256 bits of the product
                                uint256 prod1; // Most significant 256 bits of the product
                                assembly {
                                    let mm := mulmod(x, y, not(0))
                                    prod0 := mul(x, y)
                                    prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                }
                                // Handle non-overflow cases, 256 by 256 division.
                                if (prod1 == 0) {
                                    // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                                    // The surrounding unchecked block does not change this fact.
                                    // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                                    return prod0 / denominator;
                                }
                                // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                require(denominator > prod1, "Math: mulDiv overflow");
                                ///////////////////////////////////////////////
                                // 512 by 256 division.
                                ///////////////////////////////////////////////
                                // Make division exact by subtracting the remainder from [prod1 prod0].
                                uint256 remainder;
                                assembly {
                                    // Compute remainder using mulmod.
                                    remainder := mulmod(x, y, denominator)
                                    // Subtract 256 bit number from 512 bit number.
                                    prod1 := sub(prod1, gt(remainder, prod0))
                                    prod0 := sub(prod0, remainder)
                                }
                                // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                // See https://cs.stackexchange.com/q/138556/92363.
                                // Does not overflow because the denominator cannot be zero at this stage in the function.
                                uint256 twos = denominator & (~denominator + 1);
                                assembly {
                                    // Divide denominator by twos.
                                    denominator := div(denominator, twos)
                                    // Divide [prod1 prod0] by twos.
                                    prod0 := div(prod0, twos)
                                    // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                    twos := add(div(sub(0, twos), twos), 1)
                                }
                                // Shift in bits from prod1 into prod0.
                                prod0 |= prod1 * twos;
                                // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                // four bits. That is, denominator * inv = 1 mod 2^4.
                                uint256 inverse = (3 * denominator) ^ 2;
                                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                // in modular arithmetic, doubling the correct bits in each step.
                                inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                inverse *= 2 - denominator * inverse; // inverse mod 2^256
                                // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                // is no longer required.
                                result = prod0 * inverse;
                                return result;
                            }
                        }
                        /**
                         * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                         */
                        function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                            uint256 result = mulDiv(x, y, denominator);
                            if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                result += 1;
                            }
                            return result;
                        }
                        /**
                         * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                         *
                         * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                         */
                        function sqrt(uint256 a) internal pure returns (uint256) {
                            if (a == 0) {
                                return 0;
                            }
                            // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                            //
                            // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                            // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                            //
                            // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                            // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                            // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                            //
                            // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                            uint256 result = 1 << (log2(a) >> 1);
                            // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                            // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                            // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                            // into the expected uint128 result.
                            unchecked {
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                result = (result + a / result) >> 1;
                                return min(result, a / result);
                            }
                        }
                        /**
                         * @notice Calculates sqrt(a), following the selected rounding direction.
                         */
                        function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                            unchecked {
                                uint256 result = sqrt(a);
                                return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                            }
                        }
                        /**
                         * @dev Return the log in base 2, rounded down, of a positive value.
                         * Returns 0 if given 0.
                         */
                        function log2(uint256 value) internal pure returns (uint256) {
                            uint256 result = 0;
                            unchecked {
                                if (value >> 128 > 0) {
                                    value >>= 128;
                                    result += 128;
                                }
                                if (value >> 64 > 0) {
                                    value >>= 64;
                                    result += 64;
                                }
                                if (value >> 32 > 0) {
                                    value >>= 32;
                                    result += 32;
                                }
                                if (value >> 16 > 0) {
                                    value >>= 16;
                                    result += 16;
                                }
                                if (value >> 8 > 0) {
                                    value >>= 8;
                                    result += 8;
                                }
                                if (value >> 4 > 0) {
                                    value >>= 4;
                                    result += 4;
                                }
                                if (value >> 2 > 0) {
                                    value >>= 2;
                                    result += 2;
                                }
                                if (value >> 1 > 0) {
                                    result += 1;
                                }
                            }
                            return result;
                        }
                        /**
                         * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                         * Returns 0 if given 0.
                         */
                        function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                            unchecked {
                                uint256 result = log2(value);
                                return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                            }
                        }
                        /**
                         * @dev Return the log in base 10, rounded down, of a positive value.
                         * Returns 0 if given 0.
                         */
                        function log10(uint256 value) internal pure returns (uint256) {
                            uint256 result = 0;
                            unchecked {
                                if (value >= 10 ** 64) {
                                    value /= 10 ** 64;
                                    result += 64;
                                }
                                if (value >= 10 ** 32) {
                                    value /= 10 ** 32;
                                    result += 32;
                                }
                                if (value >= 10 ** 16) {
                                    value /= 10 ** 16;
                                    result += 16;
                                }
                                if (value >= 10 ** 8) {
                                    value /= 10 ** 8;
                                    result += 8;
                                }
                                if (value >= 10 ** 4) {
                                    value /= 10 ** 4;
                                    result += 4;
                                }
                                if (value >= 10 ** 2) {
                                    value /= 10 ** 2;
                                    result += 2;
                                }
                                if (value >= 10 ** 1) {
                                    result += 1;
                                }
                            }
                            return result;
                        }
                        /**
                         * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                         * Returns 0 if given 0.
                         */
                        function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                            unchecked {
                                uint256 result = log10(value);
                                return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
                            }
                        }
                        /**
                         * @dev Return the log in base 256, rounded down, of a positive value.
                         * Returns 0 if given 0.
                         *
                         * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                         */
                        function log256(uint256 value) internal pure returns (uint256) {
                            uint256 result = 0;
                            unchecked {
                                if (value >> 128 > 0) {
                                    value >>= 128;
                                    result += 16;
                                }
                                if (value >> 64 > 0) {
                                    value >>= 64;
                                    result += 8;
                                }
                                if (value >> 32 > 0) {
                                    value >>= 32;
                                    result += 4;
                                }
                                if (value >> 16 > 0) {
                                    value >>= 16;
                                    result += 2;
                                }
                                if (value >> 8 > 0) {
                                    result += 1;
                                }
                            }
                            return result;
                        }
                        /**
                         * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
                         * Returns 0 if given 0.
                         */
                        function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                            unchecked {
                                uint256 result = log256(value);
                                return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Standard signed math utilities missing in the Solidity language.
                     */
                    library SignedMath {
                        /**
                         * @dev Returns the largest of two signed numbers.
                         */
                        function max(int256 a, int256 b) internal pure returns (int256) {
                            return a > b ? a : b;
                        }
                        /**
                         * @dev Returns the smallest of two signed numbers.
                         */
                        function min(int256 a, int256 b) internal pure returns (int256) {
                            return a < b ? a : b;
                        }
                        /**
                         * @dev Returns the average of two signed numbers without overflow.
                         * The result is rounded towards zero.
                         */
                        function average(int256 a, int256 b) internal pure returns (int256) {
                            // Formula from the book "Hacker's Delight"
                            int256 x = (a & b) + ((a ^ b) >> 1);
                            return x + (int256(uint256(x) >> 255) & (a ^ b));
                        }
                        /**
                         * @dev Returns the absolute unsigned value of a signed value.
                         */
                        function abs(int256 n) internal pure returns (uint256) {
                            unchecked {
                                // must be unchecked in order to support `n = type(int256).min`
                                return uint256(n >= 0 ? n : -n);
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
                    // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Library for reading and writing primitive types to specific storage slots.
                     *
                     * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                     * This library helps with reading and writing to such slots without the need for inline assembly.
                     *
                     * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                     *
                     * Example usage to set ERC1967 implementation slot:
                     * ```solidity
                     * contract ERC1967 {
                     *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                     *
                     *     function _getImplementation() internal view returns (address) {
                     *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                     *     }
                     *
                     *     function _setImplementation(address newImplementation) internal {
                     *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                     *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                     *     }
                     * }
                     * ```
                     *
                     * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
                     * _Available since v4.9 for `string`, `bytes`._
                     */
                    library StorageSlot {
                        struct AddressSlot {
                            address value;
                        }
                        struct BooleanSlot {
                            bool value;
                        }
                        struct Bytes32Slot {
                            bytes32 value;
                        }
                        struct Uint256Slot {
                            uint256 value;
                        }
                        struct StringSlot {
                            string value;
                        }
                        struct BytesSlot {
                            bytes value;
                        }
                        /**
                         * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                         */
                        function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                         */
                        function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                         */
                        function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                         */
                        function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `StringSlot` with member `value` located at `slot`.
                         */
                        function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
                         */
                        function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := store.slot
                            }
                        }
                        /**
                         * @dev Returns an `BytesSlot` with member `value` located at `slot`.
                         */
                        function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
                         */
                        function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r.slot := store.slot
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC165 standard, as defined in the
                     * https://eips.ethereum.org/EIPS/eip-165[EIP].
                     *
                     * Implementers can declare support of contract interfaces, which can then be
                     * queried by others ({ERC165Checker}).
                     *
                     * For an implementation, see {ERC165}.
                     */
                    interface IERC165 {
                        /**
                         * @dev Returns true if this contract implements the interface defined by
                         * `interfaceId`. See the corresponding
                         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                         * to learn more about how these ids are created.
                         *
                         * This function call must use less than 30 000 gas.
                         */
                        function supportsInterface(bytes4 interfaceId) external view returns (bool);
                    }
                    

                    File 4 of 8: EventsHubProxy
                    // File: contracts/common/misc/ERCProxy.sol
                    
                    /*
                     * SPDX-License-Identitifer:    MIT
                     */
                    
                    pragma solidity ^0.5.2;
                    
                    // See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md
                    
                    interface ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId);
                        function implementation() external view returns (address codeAddr);
                    }
                    
                    // File: contracts/common/misc/DelegateProxyForwarder.sol
                    
                    pragma solidity ^0.5.2;
                    
                    contract DelegateProxyForwarder {
                        function delegatedFwd(address _dst, bytes memory _calldata) internal {
                            // solium-disable-next-line security/no-inline-assembly
                            assembly {
                                let result := delegatecall(
                                    sub(gas, 10000),
                                    _dst,
                                    add(_calldata, 0x20),
                                    mload(_calldata),
                                    0,
                                    0
                                )
                                let size := returndatasize
                    
                                let ptr := mload(0x40)
                                returndatacopy(ptr, 0, size)
                    
                                // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                // if the call returned error data, forward it
                                switch result
                                    case 0 {
                                        revert(ptr, size)
                                    }
                                    default {
                                        return(ptr, size)
                                    }
                            }
                        }
                        
                        function isContract(address _target) internal view returns (bool) {
                            if (_target == address(0)) {
                                return false;
                            }
                    
                            uint256 size;
                            assembly {
                                size := extcodesize(_target)
                            }
                            return size > 0;
                        }
                    }
                    
                    // File: contracts/common/misc/DelegateProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    contract DelegateProxy is ERCProxy, DelegateProxyForwarder {
                        function proxyType() external pure returns (uint256 proxyTypeId) {
                            // Upgradeable proxy
                            proxyTypeId = 2;
                        }
                    
                        function implementation() external view returns (address);
                    }
                    
                    // File: contracts/common/misc/UpgradableProxy.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract UpgradableProxy is DelegateProxy {
                        event ProxyUpdated(address indexed _new, address indexed _old);
                        event OwnerUpdate(address _new, address _old);
                    
                        bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation");
                        bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner");
                    
                        constructor(address _proxyTo) public {
                            setOwner(msg.sender);
                            setImplementation(_proxyTo);
                        }
                    
                        function() external payable {
                            // require(currentContract != 0, "If app code has not been set yet, do not call");
                            // Todo: filter out some calls or handle in the end fallback
                            delegatedFwd(loadImplementation(), msg.data);
                        }
                    
                        modifier onlyProxyOwner() {
                            require(loadOwner() == msg.sender, "NOT_OWNER");
                            _;
                        }
                    
                        function owner() external view returns(address) {
                            return loadOwner();
                        }
                    
                        function loadOwner() internal view returns(address) {
                            address _owner;
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                _owner := sload(position)
                            }
                            return _owner;
                        }
                    
                        function implementation() external view returns (address) {
                            return loadImplementation();
                        }
                    
                        function loadImplementation() internal view returns(address) {
                            address _impl;
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                _impl := sload(position)
                            }
                            return _impl;
                        }
                    
                        function transferOwnership(address newOwner) public onlyProxyOwner {
                            require(newOwner != address(0), "ZERO_ADDRESS");
                            emit OwnerUpdate(newOwner, loadOwner());
                            setOwner(newOwner);
                        }
                    
                        function setOwner(address newOwner) private {
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                sstore(position, newOwner)
                            }
                        }
                    
                        function updateImplementation(address _newProxyTo) public onlyProxyOwner {
                            require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS");
                            require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT");
                    
                            emit ProxyUpdated(_newProxyTo, loadImplementation());
                            
                            setImplementation(_newProxyTo);
                        }
                    
                        function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner {
                            updateImplementation(_newProxyTo);
                    
                            (bool success, bytes memory returnData) = address(this).call.value(msg.value)(data);
                            require(success, string(returnData));
                        }
                    
                        function setImplementation(address _newProxyTo) private {
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                sstore(position, _newProxyTo)
                            }
                        }
                    }
                    
                    // File: contracts/staking/EventsHubProxy.sol
                    
                    pragma solidity 0.5.17;
                    
                    
                    contract EventsHubProxy is UpgradableProxy {
                        constructor(address _proxyTo) public UpgradableProxy(_proxyTo) {}
                    }

                    File 5 of 8: Registry
                    /**
                    Matic network contracts
                    */
                    
                    pragma solidity ^0.5.2;
                    
                    
                    interface IGovernance {
                        function update(address target, bytes calldata data) external;
                    }
                    
                    contract Governable {
                        IGovernance public governance;
                    
                        constructor(address _governance) public {
                            governance = IGovernance(_governance);
                        }
                    
                        modifier onlyGovernance() {
                            require(
                                msg.sender == address(governance),
                                "Only governance contract is authorized"
                            );
                            _;
                        }
                    }
                    
                    contract IWithdrawManager {
                        function createExitQueue(address token) external;
                    
                        function verifyInclusion(
                            bytes calldata data,
                            uint8 offset,
                            bool verifyTxInclusion
                        ) external view returns (uint256 age);
                    
                        function addExitToQueue(
                            address exitor,
                            address childToken,
                            address rootToken,
                            uint256 exitAmountOrTokenId,
                            bytes32 txHash,
                            bool isRegularExit,
                            uint256 priority
                        ) external;
                    
                        function addInput(
                            uint256 exitId,
                            uint256 age,
                            address utxoOwner,
                            address token
                        ) external;
                    
                        function challengeExit(
                            uint256 exitId,
                            uint256 inputId,
                            bytes calldata challengeData,
                            address adjudicatorPredicate
                        ) external;
                    }
                    
                    contract Registry is Governable {
                        // @todo hardcode constants
                        bytes32 private constant WETH_TOKEN = keccak256("wethToken");
                        bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
                        bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
                        bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
                        bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
                        bytes32 private constant CHILD_CHAIN = keccak256("childChain");
                        bytes32 private constant STATE_SENDER = keccak256("stateSender");
                        bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
                    
                        address public erc20Predicate;
                        address public erc721Predicate;
                    
                        mapping(bytes32 => address) public contractMap;
                        mapping(address => address) public rootToChildToken;
                        mapping(address => address) public childToRootToken;
                        mapping(address => bool) public proofValidatorContracts;
                        mapping(address => bool) public isERC721;
                    
                        enum Type {Invalid, ERC20, ERC721, Custom}
                        struct Predicate {
                            Type _type;
                        }
                        mapping(address => Predicate) public predicates;
                    
                        event TokenMapped(address indexed rootToken, address indexed childToken);
                        event ProofValidatorAdded(address indexed validator, address indexed from);
                        event ProofValidatorRemoved(address indexed validator, address indexed from);
                        event PredicateAdded(address indexed predicate, address indexed from);
                        event PredicateRemoved(address indexed predicate, address indexed from);
                        event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
                    
                        constructor(address _governance) public Governable(_governance) {}
                    
                        function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
                            emit ContractMapUpdated(_key, contractMap[_key], _address);
                            contractMap[_key] = _address;
                        }
                    
                        /**
                         * @dev Map root token to child token
                         * @param _rootToken Token address on the root chain
                         * @param _childToken Token address on the child chain
                         * @param _isERC721 Is the token being mapped ERC721
                         */
                        function mapToken(
                            address _rootToken,
                            address _childToken,
                            bool _isERC721
                        ) external onlyGovernance {
                            require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
                            rootToChildToken[_rootToken] = _childToken;
                            childToRootToken[_childToken] = _rootToken;
                            isERC721[_rootToken] = _isERC721;
                            IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
                            emit TokenMapped(_rootToken, _childToken);
                        }
                    
                        function addErc20Predicate(address predicate) public onlyGovernance {
                            require(predicate != address(0x0), "Can not add null address as predicate");
                            erc20Predicate = predicate;
                            addPredicate(predicate, Type.ERC20);
                        }
                    
                        function addErc721Predicate(address predicate) public onlyGovernance {
                            erc721Predicate = predicate;
                            addPredicate(predicate, Type.ERC721);
                        }
                    
                        function addPredicate(address predicate, Type _type) public onlyGovernance {
                            require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
                            predicates[predicate]._type = _type;
                            emit PredicateAdded(predicate, msg.sender);
                        }
                    
                        function removePredicate(address predicate) public onlyGovernance {
                            require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
                            delete predicates[predicate];
                            emit PredicateRemoved(predicate, msg.sender);
                        }
                    
                        function getValidatorShareAddress() public view returns (address) {
                            return contractMap[VALIDATOR_SHARE];
                        }
                    
                        function getWethTokenAddress() public view returns (address) {
                            return contractMap[WETH_TOKEN];
                        }
                    
                        function getDepositManagerAddress() public view returns (address) {
                            return contractMap[DEPOSIT_MANAGER];
                        }
                    
                        function getStakeManagerAddress() public view returns (address) {
                            return contractMap[STAKE_MANAGER];
                        }
                    
                        function getSlashingManagerAddress() public view returns (address) {
                            return contractMap[SLASHING_MANAGER];
                        }
                    
                        function getWithdrawManagerAddress() public view returns (address) {
                            return contractMap[WITHDRAW_MANAGER];
                        }
                    
                        function getChildChainAndStateSender() public view returns (address, address) {
                            return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
                        }
                    
                        function isTokenMapped(address _token) public view returns (bool) {
                            return rootToChildToken[_token] != address(0x0);
                        }
                    
                        function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
                            require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
                            return isERC721[_token];
                        }
                    
                        function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
                            if (isTokenMappedAndIsErc721(_token)) {
                                return erc721Predicate;
                            }
                            return erc20Predicate;
                        }
                    
                        function isChildTokenErc721(address childToken) public view returns (bool) {
                            address rootToken = childToRootToken[childToken];
                            require(rootToken != address(0x0), "Child token is not mapped");
                            return isERC721[rootToken];
                        }
                    }

                    File 6 of 8: ValidatorShare
                    pragma solidity 0.5.17;
                    import {Registry} from "../../common/Registry.sol";
                    import {ERC20NonTradable} from "../../common/tokens/ERC20NonTradable.sol";
                    import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
                    import {StakingInfo} from "./../StakingInfo.sol";
                    import {EventsHub} from "./../EventsHub.sol";
                    import {OwnableLockable} from "../../common/mixin/OwnableLockable.sol";
                    import {IStakeManager} from "../stakeManager/IStakeManager.sol";
                    import {IValidatorShare} from "./IValidatorShare.sol";
                    import {Initializable} from "../../common/mixin/Initializable.sol";
                    import {IERC20Permit} from "./../../common/misc/IERC20Permit.sol";
                    contract ValidatorShare is IValidatorShare, ERC20NonTradable, OwnableLockable, Initializable {
                        struct DelegatorUnbond {
                            uint256 shares;
                            uint256 withdrawEpoch;
                        }
                        uint256 constant EXCHANGE_RATE_PRECISION = 100;
                        // maximum matic possible, even if rate will be 1 and all matic will be staked in one go, it will result in 10 ^ 58 shares
                        uint256 constant EXCHANGE_RATE_HIGH_PRECISION = 10**29;
                        uint256 constant MAX_COMMISION_RATE = 100;
                        uint256 constant REWARD_PRECISION = 10**25;
                        StakingInfo public stakingLogger;
                        IStakeManager public stakeManager;
                        uint256 public validatorId;
                        uint256 public validatorRewards_deprecated;
                        uint256 public commissionRate_deprecated;
                        uint256 public lastCommissionUpdate_deprecated;
                        uint256 public minAmount;
                        uint256 public totalStake_deprecated;
                        uint256 public rewardPerShare;
                        uint256 public activeAmount;
                        bool public delegation;
                        uint256 public withdrawPool;
                        uint256 public withdrawShares;
                        mapping(address => uint256) amountStaked_deprecated; // deprecated, keep for foundation delegators
                        mapping(address => DelegatorUnbond) public unbonds;
                        mapping(address => uint256) public initalRewardPerShare;
                        mapping(address => uint256) public unbondNonces;
                        mapping(address => mapping(uint256 => DelegatorUnbond)) public unbonds_new;
                        EventsHub public eventsHub;
                        IERC20Permit public polToken;
                        constructor() public {
                            _disableInitializer();
                        }
                        // onlyOwner will prevent this contract from initializing, since it's owner is going to be 0x0 address
                        function initialize(
                            uint256 _validatorId,
                            address _stakingLogger,
                            address _stakeManager
                        ) external initializer {
                            validatorId = _validatorId;
                            stakingLogger = StakingInfo(_stakingLogger);
                            stakeManager = IStakeManager(_stakeManager);
                            _transferOwnership(_stakeManager);
                            _getOrCacheEventsHub();
                            minAmount = 10**18;
                            delegation = true;
                        }
                        /**
                            Public View Methods
                        */
                        function exchangeRate() public view returns (uint256) {
                            uint256 totalShares = totalSupply();
                            uint256 precision = _getRatePrecision();
                            return totalShares == 0 ? precision : stakeManager.delegatedAmount(validatorId).mul(precision).div(totalShares);
                        }
                        function getTotalStake(address user) public view returns (uint256, uint256) {
                            uint256 shares = balanceOf(user);
                            uint256 rate = exchangeRate();
                            if (shares == 0) {
                                return (0, rate);
                            }
                            return (rate.mul(shares).div(_getRatePrecision()), rate);
                        }
                        function withdrawExchangeRate() public view returns (uint256) {
                            uint256 precision = _getRatePrecision();
                            if (validatorId < 8) {
                                // fix of potentially broken withdrawals for future unbonding
                                // foundation validators have no slashing enabled and thus we can return default exchange rate
                                // because without slashing rate will stay constant
                                return precision;
                            }
                            uint256 _withdrawShares = withdrawShares;
                            return _withdrawShares == 0 ? precision : withdrawPool.mul(precision).div(_withdrawShares);
                        }
                        function getLiquidRewards(address user) public view returns (uint256) {
                            return _calculateReward(user, getRewardPerShare());
                        }
                        function getRewardPerShare() public view returns (uint256) {
                            return _calculateRewardPerShareWithRewards(stakeManager.delegatorsReward(validatorId));
                        }
                        /**
                            Public Methods
                         */
                        function buyVoucher(uint256 _amount, uint256 _minSharesToMint) public returns (uint256 amountToDeposit) {
                            return _buyVoucher(_amount, _minSharesToMint, false);
                        }
                        // @dev permit only available on pol token
                        // @dev txn fails if frontrun, use buyVoucher instead
                        function buyVoucherWithPermit(
                            uint256 _amount,
                            uint256 _minSharesToMint,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public returns (uint256 amountToDeposit) {
                            IERC20Permit _polToken = _getOrCachePOLToken();
                            uint256 nonceBefore = _polToken.nonces(msg.sender);
                            _polToken.permit(msg.sender, address(stakeManager), _amount, deadline, v, r, s);
                            require(_polToken.nonces(msg.sender) == nonceBefore + 1, "Invalid permit");
                            return _buyVoucher(_amount, _minSharesToMint, true); // invokes stakeManager to pull token from msg.sender
                        }
                        function buyVoucherPOL(uint256 _amount, uint256 _minSharesToMint) public returns (uint256 amountToDeposit) {
                            return _buyVoucher(_amount, _minSharesToMint, true);
                        }
                        function _buyVoucher(uint256 _amount, uint256 _minSharesToMint, bool pol) internal returns (uint256 amountToDeposit) {
                            _withdrawAndTransferReward(msg.sender, pol);
                            amountToDeposit = _buyShares(_amount, _minSharesToMint, msg.sender);
                            require(
                                pol
                                    ? stakeManager.delegationDepositPOL(validatorId, amountToDeposit, msg.sender)
                                    : stakeManager.delegationDeposit(validatorId, amountToDeposit, msg.sender),
                                "deposit failed"
                            );
                            return amountToDeposit;
                        }
                        function restake() public returns (uint256, uint256) {
                            return _restake(false);
                        }
                        function restakePOL() public returns (uint256, uint256) {
                            return _restake(true);
                        }
                        function _restake(bool pol) public returns (uint256, uint256) {
                            address user = msg.sender;
                            uint256 liquidReward = _withdrawReward(user);
                            uint256 amountRestaked;
                            require(liquidReward >= minAmount, "Too small rewards to restake");
                            if (liquidReward != 0) {
                                amountRestaked = _buyShares(liquidReward, 0, user);
                                if (liquidReward > amountRestaked) {
                                    // return change to the user
                                    require(
                                        pol
                                            ? stakeManager.transferFundsPOL(validatorId, liquidReward - amountRestaked, user)
                                            : stakeManager.transferFunds(validatorId, liquidReward - amountRestaked, user),
                                        "Insufficent rewards"
                                    );
                                    stakingLogger.logDelegatorClaimRewards(validatorId, user, liquidReward - amountRestaked);
                                }
                                (uint256 totalStaked, ) = getTotalStake(user);
                                stakingLogger.logDelegatorRestaked(validatorId, user, totalStaked);
                            }
                            
                            return (amountRestaked, liquidReward);
                        }
                        function sellVoucher(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            __sellVoucher(claimAmount, maximumSharesToBurn, false);
                        }
                        function sellVoucherPOL(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            __sellVoucher(claimAmount, maximumSharesToBurn, true);
                        }
                        function __sellVoucher(uint256 claimAmount, uint256 maximumSharesToBurn, bool pol) internal {
                            (uint256 shares, uint256 _withdrawPoolShare) = _sellVoucher(claimAmount, maximumSharesToBurn, pol);
                            DelegatorUnbond memory unbond = unbonds[msg.sender];
                            unbond.shares = unbond.shares.add(_withdrawPoolShare);
                            // refresh unbond period
                            unbond.withdrawEpoch = stakeManager.epoch();
                            unbonds[msg.sender] = unbond;
                            StakingInfo logger = stakingLogger;
                            logger.logShareBurned(validatorId, msg.sender, claimAmount, shares);
                            logger.logStakeUpdate(validatorId);
                        }
                        function withdrawRewards() public {
                            _withdrawRewards(false);
                        }
                        function withdrawRewardsPOL() public {
                            _withdrawRewards(true);
                        }
                        function _withdrawRewards(bool pol) internal {
                            uint256 rewards = _withdrawAndTransferReward(msg.sender, pol);
                            require(rewards >= minAmount, "Too small rewards amount");
                        }
                        function migrateOut(address user, uint256 amount) external onlyOwner {
                            _withdrawAndTransferReward(user, true);
                            (uint256 totalStaked, uint256 rate) = getTotalStake(user);
                            require(totalStaked >= amount, "Migrating too much");
                            uint256 precision = _getRatePrecision();
                            uint256 shares = amount.mul(precision).div(rate);
                            _burn(user, shares);
                            stakeManager.updateValidatorState(validatorId, -int256(amount));
                            activeAmount = activeAmount.sub(amount);
                            stakingLogger.logShareBurned(validatorId, user, amount, shares);
                            stakingLogger.logStakeUpdate(validatorId);
                            stakingLogger.logDelegatorUnstaked(validatorId, user, amount);
                        }
                        function migrateIn(address user, uint256 amount) external onlyOwner {
                            _withdrawAndTransferReward(user, true);
                            _buyShares(amount, 0, user);
                        } 
                        function unstakeClaimTokens() public {
                            _unstakeClaimTokens(false);
                        }
                        function unstakeClaimTokensPOL() public {
                            _unstakeClaimTokens(true);
                        }
                        function _unstakeClaimTokens(bool pol) internal {
                            DelegatorUnbond memory unbond = unbonds[msg.sender];
                            uint256 amount = _unstakeClaimTokens(unbond, pol);
                            delete unbonds[msg.sender];
                            stakingLogger.logDelegatorUnstaked(validatorId, msg.sender, amount);
                        }
                        function slash(
                            uint256 validatorStake,
                            uint256 delegatedAmount,
                            uint256 totalAmountToSlash
                        ) external onlyOwner returns (uint256) {
                            revert("Slashing disabled");
                        }
                        function updateDelegation(bool _delegation) external onlyOwner {
                            delegation = _delegation;
                        }
                        function drain(
                            address token,
                            address payable destination,
                            uint256 amount
                        ) external onlyOwner {
                            revert("No draining.");
                        }
                        /**
                            New shares exit API
                         */
                        function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            _sellVoucher_new(claimAmount, maximumSharesToBurn, false);
                        }
                        function sellVoucher_newPOL(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            _sellVoucher_new(claimAmount, maximumSharesToBurn, true);
                        }
                        function _sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn, bool pol) public {
                            (uint256 shares, uint256 _withdrawPoolShare) = _sellVoucher(claimAmount, maximumSharesToBurn, pol);
                            uint256 unbondNonce = unbondNonces[msg.sender].add(1);
                            DelegatorUnbond memory unbond = DelegatorUnbond({
                                shares: _withdrawPoolShare,
                                withdrawEpoch: stakeManager.epoch()
                            });
                            unbonds_new[msg.sender][unbondNonce] = unbond;
                            unbondNonces[msg.sender] = unbondNonce;
                            _getOrCacheEventsHub().logShareBurnedWithId(validatorId, msg.sender, claimAmount, shares, unbondNonce);
                            stakingLogger.logStakeUpdate(validatorId);
                        }
                        function unstakeClaimTokens_new(uint256 unbondNonce) public {
                            _unstakeClaimTokens_new(unbondNonce, false);
                        }
                        function unstakeClaimTokens_newPOL(uint256 unbondNonce) public {
                            _unstakeClaimTokens_new(unbondNonce, true);
                        }
                        function _unstakeClaimTokens_new(uint256 unbondNonce, bool pol) internal {
                            DelegatorUnbond memory unbond = unbonds_new[msg.sender][unbondNonce];
                            uint256 amount = _unstakeClaimTokens(unbond, pol);
                            delete unbonds_new[msg.sender][unbondNonce];
                            _getOrCacheEventsHub().logDelegatorUnstakedWithId(validatorId, msg.sender, amount, unbondNonce);
                        }
                        /**
                            Private Methods
                         */
                        function _getOrCacheEventsHub() private returns(EventsHub) {
                            EventsHub _eventsHub = eventsHub;
                            if (_eventsHub == EventsHub(0x0)) {
                                _eventsHub = EventsHub(Registry(stakeManager.getRegistry()).contractMap(keccak256("eventsHub")));
                                eventsHub = _eventsHub;
                            }
                            return _eventsHub;
                        }
                        function _getOrCachePOLToken() private returns (IERC20Permit) {
                            IERC20Permit _polToken = polToken;
                            if (_polToken == IERC20Permit(0x0)) {
                                _polToken = IERC20Permit(Registry(stakeManager.getRegistry()).contractMap(keccak256("pol")));
                                require(_polToken != IERC20Permit(0x0), "unset");
                                polToken = _polToken;
                            }
                            return _polToken;
                        }
                        function _sellVoucher(
                            uint256 claimAmount,
                            uint256 maximumSharesToBurn,
                            bool pol
                        ) private returns (uint256, uint256) {
                            // first get how much staked in total and compare to target unstake amount
                            (uint256 totalStaked, uint256 rate) = getTotalStake(msg.sender);
                            require(totalStaked != 0 && totalStaked >= claimAmount, "Too much requested");
                            // convert requested amount back to shares
                            uint256 precision = _getRatePrecision();
                            uint256 shares = claimAmount.mul(precision).div(rate);
                            require(shares <= maximumSharesToBurn, "too much slippage");
                            _withdrawAndTransferReward(msg.sender, pol);
                            _burn(msg.sender, shares);
                            stakeManager.updateValidatorState(validatorId, -int256(claimAmount));
                            activeAmount = activeAmount.sub(claimAmount);
                            uint256 _withdrawPoolShare = claimAmount.mul(precision).div(withdrawExchangeRate());
                            withdrawPool = withdrawPool.add(claimAmount);
                            withdrawShares = withdrawShares.add(_withdrawPoolShare);
                            return (shares, _withdrawPoolShare);
                        }
                        function _unstakeClaimTokens(DelegatorUnbond memory unbond, bool pol) private returns (uint256) {
                            uint256 shares = unbond.shares;
                            require(
                                unbond.withdrawEpoch.add(stakeManager.withdrawalDelay()) <= stakeManager.epoch() && shares > 0,
                                "Incomplete withdrawal period"
                            );
                            uint256 _amount = withdrawExchangeRate().mul(shares).div(_getRatePrecision());
                            withdrawShares = withdrawShares.sub(shares);
                            withdrawPool = withdrawPool.sub(_amount);
                            require(
                                pol ? stakeManager.transferFundsPOL(validatorId, _amount, msg.sender) : stakeManager.transferFunds(validatorId, _amount, msg.sender),
                                "Insufficent rewards"
                            );
                            return _amount;
                        }
                        function _getRatePrecision() private view returns (uint256) {
                            // if foundation validator, use old precision
                            if (validatorId < 8) {
                                return EXCHANGE_RATE_PRECISION;
                            }
                            return EXCHANGE_RATE_HIGH_PRECISION;
                        }
                        function _calculateRewardPerShareWithRewards(uint256 accumulatedReward) private view returns (uint256) {
                            uint256 _rewardPerShare = rewardPerShare;
                            if (accumulatedReward != 0) {
                                uint256 totalShares = totalSupply();
                                
                                if (totalShares != 0) {
                                    _rewardPerShare = _rewardPerShare.add(accumulatedReward.mul(REWARD_PRECISION).div(totalShares));
                                }
                            }
                            return _rewardPerShare;
                        }
                        function _calculateReward(address user, uint256 _rewardPerShare) private view returns (uint256) {
                            uint256 shares = balanceOf(user);
                            if (shares == 0) {
                                return 0;
                            }
                            uint256 _initialRewardPerShare = initalRewardPerShare[user];
                            if (_initialRewardPerShare == _rewardPerShare) {
                                return 0;
                            }
                            return _rewardPerShare.sub(_initialRewardPerShare).mul(shares).div(REWARD_PRECISION);
                        }
                        function _withdrawReward(address user) private returns (uint256) {
                            uint256 _rewardPerShare = _calculateRewardPerShareWithRewards(
                                stakeManager.withdrawDelegatorsReward(validatorId)
                            );
                            uint256 liquidRewards = _calculateReward(user, _rewardPerShare);
                            
                            rewardPerShare = _rewardPerShare;
                            initalRewardPerShare[user] = _rewardPerShare;
                            return liquidRewards;
                        }
                        function _withdrawAndTransferReward(address user, bool pol) private returns (uint256) {
                            uint256 liquidRewards = _withdrawReward(user);
                            if (liquidRewards != 0) {
                                require(
                                    pol ? stakeManager.transferFundsPOL(validatorId, liquidRewards, user) : stakeManager.transferFunds(validatorId, liquidRewards, user),
                                    "Insufficent rewards"
                                );
                                stakingLogger.logDelegatorClaimRewards(validatorId, user, liquidRewards);
                            }
                            return liquidRewards;
                        }
                        function _buyShares(
                            uint256 _amount,
                            uint256 _minSharesToMint,
                            address user
                        ) private onlyWhenUnlocked returns (uint256) {
                            require(delegation, "Delegation is disabled");
                            uint256 rate = exchangeRate();
                            uint256 precision = _getRatePrecision();
                            uint256 shares = _amount.mul(precision).div(rate);
                            require(shares >= _minSharesToMint, "Too much slippage");
                            require(unbonds[user].shares == 0, "Ongoing exit");
                            _mint(user, shares);
                            // clamp amount of tokens in case resulted shares requires less tokens than anticipated
                            _amount = rate.mul(shares).div(precision);
                            stakeManager.updateValidatorState(validatorId, int256(_amount));
                            activeAmount = activeAmount.add(_amount);
                            StakingInfo logger = stakingLogger;
                            logger.logShareMinted(validatorId, user, _amount, shares);
                            logger.logStakeUpdate(validatorId);
                            return _amount;
                        }
                        function transferPOL(address to, uint256 value) public returns (bool) {
                            _transfer(to, value, true);
                            return true;
                        }
                        function transfer(address to, uint256 value) public returns (bool) {
                            _transfer(to, value, false);
                            return true;
                        }
                        function _transfer(address to, uint256 value, bool pol) internal {
                            address from = msg.sender;
                            // get rewards for recipient
                            _withdrawAndTransferReward(to, pol);
                            // convert rewards to shares
                            _withdrawAndTransferReward(from, pol);
                            // move shares to recipient
                            super._transfer(from, to, value);
                            _getOrCacheEventsHub().logSharesTransfer(validatorId, from, to, value);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Governable} from "./governance/Governable.sol";
                    import {IWithdrawManager} from "../root/withdrawManager/IWithdrawManager.sol";
                    contract Registry is Governable {
                        // @todo hardcode constants
                        bytes32 private constant WETH_TOKEN = keccak256("wethToken");
                        bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
                        bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
                        bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
                        bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
                        bytes32 private constant CHILD_CHAIN = keccak256("childChain");
                        bytes32 private constant STATE_SENDER = keccak256("stateSender");
                        bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
                        address public erc20Predicate;
                        address public erc721Predicate;
                        mapping(bytes32 => address) public contractMap;
                        mapping(address => address) public rootToChildToken;
                        mapping(address => address) public childToRootToken;
                        mapping(address => bool) public proofValidatorContracts;
                        mapping(address => bool) public isERC721;
                        enum Type {Invalid, ERC20, ERC721, Custom}
                        struct Predicate {
                            Type _type;
                        }
                        mapping(address => Predicate) public predicates;
                        event TokenMapped(address indexed rootToken, address indexed childToken);
                        event ProofValidatorAdded(address indexed validator, address indexed from);
                        event ProofValidatorRemoved(address indexed validator, address indexed from);
                        event PredicateAdded(address indexed predicate, address indexed from);
                        event PredicateRemoved(address indexed predicate, address indexed from);
                        event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
                        constructor(address _governance) public Governable(_governance) {}
                        function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
                            emit ContractMapUpdated(_key, contractMap[_key], _address);
                            contractMap[_key] = _address;
                        }
                        /**
                         * @dev Map root token to child token
                         * @param _rootToken Token address on the root chain
                         * @param _childToken Token address on the child chain
                         * @param _isERC721 Is the token being mapped ERC721
                         */
                        function mapToken(
                            address _rootToken,
                            address _childToken,
                            bool _isERC721
                        ) external onlyGovernance {
                            require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
                            rootToChildToken[_rootToken] = _childToken;
                            childToRootToken[_childToken] = _rootToken;
                            isERC721[_rootToken] = _isERC721;
                            IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
                            emit TokenMapped(_rootToken, _childToken);
                        }
                        function addErc20Predicate(address predicate) public onlyGovernance {
                            require(predicate != address(0x0), "Can not add null address as predicate");
                            erc20Predicate = predicate;
                            addPredicate(predicate, Type.ERC20);
                        }
                        function addErc721Predicate(address predicate) public onlyGovernance {
                            erc721Predicate = predicate;
                            addPredicate(predicate, Type.ERC721);
                        }
                        function addPredicate(address predicate, Type _type) public onlyGovernance {
                            require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
                            predicates[predicate]._type = _type;
                            emit PredicateAdded(predicate, msg.sender);
                        }
                        function removePredicate(address predicate) public onlyGovernance {
                            require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
                            delete predicates[predicate];
                            emit PredicateRemoved(predicate, msg.sender);
                        }
                        function getValidatorShareAddress() public view returns (address) {
                            return contractMap[VALIDATOR_SHARE];
                        }
                        function getWethTokenAddress() public view returns (address) {
                            return contractMap[WETH_TOKEN];
                        }
                        function getDepositManagerAddress() public view returns (address) {
                            return contractMap[DEPOSIT_MANAGER];
                        }
                        function getStakeManagerAddress() public view returns (address) {
                            return contractMap[STAKE_MANAGER];
                        }
                        function getSlashingManagerAddress() public view returns (address) {
                            return contractMap[SLASHING_MANAGER];
                        }
                        function getWithdrawManagerAddress() public view returns (address) {
                            return contractMap[WITHDRAW_MANAGER];
                        }
                        function getChildChainAndStateSender() public view returns (address, address) {
                            return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
                        }
                        function isTokenMapped(address _token) public view returns (bool) {
                            return rootToChildToken[_token] != address(0x0);
                        }
                        function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
                            require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
                            return isERC721[_token];
                        }
                        function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
                            if (isTokenMappedAndIsErc721(_token)) {
                                return erc721Predicate;
                            }
                            return erc20Predicate;
                        }
                        function isChildTokenErc721(address childToken) public view returns (bool) {
                            address rootToken = childToRootToken[childToken];
                            require(rootToken != address(0x0), "Child token is not mapped");
                            return isERC721[rootToken];
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
                    contract ERC20NonTradable is ERC20 {
                        function _approve(
                            address owner,
                            address spender,
                            uint256 value
                        ) internal {
                            revert("disabled");
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC20.sol";
                    import "../../math/SafeMath.sol";
                    /**
                     * @title Standard ERC20 token
                     *
                     * @dev Implementation of the basic standard token.
                     * https://eips.ethereum.org/EIPS/eip-20
                     * Originally based on code by FirstBlood:
                     * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
                     *
                     * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
                     * all accounts just by listening to said events. Note that this isn't required by the specification, and other
                     * compliant implementations may not do it.
                     */
                    contract ERC20 is IERC20 {
                        using SafeMath for uint256;
                        mapping (address => uint256) private _balances;
                        mapping (address => mapping (address => uint256)) private _allowed;
                        uint256 private _totalSupply;
                        /**
                         * @dev Total number of tokens in existence
                         */
                        function totalSupply() public view returns (uint256) {
                            return _totalSupply;
                        }
                        /**
                         * @dev Gets the balance of the specified address.
                         * @param owner The address to query the balance of.
                         * @return A uint256 representing the amount owned by the passed address.
                         */
                        function balanceOf(address owner) public view returns (uint256) {
                            return _balances[owner];
                        }
                        /**
                         * @dev Function to check the amount of tokens that an owner allowed to a spender.
                         * @param owner address The address which owns the funds.
                         * @param spender address The address which will spend the funds.
                         * @return A uint256 specifying the amount of tokens still available for the spender.
                         */
                        function allowance(address owner, address spender) public view returns (uint256) {
                            return _allowed[owner][spender];
                        }
                        /**
                         * @dev Transfer token to a specified address
                         * @param to The address to transfer to.
                         * @param value The amount to be transferred.
                         */
                        function transfer(address to, uint256 value) public returns (bool) {
                            _transfer(msg.sender, to, value);
                            return true;
                        }
                        /**
                         * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                         * Beware that changing an allowance with this method brings the risk that someone may use both the old
                         * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
                         * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         * @param spender The address which will spend the funds.
                         * @param value The amount of tokens to be spent.
                         */
                        function approve(address spender, uint256 value) public returns (bool) {
                            _approve(msg.sender, spender, value);
                            return true;
                        }
                        /**
                         * @dev Transfer tokens from one address to another.
                         * Note that while this function emits an Approval event, this is not required as per the specification,
                         * and other compliant implementations may not emit the event.
                         * @param from address The address which you want to send tokens from
                         * @param to address The address which you want to transfer to
                         * @param value uint256 the amount of tokens to be transferred
                         */
                        function transferFrom(address from, address to, uint256 value) public returns (bool) {
                            _transfer(from, to, value);
                            _approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
                            return true;
                        }
                        /**
                         * @dev Increase the amount of tokens that an owner allowed to a spender.
                         * approve should be called when _allowed[msg.sender][spender] == 0. To increment
                         * allowed value is better to use this function to avoid 2 calls (and wait until
                         * the first transaction is mined)
                         * From MonolithDAO Token.sol
                         * Emits an Approval event.
                         * @param spender The address which will spend the funds.
                         * @param addedValue The amount of tokens to increase the allowance by.
                         */
                        function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
                            _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
                            return true;
                        }
                        /**
                         * @dev Decrease the amount of tokens that an owner allowed to a spender.
                         * approve should be called when _allowed[msg.sender][spender] == 0. To decrement
                         * allowed value is better to use this function to avoid 2 calls (and wait until
                         * the first transaction is mined)
                         * From MonolithDAO Token.sol
                         * Emits an Approval event.
                         * @param spender The address which will spend the funds.
                         * @param subtractedValue The amount of tokens to decrease the allowance by.
                         */
                        function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
                            _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
                            return true;
                        }
                        /**
                         * @dev Transfer token for a specified addresses
                         * @param from The address to transfer from.
                         * @param to The address to transfer to.
                         * @param value The amount to be transferred.
                         */
                        function _transfer(address from, address to, uint256 value) internal {
                            require(to != address(0));
                            _balances[from] = _balances[from].sub(value);
                            _balances[to] = _balances[to].add(value);
                            emit Transfer(from, to, value);
                        }
                        /**
                         * @dev Internal function that mints an amount of the token and assigns it to
                         * an account. This encapsulates the modification of balances such that the
                         * proper events are emitted.
                         * @param account The account that will receive the created tokens.
                         * @param value The amount that will be created.
                         */
                        function _mint(address account, uint256 value) internal {
                            require(account != address(0));
                            _totalSupply = _totalSupply.add(value);
                            _balances[account] = _balances[account].add(value);
                            emit Transfer(address(0), account, value);
                        }
                        /**
                         * @dev Internal function that burns an amount of the token of a given
                         * account.
                         * @param account The account whose tokens will be burnt.
                         * @param value The amount that will be burnt.
                         */
                        function _burn(address account, uint256 value) internal {
                            require(account != address(0));
                            _totalSupply = _totalSupply.sub(value);
                            _balances[account] = _balances[account].sub(value);
                            emit Transfer(account, address(0), value);
                        }
                        /**
                         * @dev Approve an address to spend another addresses' tokens.
                         * @param owner The address that owns the tokens.
                         * @param spender The address that will spend the tokens.
                         * @param value The number of tokens that can be spent.
                         */
                        function _approve(address owner, address spender, uint256 value) internal {
                            require(spender != address(0));
                            require(owner != address(0));
                            _allowed[owner][spender] = value;
                            emit Approval(owner, spender, value);
                        }
                        /**
                         * @dev Internal function that burns an amount of the token of a given
                         * account, deducting from the sender's allowance for said account. Uses the
                         * internal burn function.
                         * Emits an Approval event (reflecting the reduced allowance).
                         * @param account The account whose tokens will be burnt.
                         * @param value The amount that will be burnt.
                         */
                        function _burnFrom(address account, uint256 value) internal {
                            _burn(account, value);
                            _approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Registry} from "../common/Registry.sol";
                    import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
                    import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    // dummy interface to avoid cyclic dependency
                    contract IStakeManagerLocal {
                        enum Status {Inactive, Active, Locked, Unstaked}
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                            Status status;
                        }
                        mapping(uint256 => Validator) public validators;
                        bytes32 public accountStateRoot;
                        uint256 public activeAmount; // delegation amount from validator contract
                        uint256 public validatorRewards;
                        function currentValidatorSetTotalStake() public view returns (uint256);
                        // signer to Validator mapping
                        function signerToValidator(address validatorAddress)
                            public
                            view
                            returns (uint256);
                        function isValidator(uint256 validatorId) public view returns (bool);
                    }
                    contract StakingInfo is Ownable {
                        using SafeMath for uint256;
                        mapping(uint256 => uint256) public validatorNonce;
                        /// @dev Emitted when validator stakes in '_stakeFor()' in StakeManager.
                        /// @param signer validator address.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param activationEpoch validator's first epoch as proposer.
                        /// @param amount staking amount.
                        /// @param total total staking amount.
                        /// @param signerPubkey public key of the validator
                        event Staked(
                            address indexed signer,
                            uint256 indexed validatorId,
                            uint256 nonce,
                            uint256 indexed activationEpoch,
                            uint256 amount,
                            uint256 total,
                            bytes signerPubkey
                        );
                        /// @dev Emitted when validator unstakes in 'unstakeClaim()'
                        /// @param user address of the validator.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param amount staking amount.
                        /// @param total total staking amount.
                        event Unstaked(
                            address indexed user,
                            uint256 indexed validatorId,
                            uint256 amount,
                            uint256 total
                        );
                        /// @dev Emitted when validator unstakes in '_unstake()'.
                        /// @param user address of the validator.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param deactivationEpoch last epoch for validator.
                        /// @param amount staking amount.
                        event UnstakeInit(
                            address indexed user,
                            uint256 indexed validatorId,
                            uint256 nonce,
                            uint256 deactivationEpoch,
                            uint256 indexed amount
                        );
                        /// @dev Emitted when the validator public key is updated in 'updateSigner()'.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param oldSigner old address of the validator.
                        /// @param newSigner new address of the validator.
                        /// @param signerPubkey public key of the validator.
                        event SignerChange(
                            uint256 indexed validatorId,
                            uint256 nonce,
                            address indexed oldSigner,
                            address indexed newSigner,
                            bytes signerPubkey
                        );
                        event Restaked(uint256 indexed validatorId, uint256 amount, uint256 total);
                        event Jailed(
                            uint256 indexed validatorId,
                            uint256 indexed exitEpoch,
                            address indexed signer
                        );
                        event UnJailed(uint256 indexed validatorId, address indexed signer);
                        event Slashed(uint256 indexed nonce, uint256 indexed amount);
                        event ThresholdChange(uint256 newThreshold, uint256 oldThreshold);
                        event DynastyValueChange(uint256 newDynasty, uint256 oldDynasty);
                        event ProposerBonusChange(
                            uint256 newProposerBonus,
                            uint256 oldProposerBonus
                        );
                        event RewardUpdate(uint256 newReward, uint256 oldReward);
                        /// @dev Emitted when validator confirms the auction bid and at the time of restaking in confirmAuctionBid() and restake().
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param newAmount the updated stake amount.
                        event StakeUpdate(
                            uint256 indexed validatorId,
                            uint256 indexed nonce,
                            uint256 indexed newAmount
                        );
                        event ClaimRewards(
                            uint256 indexed validatorId,
                            uint256 indexed amount,
                            uint256 indexed totalAmount
                        );
                        event StartAuction(
                            uint256 indexed validatorId,
                            uint256 indexed amount,
                            uint256 indexed auctionAmount
                        );
                        event ConfirmAuction(
                            uint256 indexed newValidatorId,
                            uint256 indexed oldValidatorId,
                            uint256 indexed amount
                        );
                        event TopUpFee(address indexed user, uint256 indexed fee);
                        event ClaimFee(address indexed user, uint256 indexed fee);
                        // Delegator events
                        event ShareMinted(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens
                        );
                        event ShareBurned(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens
                        );
                        event DelegatorClaimedRewards(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed rewards
                        );
                        event DelegatorRestaked(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed totalStaked
                        );
                        event DelegatorUnstaked(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 amount
                        );
                        event UpdateCommissionRate(
                            uint256 indexed validatorId,
                            uint256 indexed newCommissionRate,
                            uint256 indexed oldCommissionRate
                        );
                        Registry public registry;
                        modifier onlyValidatorContract(uint256 validatorId) {
                            address _contract;
                            (, , , , , , _contract, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                            require(_contract == msg.sender,
                            "Invalid sender, not validator");
                            _;
                        }
                        modifier StakeManagerOrValidatorContract(uint256 validatorId) {
                            address _contract;
                            address _stakeManager = registry.getStakeManagerAddress();
                            (, , , , , , _contract, ) = IStakeManagerLocal(_stakeManager).validators(
                                validatorId
                            );
                            require(_contract == msg.sender || _stakeManager == msg.sender,
                            "Invalid sender, not stake manager or validator contract");
                            _;
                        }
                        modifier onlyStakeManager() {
                            require(registry.getStakeManagerAddress() == msg.sender,
                            "Invalid sender, not stake manager");
                            _;
                        }
                        modifier onlySlashingManager() {
                            require(registry.getSlashingManagerAddress() == msg.sender,
                            "Invalid sender, not slashing manager");
                            _;
                        }
                        constructor(address _registry) public {
                            registry = Registry(_registry);
                        }
                        function updateNonce(
                            uint256[] calldata validatorIds,
                            uint256[] calldata nonces
                        ) external onlyOwner {
                            require(validatorIds.length == nonces.length, "args length mismatch");
                            for (uint256 i = 0; i < validatorIds.length; ++i) {
                                validatorNonce[validatorIds[i]] = nonces[i];
                            }
                        } 
                        function logStaked(
                            address signer,
                            bytes memory signerPubkey,
                            uint256 validatorId,
                            uint256 activationEpoch,
                            uint256 amount,
                            uint256 total
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit Staked(
                                signer,
                                validatorId,
                                validatorNonce[validatorId],
                                activationEpoch,
                                amount,
                                total,
                                signerPubkey
                            );
                        }
                        function logUnstaked(
                            address user,
                            uint256 validatorId,
                            uint256 amount,
                            uint256 total
                        ) public onlyStakeManager {
                            emit Unstaked(user, validatorId, amount, total);
                        }
                        function logUnstakeInit(
                            address user,
                            uint256 validatorId,
                            uint256 deactivationEpoch,
                            uint256 amount
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit UnstakeInit(
                                user,
                                validatorId,
                                validatorNonce[validatorId],
                                deactivationEpoch,
                                amount
                            );
                        }
                        function logSignerChange(
                            uint256 validatorId,
                            address oldSigner,
                            address newSigner,
                            bytes memory signerPubkey
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit SignerChange(
                                validatorId,
                                validatorNonce[validatorId],
                                oldSigner,
                                newSigner,
                                signerPubkey
                            );
                        }
                        function logRestaked(uint256 validatorId, uint256 amount, uint256 total)
                            public
                            onlyStakeManager
                        {
                            emit Restaked(validatorId, amount, total);
                        }
                        function logJailed(uint256 validatorId, uint256 exitEpoch, address signer)
                            public
                            onlyStakeManager
                        {
                            emit Jailed(validatorId, exitEpoch, signer);
                        }
                        function logUnjailed(uint256 validatorId, address signer)
                            public
                            onlyStakeManager
                        {
                            emit UnJailed(validatorId, signer);
                        }
                        function logSlashed(uint256 nonce, uint256 amount)
                            public
                            onlySlashingManager
                        {
                            emit Slashed(nonce, amount);
                        }
                        function logThresholdChange(uint256 newThreshold, uint256 oldThreshold)
                            public
                            onlyStakeManager
                        {
                            emit ThresholdChange(newThreshold, oldThreshold);
                        }
                        function logDynastyValueChange(uint256 newDynasty, uint256 oldDynasty)
                            public
                            onlyStakeManager
                        {
                            emit DynastyValueChange(newDynasty, oldDynasty);
                        }
                        function logProposerBonusChange(
                            uint256 newProposerBonus,
                            uint256 oldProposerBonus
                        ) public onlyStakeManager {
                            emit ProposerBonusChange(newProposerBonus, oldProposerBonus);
                        }
                        function logRewardUpdate(uint256 newReward, uint256 oldReward)
                            public
                            onlyStakeManager
                        {
                            emit RewardUpdate(newReward, oldReward);
                        }
                        function logStakeUpdate(uint256 validatorId)
                            public
                            StakeManagerOrValidatorContract(validatorId)
                        {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit StakeUpdate(
                                validatorId,
                                validatorNonce[validatorId],
                                totalValidatorStake(validatorId)
                            );
                        }
                        function logClaimRewards(
                            uint256 validatorId,
                            uint256 amount,
                            uint256 totalAmount
                        ) public onlyStakeManager {
                            emit ClaimRewards(validatorId, amount, totalAmount);
                        }
                        function logStartAuction(
                            uint256 validatorId,
                            uint256 amount,
                            uint256 auctionAmount
                        ) public onlyStakeManager {
                            emit StartAuction(validatorId, amount, auctionAmount);
                        }
                        function logConfirmAuction(
                            uint256 newValidatorId,
                            uint256 oldValidatorId,
                            uint256 amount
                        ) public onlyStakeManager {
                            emit ConfirmAuction(newValidatorId, oldValidatorId, amount);
                        }
                        function logTopUpFee(address user, uint256 fee) public onlyStakeManager {
                            emit TopUpFee(user, fee);
                        }
                        function logClaimFee(address user, uint256 fee) public onlyStakeManager {
                            emit ClaimFee(user, fee);
                        }
                        function getStakerDetails(uint256 validatorId)
                            public
                            view
                            returns (
                                uint256 amount,
                                uint256 reward,
                                uint256 activationEpoch,
                                uint256 deactivationEpoch,
                                address signer,
                                uint256 _status
                            )
                        {
                            IStakeManagerLocal stakeManager = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            );
                            address _contract;
                            IStakeManagerLocal.Status status;
                            (
                                amount,
                                reward,
                                activationEpoch,
                                deactivationEpoch,
                                ,
                                signer,
                                _contract,
                                status
                            ) = stakeManager.validators(validatorId);
                            _status = uint256(status);
                            if (_contract != address(0x0)) {
                                reward += IStakeManagerLocal(_contract).validatorRewards();
                            }
                        }
                        function totalValidatorStake(uint256 validatorId)
                            public
                            view
                            returns (uint256 validatorStake)
                        {
                            address contractAddress;
                            (validatorStake, , , , , , contractAddress, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                            if (contractAddress != address(0x0)) {
                                validatorStake += IStakeManagerLocal(contractAddress).activeAmount();
                            }
                        }
                        function getAccountStateRoot()
                            public
                            view
                            returns (bytes32 accountStateRoot)
                        {
                            accountStateRoot = IStakeManagerLocal(registry.getStakeManagerAddress())
                                .accountStateRoot();
                        }
                        function getValidatorContractAddress(uint256 validatorId)
                            public
                            view
                            returns (address ValidatorContract)
                        {
                            (, , , , , , ValidatorContract, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                        }
                        // validator Share contract logging func
                        function logShareMinted(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareMinted(validatorId, user, amount, tokens);
                        }
                        function logShareBurned(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareBurned(validatorId, user, amount, tokens);
                        }
                        function logDelegatorClaimRewards(
                            uint256 validatorId,
                            address user,
                            uint256 rewards
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorClaimedRewards(validatorId, user, rewards);
                        }
                        function logDelegatorRestaked(
                            uint256 validatorId,
                            address user,
                            uint256 totalStaked
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorRestaked(validatorId, user, totalStaked);
                        }
                        function logDelegatorUnstaked(uint256 validatorId, address user, uint256 amount)
                            public
                            onlyValidatorContract(validatorId)
                        {
                            emit DelegatorUnstaked(validatorId, user, amount);
                        }
                        // deprecated
                        function logUpdateCommissionRate(
                            uint256 validatorId,
                            uint256 newCommissionRate,
                            uint256 oldCommissionRate
                        ) public onlyValidatorContract(validatorId) {
                            emit UpdateCommissionRate(
                                validatorId,
                                newCommissionRate,
                                oldCommissionRate
                            );
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Registry} from "../common/Registry.sol";
                    import {Initializable} from "../common/mixin/Initializable.sol";
                    contract IStakeManagerEventsHub {
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                        }
                        mapping(uint256 => Validator) public validators;
                    }
                    contract EventsHub is Initializable {
                        Registry public registry;
                        modifier onlyValidatorContract(uint256 validatorId) {
                            address _contract;
                            (, , , , , , _contract) = IStakeManagerEventsHub(registry.getStakeManagerAddress()).validators(validatorId);
                            require(_contract == msg.sender, "not validator");
                            _;
                        }
                        modifier onlyStakeManager() {
                            require(registry.getStakeManagerAddress() == msg.sender,
                            "Invalid sender, not stake manager");
                            _;
                        }
                        function initialize(Registry _registry) external initializer {
                            registry = _registry;
                        }
                        event ShareBurnedWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens,
                            uint256 nonce
                        );
                        function logShareBurnedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareBurnedWithId(validatorId, user, amount, tokens, nonce);
                        }
                        event DelegatorUnstakeWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 amount,
                            uint256 nonce
                        );
                        function logDelegatorUnstakedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorUnstakeWithId(validatorId, user, amount, nonce);
                        }
                        event RewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        );
                        function logRewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        ) public onlyStakeManager {
                            emit RewardParams(rewardDecreasePerCheckpoint, maxRewardedCheckpoints, checkpointRewardDelta);
                        }
                        event UpdateCommissionRate(
                            uint256 indexed validatorId,
                            uint256 indexed newCommissionRate,
                            uint256 indexed oldCommissionRate
                        );
                        function logUpdateCommissionRate(
                            uint256 validatorId,
                            uint256 newCommissionRate,
                            uint256 oldCommissionRate
                        ) public onlyStakeManager {
                            emit UpdateCommissionRate(
                                validatorId,
                                newCommissionRate,
                                oldCommissionRate
                            );
                        }
                        event SharesTransfer(
                            uint256 indexed validatorId,
                            address indexed from,
                            address indexed to,
                            uint256 value
                        );
                        function logSharesTransfer(
                            uint256 validatorId,
                            address from,
                            address to,
                            uint256 value
                        ) public onlyValidatorContract(validatorId) {
                            emit SharesTransfer(validatorId, from, to, value);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import { Lockable } from "./Lockable.sol";
                    import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    contract OwnableLockable is Lockable, Ownable {
                        function lock() public onlyOwner {
                            super.lock();
                        }
                        function unlock() public onlyOwner {
                            super.unlock();
                        }
                    }
                    pragma solidity 0.5.17;
                    contract IStakeManager {
                        // validator replacement
                        function startAuction(
                            uint256 validatorId,
                            uint256 amount,
                            bool acceptDelegation,
                            bytes calldata signerPubkey
                        ) external;
                        function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external;
                        function transferFunds(
                            uint256 validatorId,
                            uint256 amount,
                            address delegator
                        ) external returns (bool);
                        function transferFundsPOL(
                            uint256 validatorId, 
                            uint256 amount, 
                            address delegator
                        ) external returns (bool);
                        function delegationDeposit(
                            uint256 validatorId,
                            uint256 amount,
                            address delegator
                        ) external returns (bool);
                        function delegationDepositPOL(
                            uint256 validatorId, 
                            uint256 amount, 
                            address delegator
                        ) external returns (bool);
                        function unstake(uint256 validatorId) external;
                        function unstakePOL(uint256 validatorId) external;
                        function totalStakedFor(address addr) external view returns (uint256);
                        function stakeFor(
                            address user,
                            uint256 amount,
                            uint256 heimdallFee,
                            bool acceptDelegation,
                            bytes memory signerPubkey
                        ) public;
                        function stakeForPOL(
                            address user,
                            uint256 amount,
                            uint256 heimdallFee,
                            bool acceptDelegation,
                            bytes memory signerPubkey
                        ) public;
                        function checkSignatures(
                            uint256 blockInterval,
                            bytes32 voteHash,
                            bytes32 stateRoot,
                            address proposer,
                            uint[3][] calldata sigs
                        ) external returns (uint256);
                        function updateValidatorState(uint256 validatorId, int256 amount) public;
                        function ownerOf(uint256 tokenId) public view returns (address);
                        function slash(bytes calldata slashingInfoList) external returns (uint256);
                        function validatorStake(uint256 validatorId) public view returns (uint256);
                        function epoch() public view returns (uint256);
                        function getRegistry() public view returns (address);
                        function withdrawalDelay() public view returns (uint256);
                        function delegatedAmount(uint256 validatorId) public view returns(uint256);
                        function decreaseValidatorDelegatedAmount(uint256 validatorId, uint256 amount) public;
                        function withdrawDelegatorsReward(uint256 validatorId) public returns(uint256);
                        function delegatorsReward(uint256 validatorId) public view returns(uint256);
                        function dethroneAndStake(
                            address auctionUser,
                            uint256 heimdallFee,
                            uint256 validatorId,
                            uint256 auctionAmount,
                            bool acceptDelegation,
                            bytes calldata signerPubkey
                        ) external;
                    }
                    pragma solidity 0.5.17;
                    // note this contract interface is only for stakeManager use
                    contract IValidatorShare {
                        function withdrawRewards() public;
                        function unstakeClaimTokens() public;
                        function getLiquidRewards(address user) public view returns (uint256);
                        
                        function owner() public view returns (address);
                        function restake() public returns(uint256, uint256);
                        function unlock() external;
                        function lock() external;
                        function drain(
                            address token,
                            address payable destination,
                            uint256 amount
                        ) external;
                        function slash(uint256 valPow, uint256 delegatedAmount, uint256 totalAmountToSlash) external returns (uint256);
                        function updateDelegation(bool delegation) external;
                        function migrateOut(address user, uint256 amount) external;
                        function migrateIn(address user, uint256 amount) external;
                    }
                    pragma solidity ^0.5.2;
                    contract Initializable {
                        bool inited = false;
                        modifier initializer() {
                            require(!inited, "already inited");
                            inited = true;
                            _;
                        }
                        function _disableInitializer() internal {
                            inited = true;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity 0.5.17;
                    interface IERC20Permit {
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                        function nonces(address owner) external view returns (uint256);
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    pragma solidity ^0.5.2;
                    import {IGovernance} from "./IGovernance.sol";
                    contract Governable {
                        IGovernance public governance;
                        constructor(address _governance) public {
                            governance = IGovernance(_governance);
                        }
                        modifier onlyGovernance() {
                            _assertGovernance();
                            _;
                        }
                        function _assertGovernance() private view {
                            require(
                                msg.sender == address(governance),
                                "Only governance contract is authorized"
                            );
                        }
                    }
                    pragma solidity ^0.5.2;
                    contract IWithdrawManager {
                        function createExitQueue(address token) external;
                        function verifyInclusion(
                            bytes calldata data,
                            uint8 offset,
                            bool verifyTxInclusion
                        ) external view returns (uint256 age);
                        function addExitToQueue(
                            address exitor,
                            address childToken,
                            address rootToken,
                            uint256 exitAmountOrTokenId,
                            bytes32 txHash,
                            bool isRegularExit,
                            uint256 priority
                        ) external;
                        function addInput(
                            uint256 exitId,
                            uint256 age,
                            address utxoOwner,
                            address token
                        ) external;
                        function challengeExit(
                            uint256 exitId,
                            uint256 inputId,
                            bytes calldata challengeData,
                            address adjudicatorPredicate
                        ) external;
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title ERC20 interface
                     * @dev see https://eips.ethereum.org/EIPS/eip-20
                     */
                    interface IERC20 {
                        function transfer(address to, uint256 value) external returns (bool);
                        function approve(address spender, uint256 value) external returns (bool);
                        function transferFrom(address from, address to, uint256 value) external returns (bool);
                        function totalSupply() external view returns (uint256);
                        function balanceOf(address who) external view returns (uint256);
                        function allowance(address owner, address spender) external view returns (uint256);
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title SafeMath
                     * @dev Unsigned math operations with safety checks that revert on error
                     */
                    library SafeMath {
                        /**
                         * @dev Multiplies two unsigned integers, reverts on overflow.
                         */
                        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                            // benefit is lost if 'b' is also tested.
                            // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                            if (a == 0) {
                                return 0;
                            }
                            uint256 c = a * b;
                            require(c / a == b);
                            return c;
                        }
                        /**
                         * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
                         */
                        function div(uint256 a, uint256 b) internal pure returns (uint256) {
                            // Solidity only automatically asserts when dividing by 0
                            require(b > 0);
                            uint256 c = a / b;
                            // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                            return c;
                        }
                        /**
                         * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                         */
                        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b <= a);
                            uint256 c = a - b;
                            return c;
                        }
                        /**
                         * @dev Adds two unsigned integers, reverts on overflow.
                         */
                        function add(uint256 a, uint256 b) internal pure returns (uint256) {
                            uint256 c = a + b;
                            require(c >= a);
                            return c;
                        }
                        /**
                         * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
                         * reverts when dividing by zero.
                         */
                        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b != 0);
                            return a % b;
                        }
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title Ownable
                     * @dev The Ownable contract has an owner address, and provides basic authorization control
                     * functions, this simplifies the implementation of "user permissions".
                     */
                    contract Ownable {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                         * account.
                         */
                        constructor () internal {
                            _owner = msg.sender;
                            emit OwnershipTransferred(address(0), _owner);
                        }
                        /**
                         * @return the address of the owner.
                         */
                        function owner() public view returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(isOwner());
                            _;
                        }
                        /**
                         * @return true if `msg.sender` is the owner of the contract.
                         */
                        function isOwner() public view returns (bool) {
                            return msg.sender == _owner;
                        }
                        /**
                         * @dev Allows the current owner to relinquish control of the contract.
                         * It will not be possible to call the functions with the `onlyOwner`
                         * modifier anymore.
                         * @notice Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                        /**
                         * @dev Allows the current owner to transfer control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function transferOwnership(address newOwner) public onlyOwner {
                            _transferOwnership(newOwner);
                        }
                        /**
                         * @dev Transfers control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function _transferOwnership(address newOwner) internal {
                            require(newOwner != address(0));
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    pragma solidity ^0.5.2;
                    contract Lockable {
                        bool public locked;
                        modifier onlyWhenUnlocked() {
                            _assertUnlocked();
                            _;
                        }
                        function _assertUnlocked() private view {
                            require(!locked, "locked");
                        }
                        function lock() public {
                            locked = true;
                        }
                        function unlock() public {
                            locked = false;
                        }
                    }
                    pragma solidity ^0.5.2;
                    interface IGovernance {
                        function update(address target, bytes calldata data) external;
                    }
                    

                    File 7 of 8: StakeManager
                    pragma solidity 0.5.17;
                    import {IERC20} from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                    import {Math} from "openzeppelin-solidity/contracts/math/Math.sol";
                    import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
                    import {ECVerify} from "../../common/lib/ECVerify.sol";
                    import {Merkle} from "../../common/lib/Merkle.sol";
                    import {GovernanceLockable} from "../../common/mixin/GovernanceLockable.sol";
                    import {DelegateProxyForwarder} from "../../common/misc/DelegateProxyForwarder.sol";
                    import {Registry} from "../../common/Registry.sol";
                    import {IStakeManager} from "./IStakeManager.sol";
                    import {IValidatorShare} from "../validatorShare/IValidatorShare.sol";
                    import {ValidatorShare} from "../validatorShare/ValidatorShare.sol";
                    import {StakingInfo} from "../StakingInfo.sol";
                    import {StakingNFT} from "./StakingNFT.sol";
                    import {ValidatorShareFactory} from "../validatorShare/ValidatorShareFactory.sol";
                    import {StakeManagerStorage} from "./StakeManagerStorage.sol";
                    import {StakeManagerStorageExtension} from "./StakeManagerStorageExtension.sol";
                    import {IGovernance} from "../../common/governance/IGovernance.sol";
                    import {Initializable} from "../../common/mixin/Initializable.sol";
                    import {StakeManagerExtension} from "./StakeManagerExtension.sol";
                    import {IPolygonMigration} from "../../common/misc/IPolygonMigration.sol";
                    contract StakeManager is
                        StakeManagerStorage,
                        Initializable,
                        IStakeManager,
                        DelegateProxyForwarder,
                        StakeManagerStorageExtension
                    {
                        using SafeMath for uint256;
                        using Merkle for bytes32;
                        struct UnsignedValidatorsContext {
                            uint256 unsignedValidatorIndex;
                            uint256 validatorIndex;
                            uint256[] unsignedValidators;
                            address[] validators;
                            uint256 totalValidators;
                        }
                        struct UnstakedValidatorsContext {
                            uint256 deactivationEpoch;
                            uint256[] deactivatedValidators;
                            uint256 validatorIndex;
                        }
                        modifier onlyStaker(uint256 validatorId) {
                            _assertStaker(validatorId);
                            _;
                        }
                        function _assertStaker(uint256 validatorId) private view {
                            require(NFTContract.ownerOf(validatorId) == msg.sender);
                        }
                        modifier onlyDelegation(uint256 validatorId) {
                            _assertDelegation(validatorId);
                            _;
                        }
                        function _assertDelegation(uint256 validatorId) private view {
                            require(validators[validatorId].contractAddress == msg.sender, "Invalid contract address");
                        }
                        constructor() public GovernanceLockable(address(0x0)) {
                            _disableInitializer();
                        }
                        function initialize(
                            address _registry,
                            address _rootchain,
                            address _token,
                            address _NFTContract,
                            address _stakingLogger,
                            address _validatorShareFactory,
                            address _governance,
                            address _owner,
                            address _extensionCode
                        ) external initializer {
                            require(isContract(_extensionCode), "auction impl incorrect");
                            extensionCode = _extensionCode;
                            governance = IGovernance(_governance);
                            registry = _registry;
                            rootChain = _rootchain;
                            token = IERC20(_token);
                            NFTContract = StakingNFT(_NFTContract);
                            logger = StakingInfo(_stakingLogger);
                            validatorShareFactory = ValidatorShareFactory(_validatorShareFactory);
                            _transferOwnership(_owner);
                            WITHDRAWAL_DELAY = (2**13); // unit: epoch
                            currentEpoch = 1;
                            dynasty = 886; // unit: epoch 50 days
                            CHECKPOINT_REWARD = 20188 * (10**18); // update via governance
                            minDeposit = (10**18); // in ERC20 token
                            minHeimdallFee = (10**18); // in ERC20 token
                            checkPointBlockInterval = 1024;
                            signerUpdateLimit = 100;
                            validatorThreshold = 7; //128
                            NFTCounter = 1;
                            auctionPeriod = (2**13) / 4; // 1 week in epochs
                            proposerBonus = 10; // 10 % of total rewards
                            delegationEnabled = true;
                        }
                        function reinitialize(
                            address _NFTContract,
                            address _stakingLogger,
                            address _validatorShareFactory,
                            address _extensionCode
                        ) external onlyGovernance {
                            require(isContract(_extensionCode));
                            eventsHub = address(0x0);
                            extensionCode = _extensionCode;
                            NFTContract = StakingNFT(_NFTContract);
                            logger = StakingInfo(_stakingLogger);
                            validatorShareFactory = ValidatorShareFactory(_validatorShareFactory);
                        }
                        function initializePOL(
                            address _tokenNew,
                            address _migration
                        ) external onlyGovernance {
                            tokenMatic = IERC20(token);
                            token = IERC20(_tokenNew);
                            migration = IPolygonMigration(_migration);
                            _convertMaticToPOL(tokenMatic.balanceOf(address(this)));
                        }
                        function isOwner() public view returns (bool) {
                            address _owner;
                            bytes32 position = keccak256("matic.network.proxy.owner");
                            assembly {
                                _owner := sload(position)
                            }
                            return msg.sender == _owner;
                        }
                        /**
                            Public View Methods
                         */
                        function getRegistry() public view returns (address) {
                            return registry;
                        }
                        /**
                            @dev Owner of validator slot NFT
                         */
                        function ownerOf(uint256 tokenId) public view returns (address) {
                            return NFTContract.ownerOf(tokenId);
                        }
                        function epoch() public view returns (uint256) {
                            return currentEpoch;
                        }
                        function withdrawalDelay() public view returns (uint256) {
                            return WITHDRAWAL_DELAY;
                        }
                        function validatorStake(uint256 validatorId) public view returns (uint256) {
                            return validators[validatorId].amount;
                        }
                        function getValidatorId(address user) public view returns (uint256) {
                            return NFTContract.tokenOfOwnerByIndex(user, 0);
                        }
                        function delegatedAmount(uint256 validatorId) public view returns (uint256) {
                            return validators[validatorId].delegatedAmount;
                        }
                        function delegatorsReward(uint256 validatorId) public view returns (uint256) {
                            uint256 _delegatorsReward;
                            if (validators[validatorId].deactivationEpoch == 0) {
                                (, _delegatorsReward) = _evaluateValidatorAndDelegationReward(validatorId);
                            }
                            return validators[validatorId].delegatorsReward.add(_delegatorsReward).sub(INITIALIZED_AMOUNT);
                        }
                        function validatorReward(uint256 validatorId) public view returns (uint256) {
                            uint256 _validatorReward;
                            if (validators[validatorId].deactivationEpoch == 0) {
                                (_validatorReward, ) = _evaluateValidatorAndDelegationReward(validatorId);
                            }
                            return validators[validatorId].reward.add(_validatorReward).sub(INITIALIZED_AMOUNT);
                        }
                        function currentValidatorSetSize() public view returns (uint256) {
                            return validatorState.stakerCount;
                        }
                        function currentValidatorSetTotalStake() public view returns (uint256) {
                            return validatorState.amount;
                        }
                        function getValidatorContract(uint256 validatorId) public view returns (address) {
                            return validators[validatorId].contractAddress;
                        }
                        function isValidator(uint256 validatorId) public view returns (bool) {
                            return
                                _isValidator(
                                    validators[validatorId].status,
                                    validators[validatorId].amount,
                                    validators[validatorId].deactivationEpoch,
                                    currentEpoch
                                );
                        }
                        /**
                            Governance Methods
                         */
                        function setDelegationEnabled(bool enabled) public onlyGovernance {
                            delegationEnabled = enabled;
                        }
                        // Housekeeping function. @todo remove later
                        function forceUnstake(uint256 validatorId) external onlyGovernance {
                            _unstake(validatorId, currentEpoch, false);
                        }
                        function forceUnstakePOL(uint256 validatorId) external onlyGovernance {
                            _unstake(validatorId, currentEpoch, true);
                        }
                        function setCurrentEpoch(uint256 _currentEpoch) external onlyGovernance {
                            currentEpoch = _currentEpoch;
                        }
                        function setStakingToken(address _token) public onlyGovernance {
                            require(_token != address(0x0));
                            token = IERC20(_token);
                        }
                        /**
                         * @dev Change the number of validators required to allow a passed header root
                         */
                        function updateValidatorThreshold(uint256 newThreshold) public onlyGovernance {
                            require(newThreshold != 0);
                            logger.logThresholdChange(newThreshold, validatorThreshold);
                            validatorThreshold = newThreshold;
                        }
                        function updateCheckPointBlockInterval(uint256 _blocks) public onlyGovernance {
                            require(_blocks != 0);
                            checkPointBlockInterval = _blocks;
                        }
                        function updateCheckpointReward(uint256 newReward) public onlyGovernance {
                            require(newReward != 0);
                            logger.logRewardUpdate(newReward, CHECKPOINT_REWARD);
                            CHECKPOINT_REWARD = newReward;
                        }
                        function updateCheckpointRewardParams(
                            uint256 _rewardDecreasePerCheckpoint,
                            uint256 _maxRewardedCheckpoints,
                            uint256 _checkpointRewardDelta
                        ) public onlyGovernance {
                            delegatedFwd(
                                extensionCode,
                                abi.encodeWithSelector(
                                    StakeManagerExtension(extensionCode).updateCheckpointRewardParams.selector,
                                    _rewardDecreasePerCheckpoint,
                                    _maxRewardedCheckpoints,
                                    _checkpointRewardDelta
                                )
                            );
                        }
                        // New implementation upgrade
                        function migrateValidatorsData(uint256 validatorIdFrom, uint256 validatorIdTo) public onlyOwner {
                            delegatedFwd(
                                extensionCode,
                                abi.encodeWithSelector(
                                    StakeManagerExtension(extensionCode).migrateValidatorsData.selector,
                                    validatorIdFrom,
                                    validatorIdTo
                                )
                            );
                        }
                        function insertSigners(address[] memory _signers) public onlyOwner {
                            signers = _signers;
                        }
                        /**
                            @dev Users must exit before this update or all funds may get lost
                         */
                        function updateValidatorContractAddress(uint256 validatorId, address newContractAddress) public onlyGovernance {
                            require(IValidatorShare(newContractAddress).owner() == address(this));
                            validators[validatorId].contractAddress = newContractAddress;
                        }
                        function updateDynastyValue(uint256 newDynasty) public onlyGovernance {
                            require(newDynasty > 0);
                            logger.logDynastyValueChange(newDynasty, dynasty);
                            dynasty = newDynasty;
                            WITHDRAWAL_DELAY = newDynasty;
                            auctionPeriod = newDynasty.div(4);
                            replacementCoolDown = currentEpoch.add(auctionPeriod);
                        }
                        // Housekeeping function. @todo remove later
                        function stopAuctions(uint256 forNCheckpoints) public onlyGovernance {
                            replacementCoolDown = currentEpoch.add(forNCheckpoints);
                        }
                        function updateProposerBonus(uint256 newProposerBonus) public onlyGovernance {
                            logger.logProposerBonusChange(newProposerBonus, proposerBonus);
                            require(newProposerBonus <= MAX_PROPOSER_BONUS, "too big");
                            proposerBonus = newProposerBonus;
                        }
                        function updateSignerUpdateLimit(uint256 _limit) public onlyGovernance {
                            signerUpdateLimit = _limit;
                        }
                        function updateMinAmounts(uint256 _minDeposit, uint256 _minHeimdallFee) public onlyGovernance {
                            minDeposit = _minDeposit;
                            minHeimdallFee = _minHeimdallFee;
                        }
                        /**
                            Public Methods
                         */
                        function topUpForFee(address user, uint256 heimdallFee) public onlyWhenUnlocked {
                            _transferAndTopUp(user, msg.sender, heimdallFee, 0, true);
                        }
                        function claimFee(uint256 accumFeeAmount, uint256 index, bytes memory proof) public {
                            require(keccak256(abi.encode(msg.sender, accumFeeAmount)).checkMembership(index, accountStateRoot, proof), "Wrong acc proof");
                            uint256 withdrawAmount = accumFeeAmount.sub(userFeeExit[msg.sender]);
                            totalHeimdallFee = totalHeimdallFee.sub(withdrawAmount);
                            logger.logClaimFee(msg.sender, withdrawAmount);
                            userFeeExit[msg.sender] = accumFeeAmount;
                            _transferToken(msg.sender, withdrawAmount, true);
                        }
                        function totalStakedFor(address user) external view returns (uint256) {
                            if (user == address(0x0) || NFTContract.balanceOf(user) == 0) {
                                return 0;
                            }
                            return validators[NFTContract.tokenOfOwnerByIndex(user, 0)].amount;
                        }
                        function startAuction(
                            uint256 validatorId,
                            uint256 amount,
                            bool _acceptDelegation,
                            bytes calldata _signerPubkey
                        ) external onlyWhenUnlocked {
                            delegatedFwd(
                                extensionCode,
                                abi.encodeWithSelector(
                                    StakeManagerExtension(extensionCode).startAuction.selector,
                                    validatorId,
                                    amount,
                                    _acceptDelegation,
                                    _signerPubkey
                                )
                            );
                        }
                        function confirmAuctionBid(
                            uint256 validatorId,
                            uint256 heimdallFee /** for new validator */
                        ) external onlyWhenUnlocked {
                            delegatedFwd(
                                extensionCode,
                                abi.encodeWithSelector(
                                    StakeManagerExtension(extensionCode).confirmAuctionBid.selector,
                                    validatorId,
                                    heimdallFee,
                                    address(this)
                                )
                            );
                        }
                        function dethroneAndStake(
                            address auctionUser,
                            uint256 heimdallFee,
                            uint256 validatorId,
                            uint256 auctionAmount,
                            bool acceptDelegation,
                            bytes calldata signerPubkey
                        ) external {
                            require(msg.sender == address(this), "not allowed");
                            // dethrone
                            _transferAndTopUp(auctionUser, auctionUser, heimdallFee, 0, true);
                            _unstake(validatorId, currentEpoch, true);
                            uint256 newValidatorId = _stakeFor(auctionUser, auctionAmount, acceptDelegation, signerPubkey);
                            logger.logConfirmAuction(newValidatorId, validatorId, auctionAmount);
                        }
                        function unstake(uint256 validatorId) external onlyStaker(validatorId) {
                            _unstakeValidator(validatorId, false);
                        }
                        function unstakePOL(uint256 validatorId) external onlyStaker(validatorId) {
                            _unstakeValidator(validatorId, true);
                        }
                        function _unstakeValidator(uint256 validatorId, bool pol) internal {
                            require(validatorAuction[validatorId].amount == 0);
                            Status status = validators[validatorId].status;
                            require(
                                validators[validatorId].activationEpoch > 0 &&
                                    validators[validatorId].deactivationEpoch == 0 &&
                                    (status == Status.Active || status == Status.Locked)
                            );
                            uint256 exitEpoch = currentEpoch.add(1); // notice period
                            _unstake(validatorId, exitEpoch, pol);
                        }
                        function transferFunds(uint256 validatorId, uint256 amount, address delegator) external returns (bool) {
                            return _transferFunds(validatorId, amount, delegator, false);
                        }
                        function transferFundsPOL(uint256 validatorId, uint256 amount, address delegator) external returns (bool) {
                            return _transferFunds(validatorId, amount, delegator, true);
                        }
                        function _transferFunds(uint256 validatorId, uint256 amount, address delegator, bool pol) internal returns (bool) {
                            require(validators[validatorId].contractAddress == msg.sender || Registry(registry).getSlashingManagerAddress() == msg.sender, "not allowed");
                            if (!pol) _convertPOLToMatic(amount);
                            IERC20 token_ = _getToken(pol);
                            return token_.transfer(delegator, amount);
                        }
                        function delegationDeposit(uint256 validatorId, uint256 amount, address delegator) external onlyDelegation(validatorId) returns (bool) {
                            return _delegationDeposit(amount, delegator, false);
                        }
                        function delegationDepositPOL(uint256 validatorId, uint256 amount, address delegator) external onlyDelegation(validatorId) returns (bool) {
                            return _delegationDeposit(amount, delegator, true);
                        }
                        function _delegationDeposit(uint256 amount, address delegator, bool pol) internal returns (bool) {
                            IERC20 token_ = _getToken(pol);
                            bool result = token_.transferFrom(delegator, address(this), amount);
                            if (!pol) _convertMaticToPOL(amount);
                            return result;
                        }
                        function stakeFor(address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey) public onlyWhenUnlocked {
                            _stakeFor(user, amount, heimdallFee, acceptDelegation, signerPubkey, false);
                        }
                        function stakeForPOL(address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey) public onlyWhenUnlocked {
                            _stakeFor(user, amount, heimdallFee, acceptDelegation, signerPubkey, true);
                        }
                        function _stakeFor(address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey, bool pol) internal {
                            require(currentValidatorSetSize() < validatorThreshold, "no more slots");
                            require(amount >= minDeposit, "not enough deposit");
                            _transferAndTopUp(user, msg.sender, heimdallFee, amount, pol);
                            _stakeFor(user, amount, acceptDelegation, signerPubkey);
                        }
                        function unstakeClaim(uint256 validatorId) public onlyStaker(validatorId) {
                            _unstakeClaim(validatorId, false);
                        }
                        function unstakeClaimPOL(uint256 validatorId) public onlyStaker(validatorId) {
                            _unstakeClaim(validatorId, true);
                        }
                        function _unstakeClaim(uint256 validatorId, bool pol) internal {
                            uint256 deactivationEpoch = validators[validatorId].deactivationEpoch;
                            // can only claim stake back after WITHDRAWAL_DELAY
                            require(
                                deactivationEpoch > 0 &&
                                    deactivationEpoch.add(WITHDRAWAL_DELAY) <= currentEpoch &&
                                    validators[validatorId].status != Status.Unstaked
                            );
                            uint256 amount = validators[validatorId].amount;
                            uint256 newTotalStaked = totalStaked.sub(amount);
                            totalStaked = newTotalStaked;
                            // claim last checkpoint reward if it was signed by validator
                            _liquidateRewards(validatorId, msg.sender, pol);
                            NFTContract.burn(validatorId);
                            validators[validatorId].amount = 0;
                            validators[validatorId].jailTime = 0;
                            validators[validatorId].signer = address(0);
                            signerToValidator[validators[validatorId].signer] = INCORRECT_VALIDATOR_ID;
                            validators[validatorId].status = Status.Unstaked;
                            _transferToken(msg.sender, amount, pol);
                            logger.logUnstaked(msg.sender, validatorId, amount, newTotalStaked);
                        }
                        function restake(uint256 validatorId, uint256 amount, bool stakeRewards) public onlyWhenUnlocked onlyStaker(validatorId) {
                            _restake(validatorId, amount, stakeRewards, false);
                        }
                        function restakePOL(uint256 validatorId, uint256 amount, bool stakeRewards) public onlyWhenUnlocked onlyStaker(validatorId) {
                            _restake(validatorId, amount, stakeRewards, true);
                        }
                        function _restake(uint256 validatorId, uint256 amount, bool stakeRewards, bool pol) internal {
                            require(validators[validatorId].deactivationEpoch == 0, "No restaking");
                            if (amount > 0) {
                                _transferTokenFrom(msg.sender, address(this), amount, pol);
                            }
                            _updateRewards(validatorId);
                            if (stakeRewards) {
                                amount = amount.add(validators[validatorId].reward).sub(INITIALIZED_AMOUNT);
                                validators[validatorId].reward = INITIALIZED_AMOUNT;
                            }
                            uint256 newTotalStaked = totalStaked.add(amount);
                            totalStaked = newTotalStaked;
                            validators[validatorId].amount = validators[validatorId].amount.add(amount);
                            updateTimeline(int256(amount), 0, 0);
                            logger.logStakeUpdate(validatorId);
                            logger.logRestaked(validatorId, validators[validatorId].amount, newTotalStaked);
                        }
                        function withdrawRewards(uint256 validatorId) public onlyStaker(validatorId) {
                            _withdrawRewards(validatorId, false);
                        }
                        function withdrawRewardsPOL(uint256 validatorId) public onlyStaker(validatorId) {
                            _withdrawRewards(validatorId, true);
                        }
                        function _withdrawRewards(uint256 validatorId, bool pol) internal {
                            _updateRewards(validatorId);
                            _liquidateRewards(validatorId, msg.sender, pol);
                        }
                        function migrateDelegation(
                            uint256 fromValidatorId,
                            uint256 toValidatorId,
                            uint256 amount
                        ) public {
                            // allow to move to any non-foundation node
                            require(toValidatorId > 7, "Invalid migration");
                            IValidatorShare(validators[fromValidatorId].contractAddress).migrateOut(msg.sender, amount);
                            IValidatorShare(validators[toValidatorId].contractAddress).migrateIn(msg.sender, amount);
                        }
                        function updateValidatorState(uint256 validatorId, int256 amount) public onlyDelegation(validatorId) {
                            if (amount > 0) {
                                // deposit during shares purchase
                                require(delegationEnabled, "Delegation is disabled");
                            }
                            uint256 deactivationEpoch = validators[validatorId].deactivationEpoch;
                            if (deactivationEpoch == 0) { // modify timeline only if validator didn't unstake
                                updateTimeline(amount, 0, 0);
                            } else if (deactivationEpoch > currentEpoch) { // validator just unstaked, need to wait till next checkpoint
                                revert("unstaking");
                            }
                            
                            if (amount >= 0) {
                                increaseValidatorDelegatedAmount(validatorId, uint256(amount));
                            } else {
                                decreaseValidatorDelegatedAmount(validatorId, uint256(amount * -1));
                            }
                        }
                        function increaseValidatorDelegatedAmount(uint256 validatorId, uint256 amount) private {
                            validators[validatorId].delegatedAmount = validators[validatorId].delegatedAmount.add(amount);
                        }
                        function decreaseValidatorDelegatedAmount(uint256 validatorId, uint256 amount) public onlyDelegation(validatorId) {
                            validators[validatorId].delegatedAmount = validators[validatorId].delegatedAmount.sub(amount);
                        }
                        function updateSigner(uint256 validatorId, bytes memory signerPubkey) public onlyStaker(validatorId) {
                            address signer = _getAndAssertSigner(signerPubkey);
                            uint256 _currentEpoch = currentEpoch;
                            require(_currentEpoch >= latestSignerUpdateEpoch[validatorId].add(signerUpdateLimit), "Not allowed");
                            address currentSigner = validators[validatorId].signer;
                            // update signer event
                            logger.logSignerChange(validatorId, currentSigner, signer, signerPubkey);
                            
                            if (validators[validatorId].deactivationEpoch == 0) { 
                                // didn't unstake, swap signer in the list
                                _removeSigner(currentSigner);
                                _insertSigner(signer);
                            }
                            signerToValidator[currentSigner] = INCORRECT_VALIDATOR_ID;
                            signerToValidator[signer] = validatorId;
                            validators[validatorId].signer = signer;
                            // reset update time to current time
                            latestSignerUpdateEpoch[validatorId] = _currentEpoch;
                        }
                        function checkSignatures(
                            uint256 blockInterval,
                            bytes32 voteHash,
                            bytes32 stateRoot,
                            address proposer,
                            uint256[3][] calldata sigs
                        ) external onlyRootChain returns (uint256) {
                            uint256 _currentEpoch = currentEpoch;
                            uint256 signedStakePower;
                            address lastAdd;
                            uint256 totalStakers = validatorState.stakerCount;
                            UnsignedValidatorsContext memory unsignedCtx;
                            unsignedCtx.unsignedValidators = new uint256[](signers.length + totalStakers);
                            unsignedCtx.validators = signers;
                            unsignedCtx.validatorIndex = 0;
                            unsignedCtx.totalValidators = signers.length;
                            UnstakedValidatorsContext memory unstakeCtx;
                            unstakeCtx.deactivatedValidators = new uint256[](signers.length + totalStakers);
                            for (uint256 i = 0; i < sigs.length; ++i) {
                                address signer = ECVerify.ecrecovery(voteHash, sigs[i]);
                                if (signer == lastAdd) {
                                    // if signer signs twice, just skip this signature
                                    continue;
                                }
                                if (signer < lastAdd) {
                                    // if signatures are out of order - break out, it is not possible to keep track of unsigned validators
                                    break;
                                }
                                uint256 validatorId = signerToValidator[signer];
                                uint256 amount = validators[validatorId].amount;
                                Status status = validators[validatorId].status;
                                unstakeCtx.deactivationEpoch = validators[validatorId].deactivationEpoch;
                                if (_isValidator(status, amount, unstakeCtx.deactivationEpoch, _currentEpoch)) {
                                    lastAdd = signer;
                                    signedStakePower = signedStakePower.add(validators[validatorId].delegatedAmount).add(amount);
                                    if (unstakeCtx.deactivationEpoch != 0) {
                                        // this validator not a part of signers list anymore
                                        unstakeCtx.deactivatedValidators[unstakeCtx.validatorIndex] = validatorId;
                                        unstakeCtx.validatorIndex++;
                                    } else {
                                        unsignedCtx = _fillUnsignedValidators(unsignedCtx, signer);
                                    }
                                } else if (status == Status.Locked) {
                                    // TODO fix double unsignedValidators appearance
                                    // make sure that jailed validator doesn't get his rewards too
                                    unsignedCtx.unsignedValidators[unsignedCtx.unsignedValidatorIndex] = validatorId;
                                    unsignedCtx.unsignedValidatorIndex++;
                                    unsignedCtx.validatorIndex++;
                                }
                            }
                            // find the rest of validators without signature
                            unsignedCtx = _fillUnsignedValidators(unsignedCtx, address(0));
                            return
                                _increaseRewardAndAssertConsensus(
                                    blockInterval,
                                    proposer,
                                    signedStakePower,
                                    stateRoot,
                                    unsignedCtx.unsignedValidators,
                                    unsignedCtx.unsignedValidatorIndex,
                                    unstakeCtx.deactivatedValidators,
                                    unstakeCtx.validatorIndex
                                );
                        }
                        function updateCommissionRate(uint256 validatorId, uint256 newCommissionRate) external onlyStaker(validatorId) {
                            _updateRewards(validatorId);
                            delegatedFwd(
                                extensionCode,
                                abi.encodeWithSelector(
                                    StakeManagerExtension(extensionCode).updateCommissionRate.selector,
                                    validatorId,
                                    newCommissionRate
                                )
                            );
                        }
                        function withdrawDelegatorsReward(uint256 validatorId) public onlyDelegation(validatorId) returns (uint256) {
                            _updateRewards(validatorId);
                            uint256 totalReward = validators[validatorId].delegatorsReward.sub(INITIALIZED_AMOUNT);
                            validators[validatorId].delegatorsReward = INITIALIZED_AMOUNT;
                            return totalReward;
                        }
                        function slash(bytes calldata _slashingInfoList) external returns (uint256) {
                            revert();
                        }
                        function unjail(uint256 validatorId) public onlyStaker(validatorId) {
                            require(validators[validatorId].status == Status.Locked, "Not jailed");
                            require(validators[validatorId].deactivationEpoch == 0, "Already unstaking");
                            uint256 _currentEpoch = currentEpoch;
                            require(validators[validatorId].jailTime <= _currentEpoch, "Incomplete jail period");
                            uint256 amount = validators[validatorId].amount;
                            require(amount >= minDeposit);
                            address delegationContract = validators[validatorId].contractAddress;
                            if (delegationContract != address(0x0)) {
                                IValidatorShare(delegationContract).unlock();
                            }
                            // undo timeline so that validator is normal validator
                            updateTimeline(int256(amount.add(validators[validatorId].delegatedAmount)), 1, 0);
                            validators[validatorId].status = Status.Active;
                            address signer = validators[validatorId].signer;
                            logger.logUnjailed(validatorId, signer);
                        }
                        function updateTimeline(
                            int256 amount,
                            int256 stakerCount,
                            uint256 targetEpoch
                        ) internal {
                            if (targetEpoch == 0) {
                                // update total stake and validator count
                                if (amount > 0) {
                                    validatorState.amount = validatorState.amount.add(uint256(amount));
                                } else if (amount < 0) {
                                    validatorState.amount = validatorState.amount.sub(uint256(amount * -1));
                                }
                                if (stakerCount > 0) {
                                    validatorState.stakerCount = validatorState.stakerCount.add(uint256(stakerCount));
                                } else if (stakerCount < 0) {
                                    validatorState.stakerCount = validatorState.stakerCount.sub(uint256(stakerCount * -1));
                                }
                            } else {
                                validatorStateChanges[targetEpoch].amount += amount;
                                validatorStateChanges[targetEpoch].stakerCount += stakerCount;
                            }
                        }
                        function updateValidatorDelegation(bool delegation) external {
                            uint256 validatorId = signerToValidator[msg.sender];
                            require(
                                _isValidator(
                                    validators[validatorId].status,
                                    validators[validatorId].amount,
                                    validators[validatorId].deactivationEpoch,
                                    currentEpoch
                                ),
                                "not validator"
                            );
                            address contractAddr = validators[validatorId].contractAddress;
                            require(contractAddr != address(0x0), "Delegation is disabled");
                            IValidatorShare(contractAddr).updateDelegation(delegation);
                        }
                        /**
                            Private Methods
                         */
                        function _getAndAssertSigner(bytes memory pub) private view returns (address) {
                            require(pub.length == 64, "not pub");
                            address signer = address(uint160(uint256(keccak256(pub))));
                            require(signer != address(0) && signerToValidator[signer] == 0, "Invalid signer");
                            return signer;
                        }
                        function _isValidator(
                            Status status,
                            uint256 amount,
                            uint256 deactivationEpoch,
                            uint256 _currentEpoch
                        ) private pure returns (bool) {
                            return (amount > 0 && (deactivationEpoch == 0 || deactivationEpoch > _currentEpoch) && status == Status.Active);
                        }
                        function _fillUnsignedValidators(UnsignedValidatorsContext memory context, address signer)
                            private
                            view
                            returns(UnsignedValidatorsContext memory)
                        {
                            while (context.validatorIndex < context.totalValidators && context.validators[context.validatorIndex] != signer) {
                                context.unsignedValidators[context.unsignedValidatorIndex] = signerToValidator[context.validators[context.validatorIndex]];
                                context.unsignedValidatorIndex++;
                                context.validatorIndex++;
                            }
                            context.validatorIndex++;
                            return context;
                        }
                        function _calculateCheckpointReward(
                            uint256 blockInterval,
                            uint256 signedStakePower,
                            uint256 currentTotalStake
                        ) internal returns (uint256) {
                            // checkpoint rewards are based on BlockInterval multiplied on `CHECKPOINT_REWARD`
                            // for bigger checkpoints reward is reduced by rewardDecreasePerCheckpoint for each subsequent interval
                            // for smaller checkpoints
                            // if interval is 50% of checkPointBlockInterval then reward R is half of `CHECKPOINT_REWARD`
                            // and then stakePower is 90% of currentValidatorSetTotalStake then final reward is 90% of R
                            uint256 targetBlockInterval = checkPointBlockInterval;
                            uint256 ckpReward = CHECKPOINT_REWARD;
                            uint256 fullIntervals = Math.min(blockInterval / targetBlockInterval, maxRewardedCheckpoints);
                            // only apply to full checkpoints
                            if (fullIntervals > 0 && fullIntervals != prevBlockInterval) {
                                if (prevBlockInterval != 0) {
                                    // give more reward for faster and less for slower checkpoint
                                    uint256 delta = (ckpReward * checkpointRewardDelta / CHK_REWARD_PRECISION);
                                    
                                    if (prevBlockInterval > fullIntervals) {
                                        // checkpoint is faster
                                        ckpReward += delta;
                                    } else {
                                        ckpReward -= delta;
                                    }
                                }
                                
                                prevBlockInterval = fullIntervals;
                            }
                            uint256 reward;
                            if (blockInterval > targetBlockInterval) {
                                // count how many full intervals
                                uint256 _rewardDecreasePerCheckpoint = rewardDecreasePerCheckpoint;
                                // calculate reward for full intervals
                                reward = ckpReward.mul(fullIntervals).sub(ckpReward.mul(((fullIntervals - 1) * fullIntervals / 2).mul(_rewardDecreasePerCheckpoint)).div(CHK_REWARD_PRECISION));
                                // adjust block interval, in case last interval is not full
                                blockInterval = blockInterval.sub(fullIntervals.mul(targetBlockInterval));
                                // adjust checkpoint reward by the amount it suppose to decrease
                                ckpReward = ckpReward.sub(ckpReward.mul(fullIntervals).mul(_rewardDecreasePerCheckpoint).div(CHK_REWARD_PRECISION));
                            }
                            // give proportionally less for the rest
                            reward = reward.add(blockInterval.mul(ckpReward).div(targetBlockInterval));
                            reward = reward.mul(signedStakePower).div(currentTotalStake);
                            return reward;
                        }
                        function _increaseRewardAndAssertConsensus(
                            uint256 blockInterval,
                            address proposer,
                            uint256 signedStakePower,
                            bytes32 stateRoot,
                            uint256[] memory unsignedValidators,
                            uint256 totalUnsignedValidators,
                            uint256[] memory deactivatedValidators,
                            uint256 totalDeactivatedValidators
                        ) private returns (uint256) {
                            uint256 currentTotalStake = validatorState.amount;
                            require(signedStakePower >= currentTotalStake.mul(2).div(3).add(1), "2/3+1 non-majority!");
                            uint256 reward = _calculateCheckpointReward(blockInterval, signedStakePower, currentTotalStake);
                            uint256 _proposerBonus = reward.mul(proposerBonus).div(MAX_PROPOSER_BONUS);
                            uint256 proposerId = signerToValidator[proposer];
                            Validator storage _proposer = validators[proposerId];
                            _proposer.reward = _proposer.reward.add(_proposerBonus);
                            // update stateMerkleTree root for accounts balance on heimdall chain
                            accountStateRoot = stateRoot;
                            uint256 newRewardPerStake =
                                rewardPerStake.add(reward.sub(_proposerBonus).mul(REWARD_PRECISION).div(signedStakePower));
                            // evaluate rewards for validator who did't sign and set latest reward per stake to new value to avoid them from getting new rewards.
                            _updateValidatorsRewards(unsignedValidators, totalUnsignedValidators, newRewardPerStake);
                            // distribute rewards between signed validators
                            rewardPerStake = newRewardPerStake;
                            // evaluate rewards for unstaked validators to ensure they get the reward for signing during their deactivationEpoch
                            _updateValidatorsRewards(deactivatedValidators, totalDeactivatedValidators, newRewardPerStake);
                            _finalizeCommit();
                            return reward;
                        }
                        function _updateValidatorsRewards(
                            uint256[] memory unsignedValidators,
                            uint256 totalUnsignedValidators,
                            uint256 newRewardPerStake
                        ) private {
                            uint256 currentRewardPerStake = rewardPerStake;
                            for (uint256 i = 0; i < totalUnsignedValidators; ++i) {
                                _updateRewardsAndCommit(unsignedValidators[i], currentRewardPerStake, newRewardPerStake);
                            }
                        }
                        function _updateRewardsAndCommit(
                            uint256 validatorId,
                            uint256 currentRewardPerStake,
                            uint256 newRewardPerStake
                        ) private {
                            uint256 deactivationEpoch = validators[validatorId].deactivationEpoch;
                            if (deactivationEpoch != 0 && currentEpoch >= deactivationEpoch) {
                                return;
                            }
                            uint256 initialRewardPerStake = validators[validatorId].initialRewardPerStake;
                            // attempt to save gas in case if rewards were updated previously
                            if (initialRewardPerStake < currentRewardPerStake) {
                                uint256 validatorsStake = validators[validatorId].amount;
                                uint256 delegatedAmount = validators[validatorId].delegatedAmount;
                                if (delegatedAmount > 0) {
                                    uint256 combinedStakePower = validatorsStake.add(delegatedAmount);
                                    _increaseValidatorRewardWithDelegation(
                                        validatorId,
                                        validatorsStake,
                                        delegatedAmount,
                                        _getEligibleValidatorReward(
                                            validatorId,
                                            combinedStakePower,
                                            currentRewardPerStake,
                                            initialRewardPerStake
                                        )
                                    );
                                } else {
                                    _increaseValidatorReward(
                                        validatorId,
                                        _getEligibleValidatorReward(
                                            validatorId,
                                            validatorsStake,
                                            currentRewardPerStake,
                                            initialRewardPerStake
                                        )
                                    );
                                }
                            }
                            if (newRewardPerStake > initialRewardPerStake) {
                                validators[validatorId].initialRewardPerStake = newRewardPerStake;
                            }
                        }
                        function _updateRewards(uint256 validatorId) private {
                            _updateRewardsAndCommit(validatorId, rewardPerStake, rewardPerStake);
                        }
                        function _getEligibleValidatorReward(
                            uint256 validatorId,
                            uint256 validatorStakePower,
                            uint256 currentRewardPerStake,
                            uint256 initialRewardPerStake
                        ) private pure returns (uint256) {
                            uint256 eligibleReward = currentRewardPerStake - initialRewardPerStake;
                            return eligibleReward.mul(validatorStakePower).div(REWARD_PRECISION);
                        }
                        function _increaseValidatorReward(uint256 validatorId, uint256 reward) private {
                            if (reward > 0) {
                                validators[validatorId].reward = validators[validatorId].reward.add(reward);
                            }
                        }
                        function _increaseValidatorRewardWithDelegation(
                            uint256 validatorId,
                            uint256 validatorsStake,
                            uint256 delegatedAmount,
                            uint256 reward
                        ) private {
                            uint256 combinedStakePower = delegatedAmount.add(validatorsStake);
                            (uint256 validatorReward, uint256 delegatorsReward) =
                                _getValidatorAndDelegationReward(validatorId, validatorsStake, reward, combinedStakePower);
                            if (delegatorsReward > 0) {
                                validators[validatorId].delegatorsReward = validators[validatorId].delegatorsReward.add(delegatorsReward);
                            }
                            if (validatorReward > 0) {
                                validators[validatorId].reward = validators[validatorId].reward.add(validatorReward);
                            }
                        }
                        function _getValidatorAndDelegationReward(
                            uint256 validatorId,
                            uint256 validatorsStake,
                            uint256 reward,
                            uint256 combinedStakePower
                        ) internal view returns (uint256, uint256) {
                            if (combinedStakePower == 0) {
                                return (0, 0);
                            }
                            uint256 validatorReward = validatorsStake.mul(reward).div(combinedStakePower);
                            // add validator commission from delegation reward
                            uint256 commissionRate = validators[validatorId].commissionRate;
                            if (commissionRate > 0) {
                                validatorReward = validatorReward.add(
                                    reward.sub(validatorReward).mul(commissionRate).div(MAX_COMMISION_RATE)
                                );
                            }
                            uint256 delegatorsReward = reward.sub(validatorReward);
                            return (validatorReward, delegatorsReward);
                        }
                        function _evaluateValidatorAndDelegationReward(uint256 validatorId)
                            private
                            view
                            returns (uint256 validatorReward, uint256 delegatorsReward)
                        {
                            uint256 validatorsStake = validators[validatorId].amount;
                            uint256 combinedStakePower = validatorsStake.add(validators[validatorId].delegatedAmount);
                            uint256 eligibleReward = rewardPerStake - validators[validatorId].initialRewardPerStake;
                            return
                                _getValidatorAndDelegationReward(
                                    validatorId,
                                    validatorsStake,
                                    eligibleReward.mul(combinedStakePower).div(REWARD_PRECISION),
                                    combinedStakePower
                                );
                        }
                        function _stakeFor(
                            address user,
                            uint256 amount,
                            bool acceptDelegation,
                            bytes memory signerPubkey
                        ) internal returns (uint256) {
                            address signer = _getAndAssertSigner(signerPubkey);
                            uint256 _currentEpoch = currentEpoch;
                            uint256 validatorId = NFTCounter;
                            StakingInfo _logger = logger;
                            uint256 newTotalStaked = totalStaked.add(amount);
                            totalStaked = newTotalStaked;
                            validators[validatorId] = Validator({
                                reward: INITIALIZED_AMOUNT,
                                amount: amount,
                                activationEpoch: _currentEpoch,
                                deactivationEpoch: 0,
                                jailTime: 0,
                                signer: signer,
                                contractAddress: acceptDelegation
                                    ? validatorShareFactory.create(validatorId, address(_logger), registry)
                                    : address(0x0),
                                status: Status.Active,
                                commissionRate: 0,
                                lastCommissionUpdate: 0,
                                delegatorsReward: INITIALIZED_AMOUNT,
                                delegatedAmount: 0,
                                initialRewardPerStake: rewardPerStake
                            });
                            latestSignerUpdateEpoch[validatorId] = _currentEpoch;
                            NFTContract.mint(user, validatorId);
                            signerToValidator[signer] = validatorId;
                            updateTimeline(int256(amount), 1, 0);
                            // no Auctions for 1 dynasty
                            validatorAuction[validatorId].startEpoch = _currentEpoch;
                            _logger.logStaked(signer, signerPubkey, validatorId, _currentEpoch, amount, newTotalStaked);
                            NFTCounter = validatorId.add(1);
                            _insertSigner(signer);
                            return validatorId;
                        }
                        function _unstake(uint256 validatorId, uint256 exitEpoch, bool pol) internal {
                            require(validators[validatorId].deactivationEpoch == 0);
                            _updateRewards(validatorId);
                            uint256 amount = validators[validatorId].amount;
                            address validator = ownerOf(validatorId);
                            validators[validatorId].deactivationEpoch = exitEpoch;
                            // unbond all delegators in future
                            int256 delegationAmount = int256(validators[validatorId].delegatedAmount);
                            address delegationContract = validators[validatorId].contractAddress;
                            if (delegationContract != address(0)) {
                                IValidatorShare(delegationContract).lock();
                            }
                            _removeSigner(validators[validatorId].signer);
                            _liquidateRewards(validatorId, validator, pol);
                            uint256 targetEpoch = exitEpoch <= currentEpoch ? 0 : exitEpoch;
                            updateTimeline(-(int256(amount) + delegationAmount), -1, targetEpoch);
                            logger.logUnstakeInit(validator, validatorId, exitEpoch, amount);
                        }
                        function _finalizeCommit() internal {
                            uint256 _currentEpoch = currentEpoch;
                            uint256 nextEpoch = _currentEpoch.add(1);
                            StateChange memory changes = validatorStateChanges[nextEpoch];
                            updateTimeline(changes.amount, changes.stakerCount, 0);
                            delete validatorStateChanges[_currentEpoch];
                            currentEpoch = nextEpoch;
                        }
                        function _liquidateRewards(uint256 validatorId, address validatorUser, bool pol) private {
                            uint256 reward = validators[validatorId].reward.sub(INITIALIZED_AMOUNT);
                            totalRewardsLiquidated = totalRewardsLiquidated.add(reward);
                            validators[validatorId].reward = INITIALIZED_AMOUNT;
                            _transferToken(validatorUser, reward, pol);
                            logger.logClaimRewards(validatorId, reward, totalRewardsLiquidated);
                        }
                        function _transferToken(address destination, uint256 amount, bool pol) private {
                            if (!pol) _convertPOLToMatic(amount);
                            IERC20 token_ = _getToken(pol);
                            require(token_.transfer(destination, amount), "transfer failed");
                        }
                        // Do not use this function to transfer from self.
                        function _transferTokenFrom(address from, address destination, uint256 amount, bool pol) private {
                            IERC20 token_ = _getToken(pol);
                            require(token_.transferFrom(from, destination, amount), "transfer from failed");
                            if (!pol && destination == address(this)) _convertMaticToPOL(amount);
                        }
                        function _transferAndTopUp(address user, address from, uint256 fee, uint256 additionalAmount, bool pol) private {
                            require(fee >= minHeimdallFee, "fee too small");
                            _transferTokenFrom(from, address(this), fee.add(additionalAmount), pol);
                            totalHeimdallFee = totalHeimdallFee.add(fee);
                            logger.logTopUpFee(user, fee);
                        }
                        function _insertSigner(address newSigner) internal {
                            signers.push(newSigner);
                            uint256 lastIndex = signers.length - 1;
                            uint256 i = lastIndex;
                            for (; i > 0; --i) {
                                address signer = signers[i - 1];
                                if (signer < newSigner) {
                                    break;
                                }
                                signers[i] = signer;
                            }
                            if (i != lastIndex) {
                                signers[i] = newSigner;
                            }
                        }
                        function _removeSigner(address signerToDelete) internal {
                            uint256 totalSigners = signers.length;
                            address swapSigner = signers[totalSigners - 1];
                            delete signers[totalSigners - 1];
                            // bubble last element to the beginning until target signer is met
                            for (uint256 i = totalSigners - 1; i > 0; --i) {
                                if (swapSigner == signerToDelete) {
                                    break;
                                }
                                (swapSigner, signers[i - 1]) = (signers[i - 1], swapSigner);
                            }
                            signers.length = totalSigners - 1;
                        }
                        function convertMaticToPOL(uint256 amount) external onlyGovernance {
                            _convertMaticToPOL(amount);
                        }
                        function _convertMaticToPOL(uint256 amount) internal {
                            require(tokenMatic.balanceOf(address(this)) >= amount, "Lacking MATIC");
                            tokenMatic.approve(address(migration), amount);
                            migration.migrate(amount);
                        }
                        function _convertPOLToMatic(uint256 amount) internal {
                            require(token.balanceOf(address(this)) >= amount, "Lacking POL");
                            token.approve(address(migration), amount);
                            migration.unmigrate(amount);
                        }
                        function _getToken(bool pol) internal view returns (IERC20 token_) {
                            token_ = pol ? token : tokenMatic;
                        }
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title ERC20 interface
                     * @dev see https://eips.ethereum.org/EIPS/eip-20
                     */
                    interface IERC20 {
                        function transfer(address to, uint256 value) external returns (bool);
                        function approve(address spender, uint256 value) external returns (bool);
                        function transferFrom(address from, address to, uint256 value) external returns (bool);
                        function totalSupply() external view returns (uint256);
                        function balanceOf(address who) external view returns (uint256);
                        function allowance(address owner, address spender) external view returns (uint256);
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title Math
                     * @dev Assorted math operations
                     */
                    library Math {
                        /**
                         * @dev Returns the largest of two numbers.
                         */
                        function max(uint256 a, uint256 b) internal pure returns (uint256) {
                            return a >= b ? a : b;
                        }
                        /**
                         * @dev Returns the smallest of two numbers.
                         */
                        function min(uint256 a, uint256 b) internal pure returns (uint256) {
                            return a < b ? a : b;
                        }
                        /**
                         * @dev Calculates the average of two numbers. Since these are integers,
                         * averages of an even and odd number cannot be represented, and will be
                         * rounded down.
                         */
                        function average(uint256 a, uint256 b) internal pure returns (uint256) {
                            // (a + b) / 2 can overflow, so we distribute
                            return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
                        }
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title SafeMath
                     * @dev Unsigned math operations with safety checks that revert on error
                     */
                    library SafeMath {
                        /**
                         * @dev Multiplies two unsigned integers, reverts on overflow.
                         */
                        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                            // benefit is lost if 'b' is also tested.
                            // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                            if (a == 0) {
                                return 0;
                            }
                            uint256 c = a * b;
                            require(c / a == b);
                            return c;
                        }
                        /**
                         * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
                         */
                        function div(uint256 a, uint256 b) internal pure returns (uint256) {
                            // Solidity only automatically asserts when dividing by 0
                            require(b > 0);
                            uint256 c = a / b;
                            // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                            return c;
                        }
                        /**
                         * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                         */
                        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b <= a);
                            uint256 c = a - b;
                            return c;
                        }
                        /**
                         * @dev Adds two unsigned integers, reverts on overflow.
                         */
                        function add(uint256 a, uint256 b) internal pure returns (uint256) {
                            uint256 c = a + b;
                            require(c >= a);
                            return c;
                        }
                        /**
                         * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
                         * reverts when dividing by zero.
                         */
                        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b != 0);
                            return a % b;
                        }
                    }
                    pragma solidity ^0.5.2;
                    library ECVerify {
                        function ecrecovery(bytes32 hash, uint[3] memory sig)
                            internal
                            pure
                            returns (address)
                        {
                            bytes32 r;
                            bytes32 s;
                            uint8 v;
                            assembly {
                                r := mload(sig)
                                s := mload(add(sig, 32))
                                v := byte(31, mload(add(sig, 64)))
                            }
                            if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                                return address(0x0);
                            }
                            // https://github.com/ethereum/go-ethereum/issues/2053
                            if (v < 27) {
                                v += 27;
                            }
                            if (v != 27 && v != 28) {
                                return address(0x0);
                            }
                            // get address out of hash and signature
                            address result = ecrecover(hash, v, r, s);
                            // ecrecover returns zero on error
                            require(result != address(0x0));
                            return result;
                        }
                        function ecrecovery(bytes32 hash, bytes memory sig)
                            internal
                            pure
                            returns (address)
                        {
                            bytes32 r;
                            bytes32 s;
                            uint8 v;
                            if (sig.length != 65) {
                                return address(0x0);
                            }
                            assembly {
                                r := mload(add(sig, 32))
                                s := mload(add(sig, 64))
                                v := and(mload(add(sig, 65)), 255)
                            }
                            // https://github.com/ethereum/go-ethereum/issues/2053
                            if (v < 27) {
                                v += 27;
                            }
                            if (v != 27 && v != 28) {
                                return address(0x0);
                            }
                            // get address out of hash and signature
                            address result = ecrecover(hash, v, r, s);
                            // ecrecover returns zero on error
                            require(result != address(0x0));
                            return result;
                        }
                        function ecrecovery(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
                            internal
                            pure
                            returns (address)
                        {
                            // get address out of hash and signature
                            address result = ecrecover(hash, v, r, s);
                            // ecrecover returns zero on error
                            require(result != address(0x0), "signature verification failed");
                            return result;
                        }
                        function ecverify(bytes32 hash, bytes memory sig, address signer)
                            internal
                            pure
                            returns (bool)
                        {
                            return signer == ecrecovery(hash, sig);
                        }
                    }
                    pragma solidity ^0.5.2;
                    library Merkle {
                        function checkMembership(
                            bytes32 leaf,
                            uint256 index,
                            bytes32 rootHash,
                            bytes memory proof
                        ) internal pure returns (bool) {
                            require(proof.length % 32 == 0, "Invalid proof length");
                            uint256 proofHeight = proof.length / 32;
                            // Proof of size n means, height of the tree is n+1.
                            // In a tree of height n+1, max #leafs possible is 2 ^ n
                            require(index < 2 ** proofHeight, "Leaf index is too big");
                            bytes32 proofElement;
                            bytes32 computedHash = leaf;
                            for (uint256 i = 32; i <= proof.length; i += 32) {
                                assembly {
                                    proofElement := mload(add(proof, i))
                                }
                                if (index % 2 == 0) {
                                    computedHash = keccak256(
                                        abi.encodePacked(computedHash, proofElement)
                                    );
                                } else {
                                    computedHash = keccak256(
                                        abi.encodePacked(proofElement, computedHash)
                                    );
                                }
                                index = index / 2;
                            }
                            return computedHash == rootHash;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Governable} from "../governance/Governable.sol";
                    import {Lockable} from "./Lockable.sol";
                    contract GovernanceLockable is Lockable, Governable {
                        constructor(address governance) public Governable(governance) {}
                        function lock() public onlyGovernance {
                            super.lock();
                        }
                        function unlock() public onlyGovernance {
                            super.unlock();
                        }
                    }
                    pragma solidity ^0.5.2;
                    contract DelegateProxyForwarder {
                        function delegatedFwd(address _dst, bytes memory _calldata) internal {
                            // solium-disable-next-line security/no-inline-assembly
                            assembly {
                                let result := delegatecall(
                                    sub(gas, 10000),
                                    _dst,
                                    add(_calldata, 0x20),
                                    mload(_calldata),
                                    0,
                                    0
                                )
                                let size := returndatasize
                                let ptr := mload(0x40)
                                returndatacopy(ptr, 0, size)
                                // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
                                // if the call returned error data, forward it
                                switch result
                                    case 0 {
                                        revert(ptr, size)
                                    }
                                    default {
                                        return(ptr, size)
                                    }
                            }
                        }
                        
                        function isContract(address _target) internal view returns (bool) {
                            if (_target == address(0)) {
                                return false;
                            }
                            uint256 size;
                            assembly {
                                size := extcodesize(_target)
                            }
                            return size > 0;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Governable} from "./governance/Governable.sol";
                    import {IWithdrawManager} from "../root/withdrawManager/IWithdrawManager.sol";
                    contract Registry is Governable {
                        // @todo hardcode constants
                        bytes32 private constant WETH_TOKEN = keccak256("wethToken");
                        bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
                        bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
                        bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
                        bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
                        bytes32 private constant CHILD_CHAIN = keccak256("childChain");
                        bytes32 private constant STATE_SENDER = keccak256("stateSender");
                        bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
                        address public erc20Predicate;
                        address public erc721Predicate;
                        mapping(bytes32 => address) public contractMap;
                        mapping(address => address) public rootToChildToken;
                        mapping(address => address) public childToRootToken;
                        mapping(address => bool) public proofValidatorContracts;
                        mapping(address => bool) public isERC721;
                        enum Type {Invalid, ERC20, ERC721, Custom}
                        struct Predicate {
                            Type _type;
                        }
                        mapping(address => Predicate) public predicates;
                        event TokenMapped(address indexed rootToken, address indexed childToken);
                        event ProofValidatorAdded(address indexed validator, address indexed from);
                        event ProofValidatorRemoved(address indexed validator, address indexed from);
                        event PredicateAdded(address indexed predicate, address indexed from);
                        event PredicateRemoved(address indexed predicate, address indexed from);
                        event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
                        constructor(address _governance) public Governable(_governance) {}
                        function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
                            emit ContractMapUpdated(_key, contractMap[_key], _address);
                            contractMap[_key] = _address;
                        }
                        /**
                         * @dev Map root token to child token
                         * @param _rootToken Token address on the root chain
                         * @param _childToken Token address on the child chain
                         * @param _isERC721 Is the token being mapped ERC721
                         */
                        function mapToken(
                            address _rootToken,
                            address _childToken,
                            bool _isERC721
                        ) external onlyGovernance {
                            require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
                            rootToChildToken[_rootToken] = _childToken;
                            childToRootToken[_childToken] = _rootToken;
                            isERC721[_rootToken] = _isERC721;
                            IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
                            emit TokenMapped(_rootToken, _childToken);
                        }
                        function addErc20Predicate(address predicate) public onlyGovernance {
                            require(predicate != address(0x0), "Can not add null address as predicate");
                            erc20Predicate = predicate;
                            addPredicate(predicate, Type.ERC20);
                        }
                        function addErc721Predicate(address predicate) public onlyGovernance {
                            erc721Predicate = predicate;
                            addPredicate(predicate, Type.ERC721);
                        }
                        function addPredicate(address predicate, Type _type) public onlyGovernance {
                            require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
                            predicates[predicate]._type = _type;
                            emit PredicateAdded(predicate, msg.sender);
                        }
                        function removePredicate(address predicate) public onlyGovernance {
                            require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
                            delete predicates[predicate];
                            emit PredicateRemoved(predicate, msg.sender);
                        }
                        function getValidatorShareAddress() public view returns (address) {
                            return contractMap[VALIDATOR_SHARE];
                        }
                        function getWethTokenAddress() public view returns (address) {
                            return contractMap[WETH_TOKEN];
                        }
                        function getDepositManagerAddress() public view returns (address) {
                            return contractMap[DEPOSIT_MANAGER];
                        }
                        function getStakeManagerAddress() public view returns (address) {
                            return contractMap[STAKE_MANAGER];
                        }
                        function getSlashingManagerAddress() public view returns (address) {
                            return contractMap[SLASHING_MANAGER];
                        }
                        function getWithdrawManagerAddress() public view returns (address) {
                            return contractMap[WITHDRAW_MANAGER];
                        }
                        function getChildChainAndStateSender() public view returns (address, address) {
                            return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
                        }
                        function isTokenMapped(address _token) public view returns (bool) {
                            return rootToChildToken[_token] != address(0x0);
                        }
                        function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
                            require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
                            return isERC721[_token];
                        }
                        function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
                            if (isTokenMappedAndIsErc721(_token)) {
                                return erc721Predicate;
                            }
                            return erc20Predicate;
                        }
                        function isChildTokenErc721(address childToken) public view returns (bool) {
                            address rootToken = childToRootToken[childToken];
                            require(rootToken != address(0x0), "Child token is not mapped");
                            return isERC721[rootToken];
                        }
                    }
                    pragma solidity 0.5.17;
                    contract IStakeManager {
                        // validator replacement
                        function startAuction(
                            uint256 validatorId,
                            uint256 amount,
                            bool acceptDelegation,
                            bytes calldata signerPubkey
                        ) external;
                        function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external;
                        function transferFunds(
                            uint256 validatorId,
                            uint256 amount,
                            address delegator
                        ) external returns (bool);
                        function transferFundsPOL(
                            uint256 validatorId, 
                            uint256 amount, 
                            address delegator
                        ) external returns (bool);
                        function delegationDeposit(
                            uint256 validatorId,
                            uint256 amount,
                            address delegator
                        ) external returns (bool);
                        function delegationDepositPOL(
                            uint256 validatorId, 
                            uint256 amount, 
                            address delegator
                        ) external returns (bool);
                        function unstake(uint256 validatorId) external;
                        function unstakePOL(uint256 validatorId) external;
                        function totalStakedFor(address addr) external view returns (uint256);
                        function stakeFor(
                            address user,
                            uint256 amount,
                            uint256 heimdallFee,
                            bool acceptDelegation,
                            bytes memory signerPubkey
                        ) public;
                        function stakeForPOL(
                            address user,
                            uint256 amount,
                            uint256 heimdallFee,
                            bool acceptDelegation,
                            bytes memory signerPubkey
                        ) public;
                        function checkSignatures(
                            uint256 blockInterval,
                            bytes32 voteHash,
                            bytes32 stateRoot,
                            address proposer,
                            uint[3][] calldata sigs
                        ) external returns (uint256);
                        function updateValidatorState(uint256 validatorId, int256 amount) public;
                        function ownerOf(uint256 tokenId) public view returns (address);
                        function slash(bytes calldata slashingInfoList) external returns (uint256);
                        function validatorStake(uint256 validatorId) public view returns (uint256);
                        function epoch() public view returns (uint256);
                        function getRegistry() public view returns (address);
                        function withdrawalDelay() public view returns (uint256);
                        function delegatedAmount(uint256 validatorId) public view returns(uint256);
                        function decreaseValidatorDelegatedAmount(uint256 validatorId, uint256 amount) public;
                        function withdrawDelegatorsReward(uint256 validatorId) public returns(uint256);
                        function delegatorsReward(uint256 validatorId) public view returns(uint256);
                        function dethroneAndStake(
                            address auctionUser,
                            uint256 heimdallFee,
                            uint256 validatorId,
                            uint256 auctionAmount,
                            bool acceptDelegation,
                            bytes calldata signerPubkey
                        ) external;
                    }
                    pragma solidity 0.5.17;
                    // note this contract interface is only for stakeManager use
                    contract IValidatorShare {
                        function withdrawRewards() public;
                        function unstakeClaimTokens() public;
                        function getLiquidRewards(address user) public view returns (uint256);
                        
                        function owner() public view returns (address);
                        function restake() public returns(uint256, uint256);
                        function unlock() external;
                        function lock() external;
                        function drain(
                            address token,
                            address payable destination,
                            uint256 amount
                        ) external;
                        function slash(uint256 valPow, uint256 delegatedAmount, uint256 totalAmountToSlash) external returns (uint256);
                        function updateDelegation(bool delegation) external;
                        function migrateOut(address user, uint256 amount) external;
                        function migrateIn(address user, uint256 amount) external;
                    }
                    pragma solidity 0.5.17;
                    import {Registry} from "../../common/Registry.sol";
                    import {ERC20NonTradable} from "../../common/tokens/ERC20NonTradable.sol";
                    import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
                    import {StakingInfo} from "./../StakingInfo.sol";
                    import {EventsHub} from "./../EventsHub.sol";
                    import {OwnableLockable} from "../../common/mixin/OwnableLockable.sol";
                    import {IStakeManager} from "../stakeManager/IStakeManager.sol";
                    import {IValidatorShare} from "./IValidatorShare.sol";
                    import {Initializable} from "../../common/mixin/Initializable.sol";
                    import {IERC20Permit} from "./../../common/misc/IERC20Permit.sol";
                    contract ValidatorShare is IValidatorShare, ERC20NonTradable, OwnableLockable, Initializable {
                        struct DelegatorUnbond {
                            uint256 shares;
                            uint256 withdrawEpoch;
                        }
                        uint256 constant EXCHANGE_RATE_PRECISION = 100;
                        // maximum matic possible, even if rate will be 1 and all matic will be staked in one go, it will result in 10 ^ 58 shares
                        uint256 constant EXCHANGE_RATE_HIGH_PRECISION = 10**29;
                        uint256 constant MAX_COMMISION_RATE = 100;
                        uint256 constant REWARD_PRECISION = 10**25;
                        StakingInfo public stakingLogger;
                        IStakeManager public stakeManager;
                        uint256 public validatorId;
                        uint256 public validatorRewards_deprecated;
                        uint256 public commissionRate_deprecated;
                        uint256 public lastCommissionUpdate_deprecated;
                        uint256 public minAmount;
                        uint256 public totalStake_deprecated;
                        uint256 public rewardPerShare;
                        uint256 public activeAmount;
                        bool public delegation;
                        uint256 public withdrawPool;
                        uint256 public withdrawShares;
                        mapping(address => uint256) amountStaked_deprecated; // deprecated, keep for foundation delegators
                        mapping(address => DelegatorUnbond) public unbonds;
                        mapping(address => uint256) public initalRewardPerShare;
                        mapping(address => uint256) public unbondNonces;
                        mapping(address => mapping(uint256 => DelegatorUnbond)) public unbonds_new;
                        EventsHub public eventsHub;
                        IERC20Permit public polToken;
                        constructor() public {
                            _disableInitializer();
                        }
                        // onlyOwner will prevent this contract from initializing, since it's owner is going to be 0x0 address
                        function initialize(
                            uint256 _validatorId,
                            address _stakingLogger,
                            address _stakeManager
                        ) external initializer {
                            validatorId = _validatorId;
                            stakingLogger = StakingInfo(_stakingLogger);
                            stakeManager = IStakeManager(_stakeManager);
                            _transferOwnership(_stakeManager);
                            _getOrCacheEventsHub();
                            minAmount = 10**18;
                            delegation = true;
                        }
                        /**
                            Public View Methods
                        */
                        function exchangeRate() public view returns (uint256) {
                            uint256 totalShares = totalSupply();
                            uint256 precision = _getRatePrecision();
                            return totalShares == 0 ? precision : stakeManager.delegatedAmount(validatorId).mul(precision).div(totalShares);
                        }
                        function getTotalStake(address user) public view returns (uint256, uint256) {
                            uint256 shares = balanceOf(user);
                            uint256 rate = exchangeRate();
                            if (shares == 0) {
                                return (0, rate);
                            }
                            return (rate.mul(shares).div(_getRatePrecision()), rate);
                        }
                        function withdrawExchangeRate() public view returns (uint256) {
                            uint256 precision = _getRatePrecision();
                            if (validatorId < 8) {
                                // fix of potentially broken withdrawals for future unbonding
                                // foundation validators have no slashing enabled and thus we can return default exchange rate
                                // because without slashing rate will stay constant
                                return precision;
                            }
                            uint256 _withdrawShares = withdrawShares;
                            return _withdrawShares == 0 ? precision : withdrawPool.mul(precision).div(_withdrawShares);
                        }
                        function getLiquidRewards(address user) public view returns (uint256) {
                            return _calculateReward(user, getRewardPerShare());
                        }
                        function getRewardPerShare() public view returns (uint256) {
                            return _calculateRewardPerShareWithRewards(stakeManager.delegatorsReward(validatorId));
                        }
                        /**
                            Public Methods
                         */
                        function buyVoucher(uint256 _amount, uint256 _minSharesToMint) public returns (uint256 amountToDeposit) {
                            return _buyVoucher(_amount, _minSharesToMint, false);
                        }
                        // @dev permit only available on pol token
                        // @dev txn fails if frontrun, use buyVoucher instead
                        function buyVoucherWithPermit(
                            uint256 _amount,
                            uint256 _minSharesToMint,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public returns (uint256 amountToDeposit) {
                            IERC20Permit _polToken = _getOrCachePOLToken();
                            uint256 nonceBefore = _polToken.nonces(msg.sender);
                            _polToken.permit(msg.sender, address(stakeManager), _amount, deadline, v, r, s);
                            require(_polToken.nonces(msg.sender) == nonceBefore + 1, "Invalid permit");
                            return _buyVoucher(_amount, _minSharesToMint, true); // invokes stakeManager to pull token from msg.sender
                        }
                        function buyVoucherPOL(uint256 _amount, uint256 _minSharesToMint) public returns (uint256 amountToDeposit) {
                            return _buyVoucher(_amount, _minSharesToMint, true);
                        }
                        function _buyVoucher(uint256 _amount, uint256 _minSharesToMint, bool pol) internal returns (uint256 amountToDeposit) {
                            _withdrawAndTransferReward(msg.sender, pol);
                            amountToDeposit = _buyShares(_amount, _minSharesToMint, msg.sender);
                            require(
                                pol
                                    ? stakeManager.delegationDepositPOL(validatorId, amountToDeposit, msg.sender)
                                    : stakeManager.delegationDeposit(validatorId, amountToDeposit, msg.sender),
                                "deposit failed"
                            );
                            return amountToDeposit;
                        }
                        function restake() public returns (uint256, uint256) {
                            return _restake(false);
                        }
                        function restakePOL() public returns (uint256, uint256) {
                            return _restake(true);
                        }
                        function _restake(bool pol) public returns (uint256, uint256) {
                            address user = msg.sender;
                            uint256 liquidReward = _withdrawReward(user);
                            uint256 amountRestaked;
                            require(liquidReward >= minAmount, "Too small rewards to restake");
                            if (liquidReward != 0) {
                                amountRestaked = _buyShares(liquidReward, 0, user);
                                if (liquidReward > amountRestaked) {
                                    // return change to the user
                                    require(
                                        pol
                                            ? stakeManager.transferFundsPOL(validatorId, liquidReward - amountRestaked, user)
                                            : stakeManager.transferFunds(validatorId, liquidReward - amountRestaked, user),
                                        "Insufficent rewards"
                                    );
                                    stakingLogger.logDelegatorClaimRewards(validatorId, user, liquidReward - amountRestaked);
                                }
                                (uint256 totalStaked, ) = getTotalStake(user);
                                stakingLogger.logDelegatorRestaked(validatorId, user, totalStaked);
                            }
                            
                            return (amountRestaked, liquidReward);
                        }
                        function sellVoucher(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            __sellVoucher(claimAmount, maximumSharesToBurn, false);
                        }
                        function sellVoucherPOL(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            __sellVoucher(claimAmount, maximumSharesToBurn, true);
                        }
                        function __sellVoucher(uint256 claimAmount, uint256 maximumSharesToBurn, bool pol) internal {
                            (uint256 shares, uint256 _withdrawPoolShare) = _sellVoucher(claimAmount, maximumSharesToBurn, pol);
                            DelegatorUnbond memory unbond = unbonds[msg.sender];
                            unbond.shares = unbond.shares.add(_withdrawPoolShare);
                            // refresh unbond period
                            unbond.withdrawEpoch = stakeManager.epoch();
                            unbonds[msg.sender] = unbond;
                            StakingInfo logger = stakingLogger;
                            logger.logShareBurned(validatorId, msg.sender, claimAmount, shares);
                            logger.logStakeUpdate(validatorId);
                        }
                        function withdrawRewards() public {
                            _withdrawRewards(false);
                        }
                        function withdrawRewardsPOL() public {
                            _withdrawRewards(true);
                        }
                        function _withdrawRewards(bool pol) internal {
                            uint256 rewards = _withdrawAndTransferReward(msg.sender, pol);
                            require(rewards >= minAmount, "Too small rewards amount");
                        }
                        function migrateOut(address user, uint256 amount) external onlyOwner {
                            _withdrawAndTransferReward(user, true);
                            (uint256 totalStaked, uint256 rate) = getTotalStake(user);
                            require(totalStaked >= amount, "Migrating too much");
                            uint256 precision = _getRatePrecision();
                            uint256 shares = amount.mul(precision).div(rate);
                            _burn(user, shares);
                            stakeManager.updateValidatorState(validatorId, -int256(amount));
                            activeAmount = activeAmount.sub(amount);
                            stakingLogger.logShareBurned(validatorId, user, amount, shares);
                            stakingLogger.logStakeUpdate(validatorId);
                            stakingLogger.logDelegatorUnstaked(validatorId, user, amount);
                        }
                        function migrateIn(address user, uint256 amount) external onlyOwner {
                            _withdrawAndTransferReward(user, true);
                            _buyShares(amount, 0, user);
                        } 
                        function unstakeClaimTokens() public {
                            _unstakeClaimTokens(false);
                        }
                        function unstakeClaimTokensPOL() public {
                            _unstakeClaimTokens(true);
                        }
                        function _unstakeClaimTokens(bool pol) internal {
                            DelegatorUnbond memory unbond = unbonds[msg.sender];
                            uint256 amount = _unstakeClaimTokens(unbond, pol);
                            delete unbonds[msg.sender];
                            stakingLogger.logDelegatorUnstaked(validatorId, msg.sender, amount);
                        }
                        function slash(
                            uint256 validatorStake,
                            uint256 delegatedAmount,
                            uint256 totalAmountToSlash
                        ) external onlyOwner returns (uint256) {
                            revert("Slashing disabled");
                        }
                        function updateDelegation(bool _delegation) external onlyOwner {
                            delegation = _delegation;
                        }
                        function drain(
                            address token,
                            address payable destination,
                            uint256 amount
                        ) external onlyOwner {
                            revert("No draining.");
                        }
                        /**
                            New shares exit API
                         */
                        function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            _sellVoucher_new(claimAmount, maximumSharesToBurn, false);
                        }
                        function sellVoucher_newPOL(uint256 claimAmount, uint256 maximumSharesToBurn) public {
                            _sellVoucher_new(claimAmount, maximumSharesToBurn, true);
                        }
                        function _sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn, bool pol) public {
                            (uint256 shares, uint256 _withdrawPoolShare) = _sellVoucher(claimAmount, maximumSharesToBurn, pol);
                            uint256 unbondNonce = unbondNonces[msg.sender].add(1);
                            DelegatorUnbond memory unbond = DelegatorUnbond({
                                shares: _withdrawPoolShare,
                                withdrawEpoch: stakeManager.epoch()
                            });
                            unbonds_new[msg.sender][unbondNonce] = unbond;
                            unbondNonces[msg.sender] = unbondNonce;
                            _getOrCacheEventsHub().logShareBurnedWithId(validatorId, msg.sender, claimAmount, shares, unbondNonce);
                            stakingLogger.logStakeUpdate(validatorId);
                        }
                        function unstakeClaimTokens_new(uint256 unbondNonce) public {
                            _unstakeClaimTokens_new(unbondNonce, false);
                        }
                        function unstakeClaimTokens_newPOL(uint256 unbondNonce) public {
                            _unstakeClaimTokens_new(unbondNonce, true);
                        }
                        function _unstakeClaimTokens_new(uint256 unbondNonce, bool pol) internal {
                            DelegatorUnbond memory unbond = unbonds_new[msg.sender][unbondNonce];
                            uint256 amount = _unstakeClaimTokens(unbond, pol);
                            delete unbonds_new[msg.sender][unbondNonce];
                            _getOrCacheEventsHub().logDelegatorUnstakedWithId(validatorId, msg.sender, amount, unbondNonce);
                        }
                        /**
                            Private Methods
                         */
                        function _getOrCacheEventsHub() private returns(EventsHub) {
                            EventsHub _eventsHub = eventsHub;
                            if (_eventsHub == EventsHub(0x0)) {
                                _eventsHub = EventsHub(Registry(stakeManager.getRegistry()).contractMap(keccak256("eventsHub")));
                                eventsHub = _eventsHub;
                            }
                            return _eventsHub;
                        }
                        function _getOrCachePOLToken() private returns (IERC20Permit) {
                            IERC20Permit _polToken = polToken;
                            if (_polToken == IERC20Permit(0x0)) {
                                _polToken = IERC20Permit(Registry(stakeManager.getRegistry()).contractMap(keccak256("pol")));
                                require(_polToken != IERC20Permit(0x0), "unset");
                                polToken = _polToken;
                            }
                            return _polToken;
                        }
                        function _sellVoucher(
                            uint256 claimAmount,
                            uint256 maximumSharesToBurn,
                            bool pol
                        ) private returns (uint256, uint256) {
                            // first get how much staked in total and compare to target unstake amount
                            (uint256 totalStaked, uint256 rate) = getTotalStake(msg.sender);
                            require(totalStaked != 0 && totalStaked >= claimAmount, "Too much requested");
                            // convert requested amount back to shares
                            uint256 precision = _getRatePrecision();
                            uint256 shares = claimAmount.mul(precision).div(rate);
                            require(shares <= maximumSharesToBurn, "too much slippage");
                            _withdrawAndTransferReward(msg.sender, pol);
                            _burn(msg.sender, shares);
                            stakeManager.updateValidatorState(validatorId, -int256(claimAmount));
                            activeAmount = activeAmount.sub(claimAmount);
                            uint256 _withdrawPoolShare = claimAmount.mul(precision).div(withdrawExchangeRate());
                            withdrawPool = withdrawPool.add(claimAmount);
                            withdrawShares = withdrawShares.add(_withdrawPoolShare);
                            return (shares, _withdrawPoolShare);
                        }
                        function _unstakeClaimTokens(DelegatorUnbond memory unbond, bool pol) private returns (uint256) {
                            uint256 shares = unbond.shares;
                            require(
                                unbond.withdrawEpoch.add(stakeManager.withdrawalDelay()) <= stakeManager.epoch() && shares > 0,
                                "Incomplete withdrawal period"
                            );
                            uint256 _amount = withdrawExchangeRate().mul(shares).div(_getRatePrecision());
                            withdrawShares = withdrawShares.sub(shares);
                            withdrawPool = withdrawPool.sub(_amount);
                            require(
                                pol ? stakeManager.transferFundsPOL(validatorId, _amount, msg.sender) : stakeManager.transferFunds(validatorId, _amount, msg.sender),
                                "Insufficent rewards"
                            );
                            return _amount;
                        }
                        function _getRatePrecision() private view returns (uint256) {
                            // if foundation validator, use old precision
                            if (validatorId < 8) {
                                return EXCHANGE_RATE_PRECISION;
                            }
                            return EXCHANGE_RATE_HIGH_PRECISION;
                        }
                        function _calculateRewardPerShareWithRewards(uint256 accumulatedReward) private view returns (uint256) {
                            uint256 _rewardPerShare = rewardPerShare;
                            if (accumulatedReward != 0) {
                                uint256 totalShares = totalSupply();
                                
                                if (totalShares != 0) {
                                    _rewardPerShare = _rewardPerShare.add(accumulatedReward.mul(REWARD_PRECISION).div(totalShares));
                                }
                            }
                            return _rewardPerShare;
                        }
                        function _calculateReward(address user, uint256 _rewardPerShare) private view returns (uint256) {
                            uint256 shares = balanceOf(user);
                            if (shares == 0) {
                                return 0;
                            }
                            uint256 _initialRewardPerShare = initalRewardPerShare[user];
                            if (_initialRewardPerShare == _rewardPerShare) {
                                return 0;
                            }
                            return _rewardPerShare.sub(_initialRewardPerShare).mul(shares).div(REWARD_PRECISION);
                        }
                        function _withdrawReward(address user) private returns (uint256) {
                            uint256 _rewardPerShare = _calculateRewardPerShareWithRewards(
                                stakeManager.withdrawDelegatorsReward(validatorId)
                            );
                            uint256 liquidRewards = _calculateReward(user, _rewardPerShare);
                            
                            rewardPerShare = _rewardPerShare;
                            initalRewardPerShare[user] = _rewardPerShare;
                            return liquidRewards;
                        }
                        function _withdrawAndTransferReward(address user, bool pol) private returns (uint256) {
                            uint256 liquidRewards = _withdrawReward(user);
                            if (liquidRewards != 0) {
                                require(
                                    pol ? stakeManager.transferFundsPOL(validatorId, liquidRewards, user) : stakeManager.transferFunds(validatorId, liquidRewards, user),
                                    "Insufficent rewards"
                                );
                                stakingLogger.logDelegatorClaimRewards(validatorId, user, liquidRewards);
                            }
                            return liquidRewards;
                        }
                        function _buyShares(
                            uint256 _amount,
                            uint256 _minSharesToMint,
                            address user
                        ) private onlyWhenUnlocked returns (uint256) {
                            require(delegation, "Delegation is disabled");
                            uint256 rate = exchangeRate();
                            uint256 precision = _getRatePrecision();
                            uint256 shares = _amount.mul(precision).div(rate);
                            require(shares >= _minSharesToMint, "Too much slippage");
                            require(unbonds[user].shares == 0, "Ongoing exit");
                            _mint(user, shares);
                            // clamp amount of tokens in case resulted shares requires less tokens than anticipated
                            _amount = rate.mul(shares).div(precision);
                            stakeManager.updateValidatorState(validatorId, int256(_amount));
                            activeAmount = activeAmount.add(_amount);
                            StakingInfo logger = stakingLogger;
                            logger.logShareMinted(validatorId, user, _amount, shares);
                            logger.logStakeUpdate(validatorId);
                            return _amount;
                        }
                        function transferPOL(address to, uint256 value) public returns (bool) {
                            _transfer(to, value, true);
                            return true;
                        }
                        function transfer(address to, uint256 value) public returns (bool) {
                            _transfer(to, value, false);
                            return true;
                        }
                        function _transfer(address to, uint256 value, bool pol) internal {
                            address from = msg.sender;
                            // get rewards for recipient
                            _withdrawAndTransferReward(to, pol);
                            // convert rewards to shares
                            _withdrawAndTransferReward(from, pol);
                            // move shares to recipient
                            super._transfer(from, to, value);
                            _getOrCacheEventsHub().logSharesTransfer(validatorId, from, to, value);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Registry} from "../common/Registry.sol";
                    import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
                    import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    // dummy interface to avoid cyclic dependency
                    contract IStakeManagerLocal {
                        enum Status {Inactive, Active, Locked, Unstaked}
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                            Status status;
                        }
                        mapping(uint256 => Validator) public validators;
                        bytes32 public accountStateRoot;
                        uint256 public activeAmount; // delegation amount from validator contract
                        uint256 public validatorRewards;
                        function currentValidatorSetTotalStake() public view returns (uint256);
                        // signer to Validator mapping
                        function signerToValidator(address validatorAddress)
                            public
                            view
                            returns (uint256);
                        function isValidator(uint256 validatorId) public view returns (bool);
                    }
                    contract StakingInfo is Ownable {
                        using SafeMath for uint256;
                        mapping(uint256 => uint256) public validatorNonce;
                        /// @dev Emitted when validator stakes in '_stakeFor()' in StakeManager.
                        /// @param signer validator address.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param activationEpoch validator's first epoch as proposer.
                        /// @param amount staking amount.
                        /// @param total total staking amount.
                        /// @param signerPubkey public key of the validator
                        event Staked(
                            address indexed signer,
                            uint256 indexed validatorId,
                            uint256 nonce,
                            uint256 indexed activationEpoch,
                            uint256 amount,
                            uint256 total,
                            bytes signerPubkey
                        );
                        /// @dev Emitted when validator unstakes in 'unstakeClaim()'
                        /// @param user address of the validator.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param amount staking amount.
                        /// @param total total staking amount.
                        event Unstaked(
                            address indexed user,
                            uint256 indexed validatorId,
                            uint256 amount,
                            uint256 total
                        );
                        /// @dev Emitted when validator unstakes in '_unstake()'.
                        /// @param user address of the validator.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param deactivationEpoch last epoch for validator.
                        /// @param amount staking amount.
                        event UnstakeInit(
                            address indexed user,
                            uint256 indexed validatorId,
                            uint256 nonce,
                            uint256 deactivationEpoch,
                            uint256 indexed amount
                        );
                        /// @dev Emitted when the validator public key is updated in 'updateSigner()'.
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param oldSigner old address of the validator.
                        /// @param newSigner new address of the validator.
                        /// @param signerPubkey public key of the validator.
                        event SignerChange(
                            uint256 indexed validatorId,
                            uint256 nonce,
                            address indexed oldSigner,
                            address indexed newSigner,
                            bytes signerPubkey
                        );
                        event Restaked(uint256 indexed validatorId, uint256 amount, uint256 total);
                        event Jailed(
                            uint256 indexed validatorId,
                            uint256 indexed exitEpoch,
                            address indexed signer
                        );
                        event UnJailed(uint256 indexed validatorId, address indexed signer);
                        event Slashed(uint256 indexed nonce, uint256 indexed amount);
                        event ThresholdChange(uint256 newThreshold, uint256 oldThreshold);
                        event DynastyValueChange(uint256 newDynasty, uint256 oldDynasty);
                        event ProposerBonusChange(
                            uint256 newProposerBonus,
                            uint256 oldProposerBonus
                        );
                        event RewardUpdate(uint256 newReward, uint256 oldReward);
                        /// @dev Emitted when validator confirms the auction bid and at the time of restaking in confirmAuctionBid() and restake().
                        /// @param validatorId unique integer to identify a validator.
                        /// @param nonce to synchronize the events in heimdal.
                        /// @param newAmount the updated stake amount.
                        event StakeUpdate(
                            uint256 indexed validatorId,
                            uint256 indexed nonce,
                            uint256 indexed newAmount
                        );
                        event ClaimRewards(
                            uint256 indexed validatorId,
                            uint256 indexed amount,
                            uint256 indexed totalAmount
                        );
                        event StartAuction(
                            uint256 indexed validatorId,
                            uint256 indexed amount,
                            uint256 indexed auctionAmount
                        );
                        event ConfirmAuction(
                            uint256 indexed newValidatorId,
                            uint256 indexed oldValidatorId,
                            uint256 indexed amount
                        );
                        event TopUpFee(address indexed user, uint256 indexed fee);
                        event ClaimFee(address indexed user, uint256 indexed fee);
                        // Delegator events
                        event ShareMinted(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens
                        );
                        event ShareBurned(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens
                        );
                        event DelegatorClaimedRewards(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed rewards
                        );
                        event DelegatorRestaked(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed totalStaked
                        );
                        event DelegatorUnstaked(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 amount
                        );
                        event UpdateCommissionRate(
                            uint256 indexed validatorId,
                            uint256 indexed newCommissionRate,
                            uint256 indexed oldCommissionRate
                        );
                        Registry public registry;
                        modifier onlyValidatorContract(uint256 validatorId) {
                            address _contract;
                            (, , , , , , _contract, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                            require(_contract == msg.sender,
                            "Invalid sender, not validator");
                            _;
                        }
                        modifier StakeManagerOrValidatorContract(uint256 validatorId) {
                            address _contract;
                            address _stakeManager = registry.getStakeManagerAddress();
                            (, , , , , , _contract, ) = IStakeManagerLocal(_stakeManager).validators(
                                validatorId
                            );
                            require(_contract == msg.sender || _stakeManager == msg.sender,
                            "Invalid sender, not stake manager or validator contract");
                            _;
                        }
                        modifier onlyStakeManager() {
                            require(registry.getStakeManagerAddress() == msg.sender,
                            "Invalid sender, not stake manager");
                            _;
                        }
                        modifier onlySlashingManager() {
                            require(registry.getSlashingManagerAddress() == msg.sender,
                            "Invalid sender, not slashing manager");
                            _;
                        }
                        constructor(address _registry) public {
                            registry = Registry(_registry);
                        }
                        function updateNonce(
                            uint256[] calldata validatorIds,
                            uint256[] calldata nonces
                        ) external onlyOwner {
                            require(validatorIds.length == nonces.length, "args length mismatch");
                            for (uint256 i = 0; i < validatorIds.length; ++i) {
                                validatorNonce[validatorIds[i]] = nonces[i];
                            }
                        } 
                        function logStaked(
                            address signer,
                            bytes memory signerPubkey,
                            uint256 validatorId,
                            uint256 activationEpoch,
                            uint256 amount,
                            uint256 total
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit Staked(
                                signer,
                                validatorId,
                                validatorNonce[validatorId],
                                activationEpoch,
                                amount,
                                total,
                                signerPubkey
                            );
                        }
                        function logUnstaked(
                            address user,
                            uint256 validatorId,
                            uint256 amount,
                            uint256 total
                        ) public onlyStakeManager {
                            emit Unstaked(user, validatorId, amount, total);
                        }
                        function logUnstakeInit(
                            address user,
                            uint256 validatorId,
                            uint256 deactivationEpoch,
                            uint256 amount
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit UnstakeInit(
                                user,
                                validatorId,
                                validatorNonce[validatorId],
                                deactivationEpoch,
                                amount
                            );
                        }
                        function logSignerChange(
                            uint256 validatorId,
                            address oldSigner,
                            address newSigner,
                            bytes memory signerPubkey
                        ) public onlyStakeManager {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit SignerChange(
                                validatorId,
                                validatorNonce[validatorId],
                                oldSigner,
                                newSigner,
                                signerPubkey
                            );
                        }
                        function logRestaked(uint256 validatorId, uint256 amount, uint256 total)
                            public
                            onlyStakeManager
                        {
                            emit Restaked(validatorId, amount, total);
                        }
                        function logJailed(uint256 validatorId, uint256 exitEpoch, address signer)
                            public
                            onlyStakeManager
                        {
                            emit Jailed(validatorId, exitEpoch, signer);
                        }
                        function logUnjailed(uint256 validatorId, address signer)
                            public
                            onlyStakeManager
                        {
                            emit UnJailed(validatorId, signer);
                        }
                        function logSlashed(uint256 nonce, uint256 amount)
                            public
                            onlySlashingManager
                        {
                            emit Slashed(nonce, amount);
                        }
                        function logThresholdChange(uint256 newThreshold, uint256 oldThreshold)
                            public
                            onlyStakeManager
                        {
                            emit ThresholdChange(newThreshold, oldThreshold);
                        }
                        function logDynastyValueChange(uint256 newDynasty, uint256 oldDynasty)
                            public
                            onlyStakeManager
                        {
                            emit DynastyValueChange(newDynasty, oldDynasty);
                        }
                        function logProposerBonusChange(
                            uint256 newProposerBonus,
                            uint256 oldProposerBonus
                        ) public onlyStakeManager {
                            emit ProposerBonusChange(newProposerBonus, oldProposerBonus);
                        }
                        function logRewardUpdate(uint256 newReward, uint256 oldReward)
                            public
                            onlyStakeManager
                        {
                            emit RewardUpdate(newReward, oldReward);
                        }
                        function logStakeUpdate(uint256 validatorId)
                            public
                            StakeManagerOrValidatorContract(validatorId)
                        {
                            validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
                            emit StakeUpdate(
                                validatorId,
                                validatorNonce[validatorId],
                                totalValidatorStake(validatorId)
                            );
                        }
                        function logClaimRewards(
                            uint256 validatorId,
                            uint256 amount,
                            uint256 totalAmount
                        ) public onlyStakeManager {
                            emit ClaimRewards(validatorId, amount, totalAmount);
                        }
                        function logStartAuction(
                            uint256 validatorId,
                            uint256 amount,
                            uint256 auctionAmount
                        ) public onlyStakeManager {
                            emit StartAuction(validatorId, amount, auctionAmount);
                        }
                        function logConfirmAuction(
                            uint256 newValidatorId,
                            uint256 oldValidatorId,
                            uint256 amount
                        ) public onlyStakeManager {
                            emit ConfirmAuction(newValidatorId, oldValidatorId, amount);
                        }
                        function logTopUpFee(address user, uint256 fee) public onlyStakeManager {
                            emit TopUpFee(user, fee);
                        }
                        function logClaimFee(address user, uint256 fee) public onlyStakeManager {
                            emit ClaimFee(user, fee);
                        }
                        function getStakerDetails(uint256 validatorId)
                            public
                            view
                            returns (
                                uint256 amount,
                                uint256 reward,
                                uint256 activationEpoch,
                                uint256 deactivationEpoch,
                                address signer,
                                uint256 _status
                            )
                        {
                            IStakeManagerLocal stakeManager = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            );
                            address _contract;
                            IStakeManagerLocal.Status status;
                            (
                                amount,
                                reward,
                                activationEpoch,
                                deactivationEpoch,
                                ,
                                signer,
                                _contract,
                                status
                            ) = stakeManager.validators(validatorId);
                            _status = uint256(status);
                            if (_contract != address(0x0)) {
                                reward += IStakeManagerLocal(_contract).validatorRewards();
                            }
                        }
                        function totalValidatorStake(uint256 validatorId)
                            public
                            view
                            returns (uint256 validatorStake)
                        {
                            address contractAddress;
                            (validatorStake, , , , , , contractAddress, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                            if (contractAddress != address(0x0)) {
                                validatorStake += IStakeManagerLocal(contractAddress).activeAmount();
                            }
                        }
                        function getAccountStateRoot()
                            public
                            view
                            returns (bytes32 accountStateRoot)
                        {
                            accountStateRoot = IStakeManagerLocal(registry.getStakeManagerAddress())
                                .accountStateRoot();
                        }
                        function getValidatorContractAddress(uint256 validatorId)
                            public
                            view
                            returns (address ValidatorContract)
                        {
                            (, , , , , , ValidatorContract, ) = IStakeManagerLocal(
                                registry.getStakeManagerAddress()
                            )
                                .validators(validatorId);
                        }
                        // validator Share contract logging func
                        function logShareMinted(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareMinted(validatorId, user, amount, tokens);
                        }
                        function logShareBurned(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareBurned(validatorId, user, amount, tokens);
                        }
                        function logDelegatorClaimRewards(
                            uint256 validatorId,
                            address user,
                            uint256 rewards
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorClaimedRewards(validatorId, user, rewards);
                        }
                        function logDelegatorRestaked(
                            uint256 validatorId,
                            address user,
                            uint256 totalStaked
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorRestaked(validatorId, user, totalStaked);
                        }
                        function logDelegatorUnstaked(uint256 validatorId, address user, uint256 amount)
                            public
                            onlyValidatorContract(validatorId)
                        {
                            emit DelegatorUnstaked(validatorId, user, amount);
                        }
                        // deprecated
                        function logUpdateCommissionRate(
                            uint256 validatorId,
                            uint256 newCommissionRate,
                            uint256 oldCommissionRate
                        ) public onlyValidatorContract(validatorId) {
                            emit UpdateCommissionRate(
                                validatorId,
                                newCommissionRate,
                                oldCommissionRate
                            );
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
                    import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    contract StakingNFT is ERC721Full, Ownable {
                        constructor(string memory name, string memory symbol)
                            public
                            ERC721Full(name, symbol)
                        {
                            // solhint-disable-previous-line no-empty-blocks
                        }
                        function mint(address to, uint256 tokenId) public onlyOwner {
                            require(
                                balanceOf(to) == 0,
                                "Validators MUST NOT own multiple stake position"
                            );
                            _mint(to, tokenId);
                        }
                        function burn(uint256 tokenId) public onlyOwner {
                            _burn(tokenId);
                        }
                        function _transferFrom(address from, address to, uint256 tokenId) internal {
                            require(
                                balanceOf(to) == 0,
                                "Validators MUST NOT own multiple stake position"
                            );
                            super._transferFrom(from, to, tokenId);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {ValidatorShareProxy} from "./ValidatorShareProxy.sol";
                    import {ValidatorShare} from "./ValidatorShare.sol";
                    contract ValidatorShareFactory {
                        /**
                        - factory to create new validatorShare contracts
                       */
                        function create(uint256 validatorId, address loggerAddress, address registry) public returns (address) {
                            ValidatorShareProxy proxy = new ValidatorShareProxy(registry);
                            proxy.transferOwnership(msg.sender);
                            address proxyAddr = address(proxy);
                            (bool success, bytes memory data) = proxyAddr.call.gas(gasleft())(
                                abi.encodeWithSelector(
                                    ValidatorShare(proxyAddr).initialize.selector, 
                                    validatorId, 
                                    loggerAddress, 
                                    msg.sender
                                )
                            );
                            require(success, string(data));
                            return proxyAddr;
                        }
                    }
                    pragma solidity 0.5.17;
                    import {IERC20} from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                    import {Registry} from "../../common/Registry.sol";
                    import {GovernanceLockable} from "../../common/mixin/GovernanceLockable.sol";
                    import {RootChainable} from "../../common/mixin/RootChainable.sol";
                    import {StakingInfo} from "../StakingInfo.sol";
                    import {StakingNFT} from "./StakingNFT.sol";
                    import {ValidatorShareFactory} from "../validatorShare/ValidatorShareFactory.sol";
                    contract StakeManagerStorage is GovernanceLockable, RootChainable {
                        enum Status {Inactive, Active, Locked, Unstaked}
                        struct Auction {
                            uint256 amount;
                            uint256 startEpoch;
                            address user;
                            bool acceptDelegation;
                            bytes signerPubkey;
                        }
                        struct State {
                            uint256 amount;
                            uint256 stakerCount;
                        }
                        struct StateChange {
                            int256 amount;
                            int256 stakerCount;
                        }
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                            Status status;
                            uint256 commissionRate;
                            uint256 lastCommissionUpdate;
                            uint256 delegatorsReward;
                            uint256 delegatedAmount;
                            uint256 initialRewardPerStake;
                        }
                        uint256 constant MAX_COMMISION_RATE = 100;
                        uint256 constant MAX_PROPOSER_BONUS = 100;
                        uint256 constant REWARD_PRECISION = 10**25;
                        uint256 internal constant INCORRECT_VALIDATOR_ID = 2**256 - 1;
                        uint256 internal constant INITIALIZED_AMOUNT = 1;
                        IERC20 public token;
                        address public registry;
                        StakingInfo public logger;
                        StakingNFT public NFTContract;
                        ValidatorShareFactory public validatorShareFactory;
                        uint256 public WITHDRAWAL_DELAY; // unit: epoch
                        uint256 public currentEpoch;
                        // genesis/governance variables
                        uint256 public dynasty; // unit: epoch 50 days
                        uint256 public CHECKPOINT_REWARD; // update via governance
                        uint256 public minDeposit; // in ERC20 token
                        uint256 public minHeimdallFee; // in ERC20 token
                        uint256 public checkPointBlockInterval;
                        uint256 public signerUpdateLimit;
                        uint256 public validatorThreshold; //128
                        uint256 public totalStaked;
                        uint256 public NFTCounter;
                        uint256 public totalRewards;
                        uint256 public totalRewardsLiquidated;
                        uint256 public auctionPeriod; // 1 week in epochs
                        uint256 public proposerBonus; // 10 % of total rewards
                        bytes32 public accountStateRoot;
                        // Stop validator auction for some time when updating dynasty value
                        uint256 public replacementCoolDown;
                        bool public delegationEnabled;
                        mapping(uint256 => Validator) public validators;
                        mapping(address => uint256) public signerToValidator;
                        // current epoch stake power and stakers count
                        State public validatorState;
                        mapping(uint256 => StateChange) public validatorStateChanges;
                        mapping(address => uint256) public userFeeExit;
                        //Ongoing auctions for validatorId
                        mapping(uint256 => Auction) public validatorAuction;
                        // validatorId to last signer update epoch
                        mapping(uint256 => uint256) public latestSignerUpdateEpoch;
                        uint256 public totalHeimdallFee;
                    }
                    pragma solidity 0.5.17;
                    import {IPolygonMigration} from "../../common/misc/IPolygonMigration.sol";
                    import {IERC20} from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                    contract StakeManagerStorageExtension {
                        address public eventsHub;
                        uint256 public rewardPerStake;
                        address public extensionCode;
                        address[] public signers;
                        uint256 constant CHK_REWARD_PRECISION = 100;
                        uint256 public prevBlockInterval;
                        // how much less reward per skipped checkpoint, 0 - 100%
                        uint256 public rewardDecreasePerCheckpoint;
                        // how many checkpoints to reward
                        uint256 public maxRewardedCheckpoints;
                        // increase / decrease value for faster or slower checkpoints, 0 - 100%
                        uint256 public checkpointRewardDelta;
                        IERC20 public tokenMatic;
                        IPolygonMigration public migration;
                    }   
                    pragma solidity ^0.5.2;
                    interface IGovernance {
                        function update(address target, bytes calldata data) external;
                    }
                    pragma solidity ^0.5.2;
                    contract Initializable {
                        bool inited = false;
                        modifier initializer() {
                            require(!inited, "already inited");
                            inited = true;
                            _;
                        }
                        function _disableInitializer() internal {
                            inited = true;
                        }
                    }
                    pragma solidity 0.5.17;
                    import {IERC20} from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
                    import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
                    import {Registry} from "../../common/Registry.sol";
                    import {GovernanceLockable} from "../../common/mixin/GovernanceLockable.sol";
                    import {IStakeManager} from "./IStakeManager.sol";
                    import {StakeManagerStorage} from "./StakeManagerStorage.sol";
                    import {StakeManagerStorageExtension} from "./StakeManagerStorageExtension.sol";
                    import {Math} from "openzeppelin-solidity/contracts/math/Math.sol";
                    import {Initializable} from "../../common/mixin/Initializable.sol";
                    import {EventsHub} from "../EventsHub.sol";
                    import {ValidatorShare} from "../validatorShare/ValidatorShare.sol";
                    contract StakeManagerExtension is StakeManagerStorage, Initializable, StakeManagerStorageExtension {
                        using SafeMath for uint256;
                        constructor() public GovernanceLockable(address(0x0)) {}
                        function startAuction(
                            uint256 validatorId,
                            uint256 amount,
                            bool _acceptDelegation,
                            bytes calldata _signerPubkey
                        ) external {
                            uint256 currentValidatorAmount = validators[validatorId].amount;
                            require(
                                validators[validatorId].deactivationEpoch == 0 && currentValidatorAmount != 0,
                                "Invalid validator for an auction"
                            );
                            uint256 senderValidatorId = signerToValidator[msg.sender];
                            // make sure that signer wasn't used already
                            require(
                                NFTContract.balanceOf(msg.sender) == 0 && // existing validators can't bid
                                    senderValidatorId != INCORRECT_VALIDATOR_ID,
                                "Already used address"
                            );
                            uint256 _currentEpoch = currentEpoch;
                            uint256 _replacementCoolDown = replacementCoolDown;
                            // when dynasty period is updated validators are in cooldown period
                            require(_replacementCoolDown == 0 || _replacementCoolDown <= _currentEpoch, "Cooldown period");
                            // (auctionPeriod--dynasty)--(auctionPeriod--dynasty)--(auctionPeriod--dynasty)
                            // if it's auctionPeriod then will get residue smaller then auctionPeriod
                            // from (CurrentPeriod of validator )%(auctionPeriod--dynasty)
                            // make sure that its `auctionPeriod` window
                            // dynasty = 30, auctionPeriod = 7, activationEpoch = 1, currentEpoch = 39
                            // residue 1 = (39-1)% (7+30), if residue <= auctionPeriod it's `auctionPeriod`
                            require(
                                (_currentEpoch.sub(validators[validatorId].activationEpoch) % dynasty.add(auctionPeriod)) < auctionPeriod,
                                "Invalid auction period"
                            );
                            uint256 perceivedStake = currentValidatorAmount;
                            perceivedStake = perceivedStake.add(validators[validatorId].delegatedAmount);
                            Auction storage auction = validatorAuction[validatorId];
                            uint256 currentAuctionAmount = auction.amount;
                            perceivedStake = Math.max(perceivedStake, currentAuctionAmount);
                            require(perceivedStake < amount, "Must bid higher");
                            require(token.transferFrom(msg.sender, address(this), amount), "Transfer failed");
                            //replace prev auction
                            if (currentAuctionAmount != 0) {
                                require(token.transfer(auction.user, currentAuctionAmount), "Bid return failed");
                            }
                            // create new auction
                            auction.amount = amount;
                            auction.user = msg.sender;
                            auction.acceptDelegation = _acceptDelegation;
                            auction.signerPubkey = _signerPubkey;
                            logger.logStartAuction(validatorId, currentValidatorAmount, amount);
                        }
                        function confirmAuctionBid(
                            uint256 validatorId,
                            uint256 heimdallFee, /** for new validator */
                            IStakeManager stakeManager
                        ) external {
                            Auction storage auction = validatorAuction[validatorId];
                            address auctionUser = auction.user;
                            require(
                                msg.sender == auctionUser || NFTContract.tokenOfOwnerByIndex(msg.sender, 0) == validatorId,
                                "Only bidder can confirm"
                            );
                            uint256 _currentEpoch = currentEpoch;
                            require(
                                _currentEpoch.sub(auction.startEpoch) % auctionPeriod.add(dynasty) >= auctionPeriod,
                                "Not allowed before auctionPeriod"
                            );
                            require(auction.user != address(0x0), "Invalid auction");
                            uint256 validatorAmount = validators[validatorId].amount;
                            uint256 perceivedStake = validatorAmount;
                            uint256 auctionAmount = auction.amount;
                            perceivedStake = perceivedStake.add(validators[validatorId].delegatedAmount);
                            // validator is last auctioner
                            if (perceivedStake >= auctionAmount && validators[validatorId].deactivationEpoch == 0) {
                                require(token.transfer(auctionUser, auctionAmount), "Bid return failed");
                                //cleanup auction data
                                auction.startEpoch = _currentEpoch;
                                logger.logConfirmAuction(validatorId, validatorId, validatorAmount);
                            } else {
                                stakeManager.dethroneAndStake(
                                    auctionUser, 
                                    heimdallFee,
                                    validatorId,
                                    auctionAmount,
                                    auction.acceptDelegation,
                                    auction.signerPubkey
                                );
                            }
                            uint256 startEpoch = auction.startEpoch;
                            delete validatorAuction[validatorId];
                            validatorAuction[validatorId].startEpoch = startEpoch;
                        }
                        function migrateValidatorsData(uint256 validatorIdFrom, uint256 validatorIdTo) external {       
                            for (uint256 i = validatorIdFrom; i < validatorIdTo; ++i) {
                                ValidatorShare contractAddress = ValidatorShare(validators[i].contractAddress);
                                if (contractAddress != ValidatorShare(0)) {
                                    // move validator rewards out from ValidatorShare contract
                                    validators[i].reward = contractAddress.validatorRewards_deprecated().add(INITIALIZED_AMOUNT);
                                    validators[i].delegatedAmount = contractAddress.activeAmount();
                                    validators[i].commissionRate = contractAddress.commissionRate_deprecated();
                                } else {
                                    validators[i].reward = validators[i].reward.add(INITIALIZED_AMOUNT);
                                }
                                validators[i].delegatorsReward = INITIALIZED_AMOUNT;
                            }
                        }
                        function updateCheckpointRewardParams(
                            uint256 _rewardDecreasePerCheckpoint,
                            uint256 _maxRewardedCheckpoints,
                            uint256 _checkpointRewardDelta
                        ) external {
                            require(_maxRewardedCheckpoints.mul(_rewardDecreasePerCheckpoint) <= CHK_REWARD_PRECISION);
                            require(_checkpointRewardDelta <= CHK_REWARD_PRECISION);
                            rewardDecreasePerCheckpoint = _rewardDecreasePerCheckpoint;
                            maxRewardedCheckpoints = _maxRewardedCheckpoints;
                            checkpointRewardDelta = _checkpointRewardDelta;
                            _getOrCacheEventsHub().logRewardParams(_rewardDecreasePerCheckpoint, _maxRewardedCheckpoints, _checkpointRewardDelta);
                        }
                        function updateCommissionRate(uint256 validatorId, uint256 newCommissionRate) external {
                            uint256 _epoch = currentEpoch;
                            uint256 _lastCommissionUpdate = validators[validatorId].lastCommissionUpdate;
                            require( // withdrawalDelay == dynasty
                                (_lastCommissionUpdate.add(WITHDRAWAL_DELAY) <= _epoch) || _lastCommissionUpdate == 0, // For initial setting of commission rate
                                "Cooldown"
                            );
                            require(newCommissionRate <= MAX_COMMISION_RATE, "Incorrect value");
                            _getOrCacheEventsHub().logUpdateCommissionRate(validatorId, newCommissionRate, validators[validatorId].commissionRate);
                            validators[validatorId].commissionRate = newCommissionRate;
                            validators[validatorId].lastCommissionUpdate = _epoch;
                        }
                        function _getOrCacheEventsHub() private returns(EventsHub) {
                            EventsHub _eventsHub = EventsHub(eventsHub);
                            if (_eventsHub == EventsHub(0x0)) {
                                _eventsHub = EventsHub(Registry(registry).contractMap(keccak256("eventsHub")));
                                eventsHub = address(_eventsHub);
                            }
                            return _eventsHub;
                        }
                    }
                    pragma solidity 0.5.17;
                    interface IPolygonMigration {
                        event Migrated(address indexed account, uint256 amount);
                        event Unmigrated(address indexed account, address indexed recipient, uint256 amount);
                        event UnmigrationLockUpdated(bool lock);
                        
                        function migrate(uint256 amount) external;
                        function unmigrate(uint256 amount) external;
                    }
                    pragma solidity ^0.5.2;
                    import {IGovernance} from "./IGovernance.sol";
                    contract Governable {
                        IGovernance public governance;
                        constructor(address _governance) public {
                            governance = IGovernance(_governance);
                        }
                        modifier onlyGovernance() {
                            _assertGovernance();
                            _;
                        }
                        function _assertGovernance() private view {
                            require(
                                msg.sender == address(governance),
                                "Only governance contract is authorized"
                            );
                        }
                    }
                    pragma solidity ^0.5.2;
                    contract Lockable {
                        bool public locked;
                        modifier onlyWhenUnlocked() {
                            _assertUnlocked();
                            _;
                        }
                        function _assertUnlocked() private view {
                            require(!locked, "locked");
                        }
                        function lock() public {
                            locked = true;
                        }
                        function unlock() public {
                            locked = false;
                        }
                    }
                    pragma solidity ^0.5.2;
                    contract IWithdrawManager {
                        function createExitQueue(address token) external;
                        function verifyInclusion(
                            bytes calldata data,
                            uint8 offset,
                            bool verifyTxInclusion
                        ) external view returns (uint256 age);
                        function addExitToQueue(
                            address exitor,
                            address childToken,
                            address rootToken,
                            uint256 exitAmountOrTokenId,
                            bytes32 txHash,
                            bool isRegularExit,
                            uint256 priority
                        ) external;
                        function addInput(
                            uint256 exitId,
                            uint256 age,
                            address utxoOwner,
                            address token
                        ) external;
                        function challengeExit(
                            uint256 exitId,
                            uint256 inputId,
                            bytes calldata challengeData,
                            address adjudicatorPredicate
                        ) external;
                    }
                    pragma solidity ^0.5.2;
                    import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
                    contract ERC20NonTradable is ERC20 {
                        function _approve(
                            address owner,
                            address spender,
                            uint256 value
                        ) internal {
                            revert("disabled");
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC20.sol";
                    import "../../math/SafeMath.sol";
                    /**
                     * @title Standard ERC20 token
                     *
                     * @dev Implementation of the basic standard token.
                     * https://eips.ethereum.org/EIPS/eip-20
                     * Originally based on code by FirstBlood:
                     * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
                     *
                     * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
                     * all accounts just by listening to said events. Note that this isn't required by the specification, and other
                     * compliant implementations may not do it.
                     */
                    contract ERC20 is IERC20 {
                        using SafeMath for uint256;
                        mapping (address => uint256) private _balances;
                        mapping (address => mapping (address => uint256)) private _allowed;
                        uint256 private _totalSupply;
                        /**
                         * @dev Total number of tokens in existence
                         */
                        function totalSupply() public view returns (uint256) {
                            return _totalSupply;
                        }
                        /**
                         * @dev Gets the balance of the specified address.
                         * @param owner The address to query the balance of.
                         * @return A uint256 representing the amount owned by the passed address.
                         */
                        function balanceOf(address owner) public view returns (uint256) {
                            return _balances[owner];
                        }
                        /**
                         * @dev Function to check the amount of tokens that an owner allowed to a spender.
                         * @param owner address The address which owns the funds.
                         * @param spender address The address which will spend the funds.
                         * @return A uint256 specifying the amount of tokens still available for the spender.
                         */
                        function allowance(address owner, address spender) public view returns (uint256) {
                            return _allowed[owner][spender];
                        }
                        /**
                         * @dev Transfer token to a specified address
                         * @param to The address to transfer to.
                         * @param value The amount to be transferred.
                         */
                        function transfer(address to, uint256 value) public returns (bool) {
                            _transfer(msg.sender, to, value);
                            return true;
                        }
                        /**
                         * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                         * Beware that changing an allowance with this method brings the risk that someone may use both the old
                         * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
                         * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         * @param spender The address which will spend the funds.
                         * @param value The amount of tokens to be spent.
                         */
                        function approve(address spender, uint256 value) public returns (bool) {
                            _approve(msg.sender, spender, value);
                            return true;
                        }
                        /**
                         * @dev Transfer tokens from one address to another.
                         * Note that while this function emits an Approval event, this is not required as per the specification,
                         * and other compliant implementations may not emit the event.
                         * @param from address The address which you want to send tokens from
                         * @param to address The address which you want to transfer to
                         * @param value uint256 the amount of tokens to be transferred
                         */
                        function transferFrom(address from, address to, uint256 value) public returns (bool) {
                            _transfer(from, to, value);
                            _approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
                            return true;
                        }
                        /**
                         * @dev Increase the amount of tokens that an owner allowed to a spender.
                         * approve should be called when _allowed[msg.sender][spender] == 0. To increment
                         * allowed value is better to use this function to avoid 2 calls (and wait until
                         * the first transaction is mined)
                         * From MonolithDAO Token.sol
                         * Emits an Approval event.
                         * @param spender The address which will spend the funds.
                         * @param addedValue The amount of tokens to increase the allowance by.
                         */
                        function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
                            _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
                            return true;
                        }
                        /**
                         * @dev Decrease the amount of tokens that an owner allowed to a spender.
                         * approve should be called when _allowed[msg.sender][spender] == 0. To decrement
                         * allowed value is better to use this function to avoid 2 calls (and wait until
                         * the first transaction is mined)
                         * From MonolithDAO Token.sol
                         * Emits an Approval event.
                         * @param spender The address which will spend the funds.
                         * @param subtractedValue The amount of tokens to decrease the allowance by.
                         */
                        function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
                            _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
                            return true;
                        }
                        /**
                         * @dev Transfer token for a specified addresses
                         * @param from The address to transfer from.
                         * @param to The address to transfer to.
                         * @param value The amount to be transferred.
                         */
                        function _transfer(address from, address to, uint256 value) internal {
                            require(to != address(0));
                            _balances[from] = _balances[from].sub(value);
                            _balances[to] = _balances[to].add(value);
                            emit Transfer(from, to, value);
                        }
                        /**
                         * @dev Internal function that mints an amount of the token and assigns it to
                         * an account. This encapsulates the modification of balances such that the
                         * proper events are emitted.
                         * @param account The account that will receive the created tokens.
                         * @param value The amount that will be created.
                         */
                        function _mint(address account, uint256 value) internal {
                            require(account != address(0));
                            _totalSupply = _totalSupply.add(value);
                            _balances[account] = _balances[account].add(value);
                            emit Transfer(address(0), account, value);
                        }
                        /**
                         * @dev Internal function that burns an amount of the token of a given
                         * account.
                         * @param account The account whose tokens will be burnt.
                         * @param value The amount that will be burnt.
                         */
                        function _burn(address account, uint256 value) internal {
                            require(account != address(0));
                            _totalSupply = _totalSupply.sub(value);
                            _balances[account] = _balances[account].sub(value);
                            emit Transfer(account, address(0), value);
                        }
                        /**
                         * @dev Approve an address to spend another addresses' tokens.
                         * @param owner The address that owns the tokens.
                         * @param spender The address that will spend the tokens.
                         * @param value The number of tokens that can be spent.
                         */
                        function _approve(address owner, address spender, uint256 value) internal {
                            require(spender != address(0));
                            require(owner != address(0));
                            _allowed[owner][spender] = value;
                            emit Approval(owner, spender, value);
                        }
                        /**
                         * @dev Internal function that burns an amount of the token of a given
                         * account, deducting from the sender's allowance for said account. Uses the
                         * internal burn function.
                         * Emits an Approval event (reflecting the reduced allowance).
                         * @param account The account whose tokens will be burnt.
                         * @param value The amount that will be burnt.
                         */
                        function _burnFrom(address account, uint256 value) internal {
                            _burn(account, value);
                            _approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Registry} from "../common/Registry.sol";
                    import {Initializable} from "../common/mixin/Initializable.sol";
                    contract IStakeManagerEventsHub {
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                        }
                        mapping(uint256 => Validator) public validators;
                    }
                    contract EventsHub is Initializable {
                        Registry public registry;
                        modifier onlyValidatorContract(uint256 validatorId) {
                            address _contract;
                            (, , , , , , _contract) = IStakeManagerEventsHub(registry.getStakeManagerAddress()).validators(validatorId);
                            require(_contract == msg.sender, "not validator");
                            _;
                        }
                        modifier onlyStakeManager() {
                            require(registry.getStakeManagerAddress() == msg.sender,
                            "Invalid sender, not stake manager");
                            _;
                        }
                        function initialize(Registry _registry) external initializer {
                            registry = _registry;
                        }
                        event ShareBurnedWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens,
                            uint256 nonce
                        );
                        function logShareBurnedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareBurnedWithId(validatorId, user, amount, tokens, nonce);
                        }
                        event DelegatorUnstakeWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 amount,
                            uint256 nonce
                        );
                        function logDelegatorUnstakedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorUnstakeWithId(validatorId, user, amount, nonce);
                        }
                        event RewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        );
                        function logRewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        ) public onlyStakeManager {
                            emit RewardParams(rewardDecreasePerCheckpoint, maxRewardedCheckpoints, checkpointRewardDelta);
                        }
                        event UpdateCommissionRate(
                            uint256 indexed validatorId,
                            uint256 indexed newCommissionRate,
                            uint256 indexed oldCommissionRate
                        );
                        function logUpdateCommissionRate(
                            uint256 validatorId,
                            uint256 newCommissionRate,
                            uint256 oldCommissionRate
                        ) public onlyStakeManager {
                            emit UpdateCommissionRate(
                                validatorId,
                                newCommissionRate,
                                oldCommissionRate
                            );
                        }
                        event SharesTransfer(
                            uint256 indexed validatorId,
                            address indexed from,
                            address indexed to,
                            uint256 value
                        );
                        function logSharesTransfer(
                            uint256 validatorId,
                            address from,
                            address to,
                            uint256 value
                        ) public onlyValidatorContract(validatorId) {
                            emit SharesTransfer(validatorId, from, to, value);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import { Lockable } from "./Lockable.sol";
                    import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    contract OwnableLockable is Lockable, Ownable {
                        function lock() public onlyOwner {
                            super.lock();
                        }
                        function unlock() public onlyOwner {
                            super.unlock();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity 0.5.17;
                    interface IERC20Permit {
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                        function nonces(address owner) external view returns (uint256);
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title Ownable
                     * @dev The Ownable contract has an owner address, and provides basic authorization control
                     * functions, this simplifies the implementation of "user permissions".
                     */
                    contract Ownable {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                         * account.
                         */
                        constructor () internal {
                            _owner = msg.sender;
                            emit OwnershipTransferred(address(0), _owner);
                        }
                        /**
                         * @return the address of the owner.
                         */
                        function owner() public view returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(isOwner());
                            _;
                        }
                        /**
                         * @return true if `msg.sender` is the owner of the contract.
                         */
                        function isOwner() public view returns (bool) {
                            return msg.sender == _owner;
                        }
                        /**
                         * @dev Allows the current owner to relinquish control of the contract.
                         * It will not be possible to call the functions with the `onlyOwner`
                         * modifier anymore.
                         * @notice Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                        /**
                         * @dev Allows the current owner to transfer control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function transferOwnership(address newOwner) public onlyOwner {
                            _transferOwnership(newOwner);
                        }
                        /**
                         * @dev Transfers control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function _transferOwnership(address newOwner) internal {
                            require(newOwner != address(0));
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./ERC721.sol";
                    import "./ERC721Enumerable.sol";
                    import "./ERC721Metadata.sol";
                    /**
                     * @title Full ERC721 Token
                     * This implementation includes all the required and some optional functionality of the ERC721 standard
                     * Moreover, it includes approve all functionality using operator terminology
                     * @dev see https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
                        constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
                            // solhint-disable-previous-line no-empty-blocks
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {UpgradableProxy} from "../../common/misc/UpgradableProxy.sol";
                    import {Registry} from "../../common/Registry.sol";
                    contract ValidatorShareProxy is UpgradableProxy {
                        constructor(address _registry) public UpgradableProxy(_registry) {}
                        function loadImplementation() internal view returns (address) {
                            return Registry(super.loadImplementation()).getValidatorShareAddress();
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
                    /**
                     * @title RootChainable
                     */
                    contract RootChainable is Ownable {
                        address public rootChain;
                        // Rootchain changed
                        event RootChainChanged(
                            address indexed previousRootChain,
                            address indexed newRootChain
                        );
                        // only root chain
                        modifier onlyRootChain() {
                            require(msg.sender == rootChain);
                            _;
                        }
                        /**
                       * @dev Allows the current owner to change root chain address.
                       * @param newRootChain The address to new rootchain.
                       */
                        function changeRootChain(address newRootChain) public onlyOwner {
                            require(newRootChain != address(0));
                            emit RootChainChanged(rootChain, newRootChain);
                            rootChain = newRootChain;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC721.sol";
                    import "./IERC721Receiver.sol";
                    import "../../math/SafeMath.sol";
                    import "../../utils/Address.sol";
                    import "../../drafts/Counters.sol";
                    import "../../introspection/ERC165.sol";
                    /**
                     * @title ERC721 Non-Fungible Token Standard basic implementation
                     * @dev see https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract ERC721 is ERC165, IERC721 {
                        using SafeMath for uint256;
                        using Address for address;
                        using Counters for Counters.Counter;
                        // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
                        // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
                        bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
                        // Mapping from token ID to owner
                        mapping (uint256 => address) private _tokenOwner;
                        // Mapping from token ID to approved address
                        mapping (uint256 => address) private _tokenApprovals;
                        // Mapping from owner to number of owned token
                        mapping (address => Counters.Counter) private _ownedTokensCount;
                        // Mapping from owner to operator approvals
                        mapping (address => mapping (address => bool)) private _operatorApprovals;
                        bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
                        /*
                         * 0x80ac58cd ===
                         *     bytes4(keccak256('balanceOf(address)')) ^
                         *     bytes4(keccak256('ownerOf(uint256)')) ^
                         *     bytes4(keccak256('approve(address,uint256)')) ^
                         *     bytes4(keccak256('getApproved(uint256)')) ^
                         *     bytes4(keccak256('setApprovalForAll(address,bool)')) ^
                         *     bytes4(keccak256('isApprovedForAll(address,address)')) ^
                         *     bytes4(keccak256('transferFrom(address,address,uint256)')) ^
                         *     bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
                         *     bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
                         */
                        constructor () public {
                            // register the supported interfaces to conform to ERC721 via ERC165
                            _registerInterface(_INTERFACE_ID_ERC721);
                        }
                        /**
                         * @dev Gets the balance of the specified address
                         * @param owner address to query the balance of
                         * @return uint256 representing the amount owned by the passed address
                         */
                        function balanceOf(address owner) public view returns (uint256) {
                            require(owner != address(0));
                            return _ownedTokensCount[owner].current();
                        }
                        /**
                         * @dev Gets the owner of the specified token ID
                         * @param tokenId uint256 ID of the token to query the owner of
                         * @return address currently marked as the owner of the given token ID
                         */
                        function ownerOf(uint256 tokenId) public view returns (address) {
                            address owner = _tokenOwner[tokenId];
                            require(owner != address(0));
                            return owner;
                        }
                        /**
                         * @dev Approves another address to transfer the given token ID
                         * The zero address indicates there is no approved address.
                         * There can only be one approved address per token at a given time.
                         * Can only be called by the token owner or an approved operator.
                         * @param to address to be approved for the given token ID
                         * @param tokenId uint256 ID of the token to be approved
                         */
                        function approve(address to, uint256 tokenId) public {
                            address owner = ownerOf(tokenId);
                            require(to != owner);
                            require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
                            _tokenApprovals[tokenId] = to;
                            emit Approval(owner, to, tokenId);
                        }
                        /**
                         * @dev Gets the approved address for a token ID, or zero if no address set
                         * Reverts if the token ID does not exist.
                         * @param tokenId uint256 ID of the token to query the approval of
                         * @return address currently approved for the given token ID
                         */
                        function getApproved(uint256 tokenId) public view returns (address) {
                            require(_exists(tokenId));
                            return _tokenApprovals[tokenId];
                        }
                        /**
                         * @dev Sets or unsets the approval of a given operator
                         * An operator is allowed to transfer all tokens of the sender on their behalf
                         * @param to operator address to set the approval
                         * @param approved representing the status of the approval to be set
                         */
                        function setApprovalForAll(address to, bool approved) public {
                            require(to != msg.sender);
                            _operatorApprovals[msg.sender][to] = approved;
                            emit ApprovalForAll(msg.sender, to, approved);
                        }
                        /**
                         * @dev Tells whether an operator is approved by a given owner
                         * @param owner owner address which you want to query the approval of
                         * @param operator operator address which you want to query the approval of
                         * @return bool whether the given operator is approved by the given owner
                         */
                        function isApprovedForAll(address owner, address operator) public view returns (bool) {
                            return _operatorApprovals[owner][operator];
                        }
                        /**
                         * @dev Transfers the ownership of a given token ID to another address
                         * Usage of this method is discouraged, use `safeTransferFrom` whenever possible
                         * Requires the msg.sender to be the owner, approved, or operator
                         * @param from current owner of the token
                         * @param to address to receive the ownership of the given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         */
                        function transferFrom(address from, address to, uint256 tokenId) public {
                            require(_isApprovedOrOwner(msg.sender, tokenId));
                            _transferFrom(from, to, tokenId);
                        }
                        /**
                         * @dev Safely transfers the ownership of a given token ID to another address
                         * If the target address is a contract, it must implement `onERC721Received`,
                         * which is called upon a safe transfer, and return the magic value
                         * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
                         * the transfer is reverted.
                         * Requires the msg.sender to be the owner, approved, or operator
                         * @param from current owner of the token
                         * @param to address to receive the ownership of the given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         */
                        function safeTransferFrom(address from, address to, uint256 tokenId) public {
                            safeTransferFrom(from, to, tokenId, "");
                        }
                        /**
                         * @dev Safely transfers the ownership of a given token ID to another address
                         * If the target address is a contract, it must implement `onERC721Received`,
                         * which is called upon a safe transfer, and return the magic value
                         * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
                         * the transfer is reverted.
                         * Requires the msg.sender to be the owner, approved, or operator
                         * @param from current owner of the token
                         * @param to address to receive the ownership of the given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         * @param _data bytes data to send along with a safe transfer check
                         */
                        function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
                            transferFrom(from, to, tokenId);
                            require(_checkOnERC721Received(from, to, tokenId, _data));
                        }
                        /**
                         * @dev Returns whether the specified token exists
                         * @param tokenId uint256 ID of the token to query the existence of
                         * @return bool whether the token exists
                         */
                        function _exists(uint256 tokenId) internal view returns (bool) {
                            address owner = _tokenOwner[tokenId];
                            return owner != address(0);
                        }
                        /**
                         * @dev Returns whether the given spender can transfer a given token ID
                         * @param spender address of the spender to query
                         * @param tokenId uint256 ID of the token to be transferred
                         * @return bool whether the msg.sender is approved for the given token ID,
                         * is an operator of the owner, or is the owner of the token
                         */
                        function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
                            address owner = ownerOf(tokenId);
                            return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
                        }
                        /**
                         * @dev Internal function to mint a new token
                         * Reverts if the given token ID already exists
                         * @param to The address that will own the minted token
                         * @param tokenId uint256 ID of the token to be minted
                         */
                        function _mint(address to, uint256 tokenId) internal {
                            require(to != address(0));
                            require(!_exists(tokenId));
                            _tokenOwner[tokenId] = to;
                            _ownedTokensCount[to].increment();
                            emit Transfer(address(0), to, tokenId);
                        }
                        /**
                         * @dev Internal function to burn a specific token
                         * Reverts if the token does not exist
                         * Deprecated, use _burn(uint256) instead.
                         * @param owner owner of the token to burn
                         * @param tokenId uint256 ID of the token being burned
                         */
                        function _burn(address owner, uint256 tokenId) internal {
                            require(ownerOf(tokenId) == owner);
                            _clearApproval(tokenId);
                            _ownedTokensCount[owner].decrement();
                            _tokenOwner[tokenId] = address(0);
                            emit Transfer(owner, address(0), tokenId);
                        }
                        /**
                         * @dev Internal function to burn a specific token
                         * Reverts if the token does not exist
                         * @param tokenId uint256 ID of the token being burned
                         */
                        function _burn(uint256 tokenId) internal {
                            _burn(ownerOf(tokenId), tokenId);
                        }
                        /**
                         * @dev Internal function to transfer ownership of a given token ID to another address.
                         * As opposed to transferFrom, this imposes no restrictions on msg.sender.
                         * @param from current owner of the token
                         * @param to address to receive the ownership of the given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         */
                        function _transferFrom(address from, address to, uint256 tokenId) internal {
                            require(ownerOf(tokenId) == from);
                            require(to != address(0));
                            _clearApproval(tokenId);
                            _ownedTokensCount[from].decrement();
                            _ownedTokensCount[to].increment();
                            _tokenOwner[tokenId] = to;
                            emit Transfer(from, to, tokenId);
                        }
                        /**
                         * @dev Internal function to invoke `onERC721Received` on a target address
                         * The call is not executed if the target address is not a contract
                         * @param from address representing the previous owner of the given token ID
                         * @param to target address that will receive the tokens
                         * @param tokenId uint256 ID of the token to be transferred
                         * @param _data bytes optional data to send along with the call
                         * @return bool whether the call correctly returned the expected magic value
                         */
                        function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
                            internal returns (bool)
                        {
                            if (!to.isContract()) {
                                return true;
                            }
                            bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
                            return (retval == _ERC721_RECEIVED);
                        }
                        /**
                         * @dev Private function to clear current approval of a given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         */
                        function _clearApproval(uint256 tokenId) private {
                            if (_tokenApprovals[tokenId] != address(0)) {
                                _tokenApprovals[tokenId] = address(0);
                            }
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC721Enumerable.sol";
                    import "./ERC721.sol";
                    import "../../introspection/ERC165.sol";
                    /**
                     * @title ERC-721 Non-Fungible Token with optional enumeration extension logic
                     * @dev See https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
                        // Mapping from owner to list of owned token IDs
                        mapping(address => uint256[]) private _ownedTokens;
                        // Mapping from token ID to index of the owner tokens list
                        mapping(uint256 => uint256) private _ownedTokensIndex;
                        // Array with all token ids, used for enumeration
                        uint256[] private _allTokens;
                        // Mapping from token id to position in the allTokens array
                        mapping(uint256 => uint256) private _allTokensIndex;
                        bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
                        /*
                         * 0x780e9d63 ===
                         *     bytes4(keccak256('totalSupply()')) ^
                         *     bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
                         *     bytes4(keccak256('tokenByIndex(uint256)'))
                         */
                        /**
                         * @dev Constructor function
                         */
                        constructor () public {
                            // register the supported interface to conform to ERC721Enumerable via ERC165
                            _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
                        }
                        /**
                         * @dev Gets the token ID at a given index of the tokens list of the requested owner
                         * @param owner address owning the tokens list to be accessed
                         * @param index uint256 representing the index to be accessed of the requested tokens list
                         * @return uint256 token ID at the given index of the tokens list owned by the requested address
                         */
                        function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
                            require(index < balanceOf(owner));
                            return _ownedTokens[owner][index];
                        }
                        /**
                         * @dev Gets the total amount of tokens stored by the contract
                         * @return uint256 representing the total amount of tokens
                         */
                        function totalSupply() public view returns (uint256) {
                            return _allTokens.length;
                        }
                        /**
                         * @dev Gets the token ID at a given index of all the tokens in this contract
                         * Reverts if the index is greater or equal to the total number of tokens
                         * @param index uint256 representing the index to be accessed of the tokens list
                         * @return uint256 token ID at the given index of the tokens list
                         */
                        function tokenByIndex(uint256 index) public view returns (uint256) {
                            require(index < totalSupply());
                            return _allTokens[index];
                        }
                        /**
                         * @dev Internal function to transfer ownership of a given token ID to another address.
                         * As opposed to transferFrom, this imposes no restrictions on msg.sender.
                         * @param from current owner of the token
                         * @param to address to receive the ownership of the given token ID
                         * @param tokenId uint256 ID of the token to be transferred
                         */
                        function _transferFrom(address from, address to, uint256 tokenId) internal {
                            super._transferFrom(from, to, tokenId);
                            _removeTokenFromOwnerEnumeration(from, tokenId);
                            _addTokenToOwnerEnumeration(to, tokenId);
                        }
                        /**
                         * @dev Internal function to mint a new token
                         * Reverts if the given token ID already exists
                         * @param to address the beneficiary that will own the minted token
                         * @param tokenId uint256 ID of the token to be minted
                         */
                        function _mint(address to, uint256 tokenId) internal {
                            super._mint(to, tokenId);
                            _addTokenToOwnerEnumeration(to, tokenId);
                            _addTokenToAllTokensEnumeration(tokenId);
                        }
                        /**
                         * @dev Internal function to burn a specific token
                         * Reverts if the token does not exist
                         * Deprecated, use _burn(uint256) instead
                         * @param owner owner of the token to burn
                         * @param tokenId uint256 ID of the token being burned
                         */
                        function _burn(address owner, uint256 tokenId) internal {
                            super._burn(owner, tokenId);
                            _removeTokenFromOwnerEnumeration(owner, tokenId);
                            // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
                            _ownedTokensIndex[tokenId] = 0;
                            _removeTokenFromAllTokensEnumeration(tokenId);
                        }
                        /**
                         * @dev Gets the list of token IDs of the requested owner
                         * @param owner address owning the tokens
                         * @return uint256[] List of token IDs owned by the requested address
                         */
                        function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
                            return _ownedTokens[owner];
                        }
                        /**
                         * @dev Private function to add a token to this extension's ownership-tracking data structures.
                         * @param to address representing the new owner of the given token ID
                         * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
                         */
                        function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
                            _ownedTokensIndex[tokenId] = _ownedTokens[to].length;
                            _ownedTokens[to].push(tokenId);
                        }
                        /**
                         * @dev Private function to add a token to this extension's token tracking data structures.
                         * @param tokenId uint256 ID of the token to be added to the tokens list
                         */
                        function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
                            _allTokensIndex[tokenId] = _allTokens.length;
                            _allTokens.push(tokenId);
                        }
                        /**
                         * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
                         * while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
                         * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
                         * This has O(1) time complexity, but alters the order of the _ownedTokens array.
                         * @param from address representing the previous owner of the given token ID
                         * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
                         */
                        function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
                            // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
                            // then delete the last slot (swap and pop).
                            uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
                            uint256 tokenIndex = _ownedTokensIndex[tokenId];
                            // When the token to delete is the last token, the swap operation is unnecessary
                            if (tokenIndex != lastTokenIndex) {
                                uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
                                _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
                                _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
                            }
                            // This also deletes the contents at the last position of the array
                            _ownedTokens[from].length--;
                            // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
                            // lastTokenId, or just over the end of the array if the token was the last one).
                        }
                        /**
                         * @dev Private function to remove a token from this extension's token tracking data structures.
                         * This has O(1) time complexity, but alters the order of the _allTokens array.
                         * @param tokenId uint256 ID of the token to be removed from the tokens list
                         */
                        function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
                            // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
                            // then delete the last slot (swap and pop).
                            uint256 lastTokenIndex = _allTokens.length.sub(1);
                            uint256 tokenIndex = _allTokensIndex[tokenId];
                            // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
                            // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
                            // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
                            uint256 lastTokenId = _allTokens[lastTokenIndex];
                            _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
                            _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
                            // This also deletes the contents at the last position of the array
                            _allTokens.length--;
                            _allTokensIndex[tokenId] = 0;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./ERC721.sol";
                    import "./IERC721Metadata.sol";
                    import "../../introspection/ERC165.sol";
                    contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
                        // Token name
                        string private _name;
                        // Token symbol
                        string private _symbol;
                        // Optional mapping for token URIs
                        mapping(uint256 => string) private _tokenURIs;
                        bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
                        /*
                         * 0x5b5e139f ===
                         *     bytes4(keccak256('name()')) ^
                         *     bytes4(keccak256('symbol()')) ^
                         *     bytes4(keccak256('tokenURI(uint256)'))
                         */
                        /**
                         * @dev Constructor function
                         */
                        constructor (string memory name, string memory symbol) public {
                            _name = name;
                            _symbol = symbol;
                            // register the supported interfaces to conform to ERC721 via ERC165
                            _registerInterface(_INTERFACE_ID_ERC721_METADATA);
                        }
                        /**
                         * @dev Gets the token name
                         * @return string representing the token name
                         */
                        function name() external view returns (string memory) {
                            return _name;
                        }
                        /**
                         * @dev Gets the token symbol
                         * @return string representing the token symbol
                         */
                        function symbol() external view returns (string memory) {
                            return _symbol;
                        }
                        /**
                         * @dev Returns an URI for a given token ID
                         * Throws if the token ID does not exist. May return an empty string.
                         * @param tokenId uint256 ID of the token to query
                         */
                        function tokenURI(uint256 tokenId) external view returns (string memory) {
                            require(_exists(tokenId));
                            return _tokenURIs[tokenId];
                        }
                        /**
                         * @dev Internal function to set the token URI for a given token
                         * Reverts if the token ID does not exist
                         * @param tokenId uint256 ID of the token to set its URI
                         * @param uri string URI to assign
                         */
                        function _setTokenURI(uint256 tokenId, string memory uri) internal {
                            require(_exists(tokenId));
                            _tokenURIs[tokenId] = uri;
                        }
                        /**
                         * @dev Internal function to burn a specific token
                         * Reverts if the token does not exist
                         * Deprecated, use _burn(uint256) instead
                         * @param owner owner of the token to burn
                         * @param tokenId uint256 ID of the token being burned by the msg.sender
                         */
                        function _burn(address owner, uint256 tokenId) internal {
                            super._burn(owner, tokenId);
                            // Clear metadata (if any)
                            if (bytes(_tokenURIs[tokenId]).length != 0) {
                                delete _tokenURIs[tokenId];
                            }
                        }
                    }
                    pragma solidity ^0.5.2;
                    import {DelegateProxy} from "./DelegateProxy.sol";
                    contract UpgradableProxy is DelegateProxy {
                        event ProxyUpdated(address indexed _new, address indexed _old);
                        event OwnerUpdate(address _new, address _old);
                        bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation");
                        bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner");
                        constructor(address _proxyTo) public {
                            setOwner(msg.sender);
                            setImplementation(_proxyTo);
                        }
                        function() external payable {
                            // require(currentContract != 0, "If app code has not been set yet, do not call");
                            // Todo: filter out some calls or handle in the end fallback
                            delegatedFwd(loadImplementation(), msg.data);
                        }
                        modifier onlyProxyOwner() {
                            require(loadOwner() == msg.sender, "NOT_OWNER");
                            _;
                        }
                        function owner() external view returns(address) {
                            return loadOwner();
                        }
                        function loadOwner() internal view returns(address) {
                            address _owner;
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                _owner := sload(position)
                            }
                            return _owner;
                        }
                        function implementation() external view returns (address) {
                            return loadImplementation();
                        }
                        function loadImplementation() internal view returns(address) {
                            address _impl;
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                _impl := sload(position)
                            }
                            return _impl;
                        }
                        function transferOwnership(address newOwner) public onlyProxyOwner {
                            require(newOwner != address(0), "ZERO_ADDRESS");
                            emit OwnerUpdate(newOwner, loadOwner());
                            setOwner(newOwner);
                        }
                        function setOwner(address newOwner) private {
                            bytes32 position = OWNER_SLOT;
                            assembly {
                                sstore(position, newOwner)
                            }
                        }
                        function updateImplementation(address _newProxyTo) public onlyProxyOwner {
                            require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS");
                            require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT");
                            emit ProxyUpdated(_newProxyTo, loadImplementation());
                            
                            setImplementation(_newProxyTo);
                        }
                        function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner {
                            updateImplementation(_newProxyTo);
                            (bool success, bytes memory returnData) = address(this).call.value(msg.value)(data);
                            require(success, string(returnData));
                        }
                        function setImplementation(address _newProxyTo) private {
                            bytes32 position = IMPLEMENTATION_SLOT;
                            assembly {
                                sstore(position, _newProxyTo)
                            }
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "../../introspection/IERC165.sol";
                    /**
                     * @title ERC721 Non-Fungible Token Standard basic interface
                     * @dev see https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract IERC721 is IERC165 {
                        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
                        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
                        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                        function balanceOf(address owner) public view returns (uint256 balance);
                        function ownerOf(uint256 tokenId) public view returns (address owner);
                        function approve(address to, uint256 tokenId) public;
                        function getApproved(uint256 tokenId) public view returns (address operator);
                        function setApprovalForAll(address operator, bool _approved) public;
                        function isApprovedForAll(address owner, address operator) public view returns (bool);
                        function transferFrom(address from, address to, uint256 tokenId) public;
                        function safeTransferFrom(address from, address to, uint256 tokenId) public;
                        function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title ERC721 token receiver interface
                     * @dev Interface for any contract that wants to support safeTransfers
                     * from ERC721 asset contracts.
                     */
                    contract IERC721Receiver {
                        /**
                         * @notice Handle the receipt of an NFT
                         * @dev The ERC721 smart contract calls this function on the recipient
                         * after a `safeTransfer`. This function MUST return the function selector,
                         * otherwise the caller will revert the transaction. The selector to be
                         * returned can be obtained as `this.onERC721Received.selector`. This
                         * function MAY throw to revert and reject the transfer.
                         * Note: the ERC721 contract address is always the message sender.
                         * @param operator The address which called `safeTransferFrom` function
                         * @param from The address which previously owned the token
                         * @param tokenId The NFT identifier which is being transferred
                         * @param data Additional data with no specified format
                         * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
                         */
                        function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
                        public returns (bytes4);
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * Utility library of inline functions on addresses
                     */
                    library Address {
                        /**
                         * Returns whether the target address is a contract
                         * @dev This function will return false if invoked during the constructor of a contract,
                         * as the code is not actually created until after the constructor finishes.
                         * @param account address of the account to check
                         * @return whether the target address is a contract
                         */
                        function isContract(address account) internal view returns (bool) {
                            uint256 size;
                            // XXX Currently there is no better way to check if there is a contract in an address
                            // than to check the size of the code at that address.
                            // See https://ethereum.stackexchange.com/a/14016/36603
                            // for more details about how this works.
                            // TODO Check this again before the Serenity release, because all addresses will be
                            // contracts then.
                            // solhint-disable-next-line no-inline-assembly
                            assembly { size := extcodesize(account) }
                            return size > 0;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "../math/SafeMath.sol";
                    /**
                     * @title Counters
                     * @author Matt Condon (@shrugs)
                     * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
                     * of elements in a mapping, issuing ERC721 ids, or counting request ids
                     *
                     * Include with `using Counters for Counters.Counter;`
                     * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
                     * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
                     * directly accessed.
                     */
                    library Counters {
                        using SafeMath for uint256;
                        struct Counter {
                            // This variable should never be directly accessed by users of the library: interactions must be restricted to
                            // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                            // this feature: see https://github.com/ethereum/solidity/issues/4637
                            uint256 _value; // default: 0
                        }
                        function current(Counter storage counter) internal view returns (uint256) {
                            return counter._value;
                        }
                        function increment(Counter storage counter) internal {
                            counter._value += 1;
                        }
                        function decrement(Counter storage counter) internal {
                            counter._value = counter._value.sub(1);
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC165.sol";
                    /**
                     * @title ERC165
                     * @author Matt Condon (@shrugs)
                     * @dev Implements ERC165 using a lookup table.
                     */
                    contract ERC165 is IERC165 {
                        bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
                        /*
                         * 0x01ffc9a7 ===
                         *     bytes4(keccak256('supportsInterface(bytes4)'))
                         */
                        /**
                         * @dev a mapping of interface id to whether or not it's supported
                         */
                        mapping(bytes4 => bool) private _supportedInterfaces;
                        /**
                         * @dev A contract implementing SupportsInterfaceWithLookup
                         * implement ERC165 itself
                         */
                        constructor () internal {
                            _registerInterface(_INTERFACE_ID_ERC165);
                        }
                        /**
                         * @dev implement supportsInterface(bytes4) using a lookup table
                         */
                        function supportsInterface(bytes4 interfaceId) external view returns (bool) {
                            return _supportedInterfaces[interfaceId];
                        }
                        /**
                         * @dev internal method for registering an interface
                         */
                        function _registerInterface(bytes4 interfaceId) internal {
                            require(interfaceId != 0xffffffff);
                            _supportedInterfaces[interfaceId] = true;
                        }
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC721.sol";
                    /**
                     * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
                     * @dev See https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract IERC721Enumerable is IERC721 {
                        function totalSupply() public view returns (uint256);
                        function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
                        function tokenByIndex(uint256 index) public view returns (uint256);
                    }
                    pragma solidity ^0.5.2;
                    import "./IERC721.sol";
                    /**
                     * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
                     * @dev See https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract IERC721Metadata is IERC721 {
                        function name() external view returns (string memory);
                        function symbol() external view returns (string memory);
                        function tokenURI(uint256 tokenId) external view returns (string memory);
                    }
                    pragma solidity ^0.5.2;
                    import {ERCProxy} from "./ERCProxy.sol";
                    import {DelegateProxyForwarder} from "./DelegateProxyForwarder.sol";
                    contract DelegateProxy is ERCProxy, DelegateProxyForwarder {
                        function proxyType() external pure returns (uint256 proxyTypeId) {
                            // Upgradeable proxy
                            proxyTypeId = 2;
                        }
                        function implementation() external view returns (address);
                    }
                    pragma solidity ^0.5.2;
                    /**
                     * @title IERC165
                     * @dev https://eips.ethereum.org/EIPS/eip-165
                     */
                    interface IERC165 {
                        /**
                         * @notice Query if a contract implements an interface
                         * @param interfaceId The interface identifier, as specified in ERC-165
                         * @dev Interface identification is specified in ERC-165. This function
                         * uses less than 30,000 gas.
                         */
                        function supportsInterface(bytes4 interfaceId) external view returns (bool);
                    }
                    /*
                     * SPDX-License-Identitifer:    MIT
                     */
                    pragma solidity ^0.5.2;
                    // See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md
                    interface ERCProxy {
                        function proxyType() external pure returns (uint256 proxyTypeId);
                        function implementation() external view returns (address codeAddr);
                    }
                    

                    File 8 of 8: EventsHub
                    // File: contracts/common/governance/IGovernance.sol
                    
                    pragma solidity ^0.5.2;
                    
                    interface IGovernance {
                        function update(address target, bytes calldata data) external;
                    }
                    
                    // File: contracts/common/governance/Governable.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    contract Governable {
                        IGovernance public governance;
                    
                        constructor(address _governance) public {
                            governance = IGovernance(_governance);
                        }
                    
                        modifier onlyGovernance() {
                            _assertGovernance();
                            _;
                        }
                    
                        function _assertGovernance() private view {
                            require(
                                msg.sender == address(governance),
                                "Only governance contract is authorized"
                            );
                        }
                    }
                    
                    // File: contracts/root/withdrawManager/IWithdrawManager.sol
                    
                    pragma solidity ^0.5.2;
                    
                    contract IWithdrawManager {
                        function createExitQueue(address token) external;
                    
                        function verifyInclusion(
                            bytes calldata data,
                            uint8 offset,
                            bool verifyTxInclusion
                        ) external view returns (uint256 age);
                    
                        function addExitToQueue(
                            address exitor,
                            address childToken,
                            address rootToken,
                            uint256 exitAmountOrTokenId,
                            bytes32 txHash,
                            bool isRegularExit,
                            uint256 priority
                        ) external;
                    
                        function addInput(
                            uint256 exitId,
                            uint256 age,
                            address utxoOwner,
                            address token
                        ) external;
                    
                        function challengeExit(
                            uint256 exitId,
                            uint256 inputId,
                            bytes calldata challengeData,
                            address adjudicatorPredicate
                        ) external;
                    }
                    
                    // File: contracts/common/Registry.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    
                    contract Registry is Governable {
                        // @todo hardcode constants
                        bytes32 private constant WETH_TOKEN = keccak256("wethToken");
                        bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
                        bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
                        bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
                        bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
                        bytes32 private constant CHILD_CHAIN = keccak256("childChain");
                        bytes32 private constant STATE_SENDER = keccak256("stateSender");
                        bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
                    
                        address public erc20Predicate;
                        address public erc721Predicate;
                    
                        mapping(bytes32 => address) public contractMap;
                        mapping(address => address) public rootToChildToken;
                        mapping(address => address) public childToRootToken;
                        mapping(address => bool) public proofValidatorContracts;
                        mapping(address => bool) public isERC721;
                    
                        enum Type {Invalid, ERC20, ERC721, Custom}
                        struct Predicate {
                            Type _type;
                        }
                        mapping(address => Predicate) public predicates;
                    
                        event TokenMapped(address indexed rootToken, address indexed childToken);
                        event ProofValidatorAdded(address indexed validator, address indexed from);
                        event ProofValidatorRemoved(address indexed validator, address indexed from);
                        event PredicateAdded(address indexed predicate, address indexed from);
                        event PredicateRemoved(address indexed predicate, address indexed from);
                        event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
                    
                        constructor(address _governance) public Governable(_governance) {}
                    
                        function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
                            emit ContractMapUpdated(_key, contractMap[_key], _address);
                            contractMap[_key] = _address;
                        }
                    
                        /**
                         * @dev Map root token to child token
                         * @param _rootToken Token address on the root chain
                         * @param _childToken Token address on the child chain
                         * @param _isERC721 Is the token being mapped ERC721
                         */
                        function mapToken(
                            address _rootToken,
                            address _childToken,
                            bool _isERC721
                        ) external onlyGovernance {
                            require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
                            rootToChildToken[_rootToken] = _childToken;
                            childToRootToken[_childToken] = _rootToken;
                            isERC721[_rootToken] = _isERC721;
                            IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
                            emit TokenMapped(_rootToken, _childToken);
                        }
                    
                        function addErc20Predicate(address predicate) public onlyGovernance {
                            require(predicate != address(0x0), "Can not add null address as predicate");
                            erc20Predicate = predicate;
                            addPredicate(predicate, Type.ERC20);
                        }
                    
                        function addErc721Predicate(address predicate) public onlyGovernance {
                            erc721Predicate = predicate;
                            addPredicate(predicate, Type.ERC721);
                        }
                    
                        function addPredicate(address predicate, Type _type) public onlyGovernance {
                            require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
                            predicates[predicate]._type = _type;
                            emit PredicateAdded(predicate, msg.sender);
                        }
                    
                        function removePredicate(address predicate) public onlyGovernance {
                            require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
                            delete predicates[predicate];
                            emit PredicateRemoved(predicate, msg.sender);
                        }
                    
                        function getValidatorShareAddress() public view returns (address) {
                            return contractMap[VALIDATOR_SHARE];
                        }
                    
                        function getWethTokenAddress() public view returns (address) {
                            return contractMap[WETH_TOKEN];
                        }
                    
                        function getDepositManagerAddress() public view returns (address) {
                            return contractMap[DEPOSIT_MANAGER];
                        }
                    
                        function getStakeManagerAddress() public view returns (address) {
                            return contractMap[STAKE_MANAGER];
                        }
                    
                        function getSlashingManagerAddress() public view returns (address) {
                            return contractMap[SLASHING_MANAGER];
                        }
                    
                        function getWithdrawManagerAddress() public view returns (address) {
                            return contractMap[WITHDRAW_MANAGER];
                        }
                    
                        function getChildChainAndStateSender() public view returns (address, address) {
                            return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
                        }
                    
                        function isTokenMapped(address _token) public view returns (bool) {
                            return rootToChildToken[_token] != address(0x0);
                        }
                    
                        function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
                            require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
                            return isERC721[_token];
                        }
                    
                        function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
                            if (isTokenMappedAndIsErc721(_token)) {
                                return erc721Predicate;
                            }
                            return erc20Predicate;
                        }
                    
                        function isChildTokenErc721(address childToken) public view returns (bool) {
                            address rootToken = childToRootToken[childToken];
                            require(rootToken != address(0x0), "Child token is not mapped");
                            return isERC721[rootToken];
                        }
                    }
                    
                    // File: contracts/common/mixin/Initializable.sol
                    
                    pragma solidity ^0.5.2;
                    
                    contract Initializable {
                        bool inited = false;
                    
                        modifier initializer() {
                            require(!inited, "already inited");
                            inited = true;
                            
                            _;
                        }
                    }
                    
                    // File: contracts/staking/EventsHub.sol
                    
                    pragma solidity ^0.5.2;
                    
                    
                    
                    contract IStakeManagerEventsHub {
                        struct Validator {
                            uint256 amount;
                            uint256 reward;
                            uint256 activationEpoch;
                            uint256 deactivationEpoch;
                            uint256 jailTime;
                            address signer;
                            address contractAddress;
                        }
                    
                        mapping(uint256 => Validator) public validators;
                    }
                    
                    contract EventsHub is Initializable {
                        Registry public registry;
                    
                        modifier onlyValidatorContract(uint256 validatorId) {
                            address _contract;
                            (, , , , , , _contract) = IStakeManagerEventsHub(registry.getStakeManagerAddress()).validators(validatorId);
                            require(_contract == msg.sender, "not validator");
                            _;
                        }
                    
                        modifier onlyStakeManager() {
                            require(registry.getStakeManagerAddress() == msg.sender,
                            "Invalid sender, not stake manager");
                            _;
                        }
                    
                        function initialize(Registry _registry) external initializer {
                            registry = _registry;
                        }
                    
                        event ShareBurnedWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 indexed amount,
                            uint256 tokens,
                            uint256 nonce
                        );
                    
                        function logShareBurnedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 tokens,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit ShareBurnedWithId(validatorId, user, amount, tokens, nonce);
                        }
                    
                        event DelegatorUnstakeWithId(
                            uint256 indexed validatorId,
                            address indexed user,
                            uint256 amount,
                            uint256 nonce
                        );
                    
                        function logDelegatorUnstakedWithId(
                            uint256 validatorId,
                            address user,
                            uint256 amount,
                            uint256 nonce
                        ) public onlyValidatorContract(validatorId) {
                            emit DelegatorUnstakeWithId(validatorId, user, amount, nonce);
                        }
                    
                        event RewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        );
                    
                        function logRewardParams(
                            uint256 rewardDecreasePerCheckpoint,
                            uint256 maxRewardedCheckpoints,
                            uint256 checkpointRewardDelta
                        ) public onlyStakeManager {
                            emit RewardParams(rewardDecreasePerCheckpoint, maxRewardedCheckpoints, checkpointRewardDelta);
                        }
                    
                        event UpdateCommissionRate(
                            uint256 indexed validatorId,
                            uint256 indexed newCommissionRate,
                            uint256 indexed oldCommissionRate
                        );
                    
                        function logUpdateCommissionRate(
                            uint256 validatorId,
                            uint256 newCommissionRate,
                            uint256 oldCommissionRate
                        ) public onlyStakeManager {
                            emit UpdateCommissionRate(
                                validatorId,
                                newCommissionRate,
                                oldCommissionRate
                            );
                        }
                    
                        event SharesTransfer(
                            uint256 indexed validatorId,
                            address indexed from,
                            address indexed to,
                            uint256 value
                        );
                    
                        function logSharesTransfer(
                            uint256 validatorId,
                            address from,
                            address to,
                            uint256 value
                        ) public onlyValidatorContract(validatorId) {
                            emit SharesTransfer(validatorId, from, to, value);
                        }
                    }