ETH Price: $2,542.39 (-0.76%)

Transaction Decoder

Block:
22855256 at Jul-05-2025 07:59:47 PM +UTC
Transaction Fee:
0.000341549394592936 ETH $0.87
Gas Used:
146,668 Gas / 2.328724702 Gwei

Emitted Events:

209 InitializableAdminUpgradeabilityProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x00000000000000000000000096ea3317a62d77d66b857b323abf56d3c8acc6a4, 0x000000000000000000000000881d40237659c251811cec9c364ef91dc08d300c, 0000000000000000000000000000000000000000000000000000000000000000 )
210 InitializableAdminUpgradeabilityProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x00000000000000000000000096ea3317a62d77d66b857b323abf56d3c8acc6a4, 0x0000000000000000000000004da27a545c0c5b758a6ba100e3a049001de870f5, 0000000000000000000000000000000000000000000000000000000000000000 )
211 InitializableAdminUpgradeabilityProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x00000000000000000000000096ea3317a62d77d66b857b323abf56d3c8acc6a4, 0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d, 0000000000000000000000000000000000000000000000000000000000000000 )
212 Dai.Approval( src=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, guy=0x2a1530C4...7b7158667, wad=0 )
213 Dai.Approval( src=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, guy=0x29fe7D60...a6b2bD958, wad=0 )
214 Dai.Approval( src=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, guy=0x1E0447b1...659614e4e, wad=0 )
215 Dai.Approval( src=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, guy=0x882d80D3...99307ec1C, wad=0 )
216 District0xNetworkToken.Approval( _owner=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, _spender=0x7a250d56...659F2488D, _amount=0 )
217 HOPToken.Approval( owner=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, spender=0x68b34658...D8665Fc45, value=0 )
218 Imx.Approval( owner=[Receiver] 0x96ea3317a62d77d66b857b323abf56d3c8acc6a4, spender=0x7a250d56...659F2488D, amount=0 )

Account State Difference:

  Address   Before After State Difference Code
0x0AbdAce7...b945604ea
0x6B175474...495271d0F
0x7b35Ce52...529764a00
0x7Fc66500...33E2DDaE9
0x96Ea3317...3c8acC6A4
0.098471215294369649 Eth
Nonce: 343
0.098129665899776713 Eth
Nonce: 345
0.000341549394592936
0xc5102fE9...50d81a3CC
(BuilderNet)
30.231627492174411925 Eth30.231920828174411925 Eth0.000293336

Execution Trace

0x96ea3317a62d77d66b857b323abf56d3c8acc6a4.e9ae5c53( )
  • InitializableAdminUpgradeabilityProxy.095ea7b3( )
    • AaveTokenV3.approve( spender=0x881D40237659C251811CEC9c364ef91dC08D300C, amount=0 ) => ( True )
    • InitializableAdminUpgradeabilityProxy.095ea7b3( )
      • AaveTokenV3.approve( spender=0x4da27a545c0c5B758a6BA100e3a049001de870f5, amount=0 ) => ( True )
      • InitializableAdminUpgradeabilityProxy.095ea7b3( )
        • AaveTokenV3.approve( spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, amount=0 ) => ( True )
        • Dai.approve( usr=0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667, wad=0 ) => ( True )
        • Dai.approve( usr=0x29fe7D60DdF151E5b52e5FAB4f1325da6b2bD958, wad=0 ) => ( True )
        • Dai.approve( usr=0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e, wad=0 ) => ( True )
        • Dai.approve( usr=0x882d80D3a191859d64477eb78Cca46599307ec1C, wad=0 ) => ( True )
        • District0xNetworkToken.approve( _spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _amount=0 ) => ( success=True )
          • District0xContribution.onApprove( _owner=0x96Ea3317a62d77d66b857b323abF56d3c8acC6A4, _spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _amount=0 ) => ( True )
          • HOPToken.approve( spender=0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45, amount=0 ) => ( True )
          • Imx.approve( spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, rawAmount=0 ) => ( True )
            File 1 of 7: InitializableAdminUpgradeabilityProxy
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20 {
                /**
                 * @dev Returns the amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` tokens from the caller's account to `recipient`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address recipient, uint256 amount) external returns (bool);
                /**
                 * @dev Returns the remaining number of tokens that `spender` will be
                 * allowed to spend on behalf of `owner` through {transferFrom}. This is
                 * zero by default.
                 *
                 * This value changes when {approve} or {transferFrom} are called.
                 */
                function allowance(address owner, address spender) external view returns (uint256);
                /**
                 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * IMPORTANT: Beware that changing an allowance with this method brings the risk
                 * that someone may use both the old and the new allowance by unfortunate
                 * transaction ordering. One possible solution to mitigate this race
                 * condition is to first reduce the spender's allowance to 0 and set the
                 * desired value afterwards:
                 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address spender, uint256 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `sender` to `recipient` using the
                 * allowance mechanism. `amount` is then deducted from the caller's
                 * allowance.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
            }// SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import {IERC20} from "./IERC20.sol";
            interface IERC20Detailed is IERC20 {
                function name() external view returns(string memory);
                function symbol() external view returns(string memory);
                function decimals() external view returns(uint8);
            }
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            interface ITransferHook {
                function onTransfer(address from, address to, uint256 amount) external;
            }pragma solidity ^0.6.2;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                    // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                    // for accounts without code, i.e. `keccak256('')`
                    bytes32 codehash;
                    bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                    // solhint-disable-next-line no-inline-assembly
                    assembly { codehash := extcodehash(account) }
                    return (codehash != accountHash && codehash != 0x0);
                }
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                    (bool success, ) = recipient.call{ value: amount }("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
            }pragma solidity ^0.6.0;
            import './UpgradeabilityProxy.sol';
            /**
             * @title BaseAdminUpgradeabilityProxy
             * @dev This contract combines an upgradeability proxy with an authorization
             * mechanism for administrative tasks.
             * All external functions in this contract must be guarded by the
             * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
             * feature proposal that would enable this to be done automatically.
             */
            contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
              /**
               * @dev Emitted when the administration has been transferred.
               * @param previousAdmin Address of the previous admin.
               * @param newAdmin Address of the new admin.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
              /**
               * @dev Storage slot with the admin of the contract.
               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
              /**
               * @dev Modifier to check whether the `msg.sender` is the admin.
               * If it is, it will run the function. Otherwise, it will delegate the call
               * to the implementation.
               */
              modifier ifAdmin() {
                if (msg.sender == _admin()) {
                  _;
                } else {
                  _fallback();
                }
              }
              /**
               * @return The address of the proxy admin.
               */
              function admin() external ifAdmin returns (address) {
                return _admin();
              }
              /**
               * @return The address of the implementation.
               */
              function implementation() external ifAdmin returns (address) {
                return _implementation();
              }
              /**
               * @dev Changes the admin of the proxy.
               * Only the current admin can call this function.
               * @param newAdmin Address to transfer proxy administration to.
               */
              function changeAdmin(address newAdmin) external ifAdmin {
                require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                emit AdminChanged(_admin(), newAdmin);
                _setAdmin(newAdmin);
              }
              /**
               * @dev Upgrade the backing implementation of the proxy.
               * Only the admin can call this function.
               * @param newImplementation Address of the new implementation.
               */
              function upgradeTo(address newImplementation) external ifAdmin {
                _upgradeTo(newImplementation);
              }
              /**
               * @dev Upgrade the backing implementation of the proxy and call a function
               * on the new implementation.
               * This is useful to initialize the proxied contract.
               * @param newImplementation Address of the new implementation.
               * @param data Data to send as msg.data in the low level call.
               * It should include the signature and the parameters of the function to be called, as described in
               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
               */
              function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
                _upgradeTo(newImplementation);
                (bool success,) = newImplementation.delegatecall(data);
                require(success);
              }
              /**
               * @return adm The admin slot.
               */
              function _admin() internal view returns (address adm) {
                bytes32 slot = ADMIN_SLOT;
                assembly {
                  adm := sload(slot)
                }
              }
              /**
               * @dev Sets the address of the proxy admin.
               * @param newAdmin Address of the new proxy admin.
               */
              function _setAdmin(address newAdmin) internal {
                bytes32 slot = ADMIN_SLOT;
                assembly {
                  sstore(slot, newAdmin)
                }
              }
              /**
               * @dev Only fall back when the sender is not the admin.
               */
              function _willFallback() internal override virtual {
                require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                super._willFallback();
              }
            }pragma solidity ^0.6.0;
            import './BaseUpgradeabilityProxy.sol';
            /**
             * @title UpgradeabilityProxy
             * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
             * implementation and init data.
             */
            contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
              /**
               * @dev Contract constructor.
               * @param _logic Address of the initial implementation.
               * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
               * It should include the signature and the parameters of the function to be called, as described in
               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
               * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
               */
              constructor(address _logic, bytes memory _data) public payable {
                assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
                _setImplementation(_logic);
                if(_data.length > 0) {
                  (bool success,) = _logic.delegatecall(_data);
                  require(success);
                }
              }  
            }pragma solidity ^0.6.0;
            import './Proxy.sol';
            import './Address.sol';
            /**
             * @title BaseUpgradeabilityProxy
             * @dev This contract implements a proxy that allows to change the
             * implementation address to which it will delegate.
             * Such a change is called an implementation upgrade.
             */
            contract BaseUpgradeabilityProxy is Proxy {
              /**
               * @dev Emitted when the implementation is upgraded.
               * @param implementation Address of the new implementation.
               */
              event Upgraded(address indexed implementation);
              /**
               * @dev Storage slot with the address of the current implementation.
               * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
              /**
               * @dev Returns the current implementation.
               * @return impl Address of the current implementation
               */
              function _implementation() internal override view returns (address impl) {
                bytes32 slot = IMPLEMENTATION_SLOT;
                assembly {
                  impl := sload(slot)
                }
              }
              /**
               * @dev Upgrades the proxy to a new implementation.
               * @param newImplementation Address of the new implementation.
               */
              function _upgradeTo(address newImplementation) internal {
                _setImplementation(newImplementation);
                emit Upgraded(newImplementation);
              }
              /**
               * @dev Sets the implementation address of the proxy.
               * @param newImplementation Address of the new implementation.
               */
              function _setImplementation(address newImplementation) internal {
                require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                bytes32 slot = IMPLEMENTATION_SLOT;
                assembly {
                  sstore(slot, newImplementation)
                }
              }
            }pragma solidity ^0.6.0;
            /**
             * @title Proxy
             * @dev Implements delegation of calls to other contracts, with proper
             * forwarding of return values and bubbling of failures.
             * It defines a fallback function that delegates all calls to the address
             * returned by the abstract _implementation() internal function.
             */
            abstract contract Proxy {
              /**
               * @dev Fallback function.
               * Implemented entirely in `_fallback`.
               */
              fallback () payable external {
                _fallback();
              }
              /**
               * @return The Address of the implementation.
               */
              function _implementation() internal virtual view returns (address);
              /**
               * @dev Delegates execution to an implementation contract.
               * This is a low level function that doesn't return to its internal call site.
               * It will return to the external caller whatever the implementation returns.
               * @param implementation Address to delegate.
               */
              function _delegate(address implementation) internal {
                assembly {
                  // Copy msg.data. We take full control of memory in this inline assembly
                  // block because it will not return to Solidity code. We overwrite the
                  // Solidity scratch pad at memory position 0.
                  calldatacopy(0, 0, calldatasize())
                  // Call the implementation.
                  // out and outsize are 0 because we don't know the size yet.
                  let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                  // Copy the returned data.
                  returndatacopy(0, 0, returndatasize())
                  switch result
                  // delegatecall returns 0 on error.
                  case 0 { revert(0, returndatasize()) }
                  default { return(0, returndatasize()) }
                }
              }
              /**
               * @dev Function that is run as the first thing in the fallback function.
               * Can be redefined in derived contracts to add functionality.
               * Redefinitions must call super._willFallback().
               */
              function _willFallback() internal virtual {
              }
              /**
               * @dev fallback implementation.
               * Extracted to enable manual triggering.
               */
              function _fallback() internal {
                _willFallback();
                _delegate(_implementation());
              }
            }// SPDX-License-Identifier: MIT
            pragma solidity ^0.6.0;
            /*
             * @dev Provides information about the current execution context, including the
             * sender of the transaction and its data. While these are generally available
             * via msg.sender and msg.data, they should not be accessed in such a direct
             * manner, since when dealing with GSN meta-transactions the account sending and
             * paying for execution may not be the actual sender (as far as an application
             * is concerned).
             *
             * This contract is only required for intermediate, library-like contracts.
             */
            abstract contract Context {
                function _msgSender() internal view virtual returns (address payable) {
                    return msg.sender;
                }
                function _msgData() internal view virtual returns (bytes memory) {
                    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                    return msg.data;
                }
            }// SPDX-License-Identifier: MIT
            pragma solidity ^0.6.0;
            import "./Context.sol";
            import "../interfaces/IERC20.sol";
            import "./SafeMath.sol";
            import "./Address.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
             * to implement supply mechanisms].
             *
             * We have followed general OpenZeppelin guidelines: functions revert instead
             * of returning `false` on failure. This behavior is nonetheless conventional
             * and does not conflict with the expectations of ERC20 applications.
             *
             * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
             * This allows applications to reconstruct the allowance for all accounts just
             * by listening to said events. Other implementations of the EIP may not emit
             * these events, as it isn't required by the specification.
             *
             * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
             * functions have been added to mitigate the well-known issues around setting
             * allowances. See {IERC20-approve}.
             */
            contract ERC20 is Context, IERC20 {
                using SafeMath for uint256;
                using Address for address;
                mapping (address => uint256) private _balances;
                mapping (address => mapping (address => uint256)) private _allowances;
                uint256 private _totalSupply;
                string internal _name;
                string internal _symbol;
                uint8 private _decimals;
                /**
                 * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
                 * a default value of 18.
                 *
                 * To select a different value for {decimals}, use {_setupDecimals}.
                 *
                 * All three of these values are immutable: they can only be set once during
                 * construction.
                 */
                constructor (string memory name, string memory symbol) public {
                    _name = name;
                    _symbol = symbol;
                    _decimals = 18;
                }
                /**
                 * @dev Returns the name of the token.
                 */
                function name() public view returns (string memory) {
                    return _name;
                }
                /**
                 * @dev Returns the symbol of the token, usually a shorter version of the
                 * name.
                 */
                function symbol() public view returns (string memory) {
                    return _symbol;
                }
                /**
                 * @dev Returns the number of decimals used to get its user representation.
                 * For example, if `decimals` equals `2`, a balance of `505` tokens should
                 * be displayed to a user as `5,05` (`505 / 10 ** 2`).
                 *
                 * Tokens usually opt for a value of 18, imitating the relationship between
                 * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
                 * called.
                 *
                 * NOTE: This information is only used for _display_ purposes: it in
                 * no way affects any of the arithmetic of the contract, including
                 * {IERC20-balanceOf} and {IERC20-transfer}.
                 */
                function decimals() public view returns (uint8) {
                    return _decimals;
                }
                /**
                 * @dev See {IERC20-totalSupply}.
                 */
                function totalSupply() public view override returns (uint256) {
                    return _totalSupply;
                }
                /**
                 * @dev See {IERC20-balanceOf}.
                 */
                function balanceOf(address account) public view override returns (uint256) {
                    return _balances[account];
                }
                /**
                 * @dev See {IERC20-transfer}.
                 *
                 * Requirements:
                 *
                 * - `recipient` cannot be the zero address.
                 * - the caller must have a balance of at least `amount`.
                 */
                function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                    _transfer(_msgSender(), recipient, amount);
                    return true;
                }
                /**
                 * @dev See {IERC20-allowance}.
                 */
                function allowance(address owner, address spender) public view virtual override returns (uint256) {
                    return _allowances[owner][spender];
                }
                /**
                 * @dev See {IERC20-approve}.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function approve(address spender, uint256 amount) public virtual override returns (bool) {
                    _approve(_msgSender(), spender, amount);
                    return true;
                }
                /**
                 * @dev See {IERC20-transferFrom}.
                 *
                 * Emits an {Approval} event indicating the updated allowance. This is not
                 * required by the EIP. See the note at the beginning of {ERC20};
                 *
                 * Requirements:
                 * - `sender` and `recipient` cannot be the zero address.
                 * - `sender` must have a balance of at least `amount`.
                 * - the caller must have allowance for ``sender``'s tokens of at least
                 * `amount`.
                 */
                function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
                    _transfer(sender, recipient, amount);
                    _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
                    return true;
                }
                /**
                 * @dev Atomically increases the allowance granted to `spender` by the caller.
                 *
                 * This is an alternative to {approve} that can be used as a mitigation for
                 * problems described in {IERC20-approve}.
                 *
                 * Emits an {Approval} event indicating the updated allowance.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                    _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
                    return true;
                }
                /**
                 * @dev Atomically decreases the allowance granted to `spender` by the caller.
                 *
                 * This is an alternative to {approve} that can be used as a mitigation for
                 * problems described in {IERC20-approve}.
                 *
                 * Emits an {Approval} event indicating the updated allowance.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 * - `spender` must have allowance for the caller of at least
                 * `subtractedValue`.
                 */
                function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                    _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                    return true;
                }
                /**
                 * @dev Moves tokens `amount` from `sender` to `recipient`.
                 *
                 * This is internal function is equivalent to {transfer}, and can be used to
                 * e.g. implement automatic token fees, slashing mechanisms, etc.
                 *
                 * Emits a {Transfer} event.
                 *
                 * Requirements:
                 *
                 * - `sender` cannot be the zero address.
                 * - `recipient` cannot be the zero address.
                 * - `sender` must have a balance of at least `amount`.
                 */
                function _transfer(address sender, address recipient, uint256 amount) internal virtual {
                    require(sender != address(0), "ERC20: transfer from the zero address");
                    require(recipient != address(0), "ERC20: transfer to the zero address");
                    _beforeTokenTransfer(sender, recipient, amount);
                    _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                    _balances[recipient] = _balances[recipient].add(amount);
                    emit Transfer(sender, recipient, amount);
                }
                /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                 * the total supply.
                 *
                 * Emits a {Transfer} event with `from` set to the zero address.
                 *
                 * Requirements
                 *
                 * - `to` cannot be the zero address.
                 */
                function _mint(address account, uint256 amount) internal virtual {
                    require(account != address(0), "ERC20: mint to the zero address");
                    _beforeTokenTransfer(address(0), account, amount);
                    _totalSupply = _totalSupply.add(amount);
                    _balances[account] = _balances[account].add(amount);
                    emit Transfer(address(0), account, amount);
                }
                /**
                 * @dev Destroys `amount` tokens from `account`, reducing the
                 * total supply.
                 *
                 * Emits a {Transfer} event with `to` set to the zero address.
                 *
                 * Requirements
                 *
                 * - `account` cannot be the zero address.
                 * - `account` must have at least `amount` tokens.
                 */
                function _burn(address account, uint256 amount) internal virtual {
                    require(account != address(0), "ERC20: burn from the zero address");
                    _beforeTokenTransfer(account, address(0), amount);
                    _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                    _totalSupply = _totalSupply.sub(amount);
                    emit Transfer(account, address(0), amount);
                }
                /**
                 * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
                 *
                 * This is internal function is equivalent to `approve`, and can be used to
                 * e.g. set automatic allowances for certain subsystems, etc.
                 *
                 * Emits an {Approval} event.
                 *
                 * Requirements:
                 *
                 * - `owner` cannot be the zero address.
                 * - `spender` cannot be the zero address.
                 */
                function _approve(address owner, address spender, uint256 amount) internal virtual {
                    require(owner != address(0), "ERC20: approve from the zero address");
                    require(spender != address(0), "ERC20: approve to the zero address");
                    _allowances[owner][spender] = amount;
                    emit Approval(owner, spender, amount);
                }
                /**
                 * @dev Sets {decimals} to a value other than the default one of 18.
                 *
                 * WARNING: This function should only be called from the constructor. Most
                 * applications that interact with token contracts will not expect
                 * {decimals} to ever change, and may work incorrectly if it does.
                 */
                function _setupDecimals(uint8 decimals_) internal {
                    _decimals = decimals_;
                }
                /**
                 * @dev Hook that is called before any transfer of tokens. This includes
                 * minting and burning.
                 *
                 * Calling conditions:
                 *
                 * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                 * will be to transferred to `to`.
                 * - when `from` is zero, `amount` tokens will be minted for `to`.
                 * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                 * - `from` and `to` are never both zero.
                 *
                 * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                 */
                function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
            }pragma solidity ^0.6.0;
            /**
             * @dev Wrappers over Solidity's arithmetic operations with added overflow
             * checks.
             *
             * Arithmetic operations in Solidity wrap on overflow. This can easily result
             * in bugs, because programmers usually assume that an overflow raises an
             * error, which is the standard behavior in high level programming languages.
             * `SafeMath` restores this intuition by reverting the transaction when an
             * operation overflows.
             *
             * Using this library instead of the unchecked operations eliminates an entire
             * class of bugs, so it's recommended to use it always.
             */
            library SafeMath {
                /**
                 * @dev Returns the addition of two unsigned integers, reverting on
                 * overflow.
                 *
                 * Counterpart to Solidity's `+` operator.
                 *
                 * Requirements:
                 * - Addition cannot overflow.
                 */
                function add(uint256 a, uint256 b) internal pure returns (uint256) {
                    uint256 c = a + b;
                    require(c >= a, "SafeMath: addition overflow");
                    return c;
                }
                /**
                 * @dev Returns the subtraction of two unsigned integers, reverting on
                 * overflow (when the result is negative).
                 *
                 * Counterpart to Solidity's `-` operator.
                 *
                 * Requirements:
                 * - Subtraction cannot overflow.
                 */
                function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                    return sub(a, b, "SafeMath: subtraction overflow");
                }
                /**
                 * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                 * overflow (when the result is negative).
                 *
                 * Counterpart to Solidity's `-` operator.
                 *
                 * Requirements:
                 * - Subtraction cannot overflow.
                 */
                function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                    require(b <= a, errorMessage);
                    uint256 c = a - b;
                    return c;
                }
                /**
                 * @dev Returns the multiplication of two unsigned integers, reverting on
                 * overflow.
                 *
                 * Counterpart to Solidity's `*` operator.
                 *
                 * Requirements:
                 * - Multiplication cannot overflow.
                 */
                function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                    // benefit is lost if 'b' is also tested.
                    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                    if (a == 0) {
                        return 0;
                    }
                    uint256 c = a * b;
                    require(c / a == b, "SafeMath: multiplication overflow");
                    return c;
                }
                /**
                 * @dev Returns the integer division of two unsigned integers. Reverts on
                 * division by zero. The result is rounded towards zero.
                 *
                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                 * uses an invalid opcode to revert (consuming all remaining gas).
                 *
                 * Requirements:
                 * - The divisor cannot be zero.
                 */
                function div(uint256 a, uint256 b) internal pure returns (uint256) {
                    return div(a, b, "SafeMath: division by zero");
                }
                /**
                 * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                 * division by zero. The result is rounded towards zero.
                 *
                 * Counterpart to Solidity's `/` operator. Note: this function uses a
                 * `revert` opcode (which leaves remaining gas untouched) while Solidity
                 * uses an invalid opcode to revert (consuming all remaining gas).
                 *
                 * Requirements:
                 * - The divisor cannot be zero.
                 */
                function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                    // Solidity only automatically asserts when dividing by 0
                    require(b > 0, errorMessage);
                    uint256 c = a / b;
                    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                    return c;
                }
                /**
                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                 * Reverts when dividing by zero.
                 *
                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                 * invalid opcode to revert (consuming all remaining gas).
                 *
                 * Requirements:
                 * - The divisor cannot be zero.
                 */
                function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                    return mod(a, b, "SafeMath: modulo by zero");
                }
                /**
                 * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                 * Reverts with custom message when dividing by zero.
                 *
                 * Counterpart to Solidity's `%` operator. This function uses a `revert`
                 * opcode (which leaves remaining gas untouched) while Solidity uses an
                 * invalid opcode to revert (consuming all remaining gas).
                 *
                 * Requirements:
                 * - The divisor cannot be zero.
                 */
                function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                    require(b != 0, errorMessage);
                    return a % b;
                }
            }// SPDX-License-Identifier: agpl-3.0
            pragma solidity ^0.6.10;
            import "./BaseAdminUpgradeabilityProxy.sol";
            import "./InitializableUpgradeabilityProxy.sol";
            /**
             * @title InitializableAdminUpgradeabilityProxy
             * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for 
             * initializing the implementation, admin, and init data.
             */
            contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
                /**
               * Contract initializer.
               * @param _logic address of the initial implementation.
               * @param _admin Address of the proxy administrator.
               * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
               * It should include the signature and the parameters of the function to be called, as described in
               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
               * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
               */
                function initialize(address _logic, address _admin, bytes memory _data) public payable {
                    require(_implementation() == address(0));
                    InitializableUpgradeabilityProxy.initialize(_logic, _data);
                    assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                    _setAdmin(_admin);
                }
                /**
                * @dev Only fall back when the sender is not the admin.
                */
                function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
                    BaseAdminUpgradeabilityProxy._willFallback();
                }
            }
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity ^0.6.10;
            import "./BaseUpgradeabilityProxy.sol";
            /**
             * @title InitializableUpgradeabilityProxy
             * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
             * implementation and init data.
             */
            contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
                /**
               * @dev Contract initializer.
               * @param _logic Address of the initial implementation.
               * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
               * It should include the signature and the parameters of the function to be called, as described in
               * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
               * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
               */
                function initialize(address _logic, bytes memory _data) public payable {
                    require(_implementation() == address(0));
                    assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                    _setImplementation(_logic);
                    if (_data.length > 0) {
                        (bool success, ) = _logic.delegatecall(_data);
                        require(success);
                    }
                }
            }
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import {ERC20} from "../open-zeppelin/ERC20.sol";
            import {ITransferHook} from "../interfaces/ITransferHook.sol";
            import {VersionedInitializable} from "../utils/VersionedInitializable.sol";
            /**
            * @notice implementation of the AAVE token contract
            * @author Aave
            */
            contract AaveToken is ERC20, VersionedInitializable {
                /// @dev snapshot of a value on a specific block, used for balances
                struct Snapshot {
                    uint128 blockNumber;
                    uint128 value;
                }
                string internal constant NAME = "Aave Token";
                string internal constant SYMBOL = "AAVE";
                uint8 internal constant DECIMALS = 18;
                /// @dev the amount being distributed for the LEND -> AAVE migration
                uint256 internal constant MIGRATION_AMOUNT = 13000000 ether;
                /// @dev the amount being distributed for the PSI and PEI
                uint256 internal constant DISTRIBUTION_AMOUNT = 3000000 ether;
                uint256 public constant REVISION = 1;
                /// @dev owner => next valid nonce to submit with permit()
                mapping (address => uint256) public _nonces;
                mapping (address => mapping (uint256 => Snapshot)) public _snapshots;
                mapping (address => uint256) public _countsSnapshots;
                /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer
                /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility
                /// to control all potential reentrancies by calling back the AaveToken
                ITransferHook public _aaveGovernance;
                bytes32 public DOMAIN_SEPARATOR;
                bytes public constant EIP712_REVISION = bytes("1");
                bytes32 internal constant EIP712_DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
                bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                event SnapshotDone(address owner, uint128 oldValue, uint128 newValue);
                constructor() ERC20(NAME, SYMBOL) public {}
                /**
                * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy
                * @param migrator the address of the LEND -> AAVE migration contract
                * @param distributor the address of the AAVE distribution contract
                */
                function initialize(
                    address migrator,
                    address distributor,
                    ITransferHook aaveGovernance
                ) external initializer {
                    uint256 chainId;
                    //solium-disable-next-line
                    assembly {
                        chainId := chainid()
                    }
                    DOMAIN_SEPARATOR = keccak256(abi.encode(
                        EIP712_DOMAIN,
                        keccak256(bytes(NAME)),
                        keccak256(EIP712_REVISION),
                        chainId,
                        address(this)
                    ));
                    _name = NAME;
                    _symbol = SYMBOL;
                    _setupDecimals(DECIMALS);
                    _aaveGovernance = aaveGovernance;
                    _mint(migrator, MIGRATION_AMOUNT);
                    _mint(distributor, DISTRIBUTION_AMOUNT);
                }
                /**
                * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
                * @param owner the owner of the funds
                * @param spender the spender
                * @param value the amount
                * @param deadline the deadline timestamp, type(uint256).max for no deadline
                * @param v signature param
                * @param s signature param
                * @param r signature param
                */
                function permit(
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) external {
                    require(owner != address(0), "INVALID_OWNER");
                    //solium-disable-next-line
                    require(block.timestamp <= deadline, "INVALID_EXPIRATION");
                    uint256 currentValidNonce = _nonces[owner];
                    bytes32 digest = keccak256(
                            abi.encodePacked(
                                "\\x19\\x01",
                                DOMAIN_SEPARATOR,
                                keccak256(
                                    abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
                                )
                    );
                    require(owner == ecrecover(digest, v, r, s), "INVALID_SIGNATURE");
                    _nonces[owner] = currentValidNonce.add(1);
                    _approve(owner, spender, value);
                }
                /**
                * @dev returns the revision of the implementation contract
                */
                function getRevision() internal pure override returns (uint256) {
                    return REVISION;
                }
                /**
                * @dev Writes a snapshot for an owner of tokens
                * @param owner The owner of the tokens
                * @param oldValue The value before the operation that is gonna be executed after the snapshot
                * @param newValue The value after the operation
                */
                function _writeSnapshot(address owner, uint128 oldValue, uint128 newValue) internal {
                    uint128 currentBlock = uint128(block.number);
                    uint256 ownerCountOfSnapshots = _countsSnapshots[owner];
                    mapping (uint256 => Snapshot) storage snapshotsOwner = _snapshots[owner];
                    // Doing multiple operations in the same block
                    if (ownerCountOfSnapshots != 0 && snapshotsOwner[ownerCountOfSnapshots.sub(1)].blockNumber == currentBlock) {
                        snapshotsOwner[ownerCountOfSnapshots.sub(1)].value = newValue;
                    } else {
                        snapshotsOwner[ownerCountOfSnapshots] = Snapshot(currentBlock, newValue);
                        _countsSnapshots[owner] = ownerCountOfSnapshots.add(1);
                    }
                    emit SnapshotDone(owner, oldValue, newValue);
                }
                /**
                * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn
                * - On _transfer, it writes snapshots for both "from" and "to"
                * - On _mint, only for _to
                * - On _burn, only for _from
                * @param from the from address
                * @param to the to address
                * @param amount the amount to transfer
                */
                function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
                    if (from == to) {
                        return;
                    }
                    if (from != address(0)) {
                        uint256 fromBalance = balanceOf(from);
                        _writeSnapshot(from, uint128(fromBalance), uint128(fromBalance.sub(amount)));
                    }
                    if (to != address(0)) {
                        uint256 toBalance = balanceOf(to);
                        _writeSnapshot(to, uint128(toBalance), uint128(toBalance.add(amount)));
                    }
                    // caching the aave governance address to avoid multiple state loads
                    ITransferHook aaveGovernance = _aaveGovernance;
                    if (aaveGovernance != ITransferHook(0)) {
                        aaveGovernance.onTransfer(from, to, amount);
                    }
                }
            }// SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            /**
             * @title VersionedInitializable
             *
             * @dev Helper contract to support initializer functions. To use it, replace
             * the constructor with a function that has the `initializer` modifier.
             * WARNING: Unlike constructors, initializer functions must be manually
             * invoked. This applies both to deploying an Initializable contract, as well
             * as extending an Initializable contract via inheritance.
             * WARNING: When used with inheritance, manual care must be taken to not invoke
             * a parent initializer twice, or ensure that all initializers are idempotent,
             * because this is not dealt with automatically as with constructors.
             *
             * @author Aave, inspired by the OpenZeppelin Initializable contract
             */
            abstract contract VersionedInitializable {
                /**
               * @dev Indicates that the contract has been initialized.
               */
                uint256 internal lastInitializedRevision = 0;
               /**
               * @dev Modifier to use in the initializer function of a contract.
               */
                modifier initializer() {
                    uint256 revision = getRevision();
                    require(revision > lastInitializedRevision, "Contract instance has already been initialized");
                    lastInitializedRevision = revision;
                    _;
                }
                /// @dev returns the revision number of the contract.
                /// Needs to be defined in the inherited class as a constant.
                function getRevision() internal pure virtual returns(uint256);
                // Reserved storage space to allow for layout changes in the future.
                uint256[50] private ______gap;
            }
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import {IERC20} from "../interfaces/IERC20.sol";
            import {SafeMath} from "../open-zeppelin/SafeMath.sol";
            import {VersionedInitializable} from "../utils/VersionedInitializable.sol";
            /**
            * @title LendToAaveMigrator
            * @notice This contract implements the migration from LEND to AAVE token
            * @author Aave 
            */
            contract LendToAaveMigrator is VersionedInitializable {
                using SafeMath for uint256;
                IERC20 public immutable AAVE;
                IERC20 public immutable LEND;
                uint256 public immutable LEND_AAVE_RATIO;
                uint256 public constant REVISION = 1;
                
                uint256 public _totalLendMigrated;
                /**
                * @dev emitted on migration
                * @param sender the caller of the migration
                * @param amount the amount being migrated
                */
                event LendMigrated(address indexed sender, uint256 indexed amount);
                /**
                * @param aave the address of the AAVE token
                * @param lend the address of the LEND token
                * @param lendAaveRatio the exchange rate between LEND and AAVE 
                 */
                constructor(IERC20 aave, IERC20 lend, uint256 lendAaveRatio) public {
                    AAVE = aave;
                    LEND = lend;
                    LEND_AAVE_RATIO = lendAaveRatio;
                }
                /**
                * @dev initializes the implementation
                */
                function initialize() public initializer {
                }
                /**
                * @dev returns true if the migration started
                */
                function migrationStarted() external view returns(bool) {
                    return lastInitializedRevision != 0;
                }
                /**
                * @dev executes the migration from LEND to AAVE. Users need to give allowance to this contract to transfer LEND before executing
                * this transaction.
                * @param amount the amount of LEND to be migrated
                */
                function migrateFromLEND(uint256 amount) external {
                    require(lastInitializedRevision != 0, "MIGRATION_NOT_STARTED");
                    _totalLendMigrated = _totalLendMigrated.add(amount);
                    LEND.transferFrom(msg.sender, address(this), amount);
                    AAVE.transfer(msg.sender, amount.div(LEND_AAVE_RATIO));
                    emit LendMigrated(msg.sender, amount);
                }
                /**
                * @dev returns the implementation revision
                * @return the implementation revision
                */
                function getRevision() internal pure override returns (uint256) {
                    return REVISION;
                }
            }// SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import "../interfaces/IERC20.sol";
            contract DoubleTransferHelper {
                IERC20 public immutable AAVE;
                constructor(IERC20 aave) public {
                    AAVE = aave;
                }
                function doubleSend(address to, uint256 amount1, uint256 amount2) external {
                    AAVE.transfer(to, amount1);
                    AAVE.transfer(to, amount2);
                }
            }// SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import "../open-zeppelin/ERC20.sol";
            /**
             * @title ERC20Mintable
             * @dev ERC20 minting logic
             */
            contract MintableErc20 is ERC20 {
                constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) public {
                    _setupDecimals(decimals);
                }
                /**
                 * @dev Function to mint tokens
                 * @param value The amount of tokens to mint.
                 * @return A boolean that indicates if the operation was successful.
                 */
                function mint(uint256 value) public returns (bool) {
                    _mint(msg.sender, value);
                    return true;
                }
            }
            // SPDX-License-Identifier: agpl-3.0
            pragma solidity 0.6.10;
            import {ITransferHook} from "../interfaces/ITransferHook.sol";
            contract MockTransferHook is ITransferHook {
                event MockHookEvent();
                function onTransfer(address from, address to, uint256 amount) external override {
                    emit MockHookEvent();
                }
            }

            File 2 of 7: Dai
            // hevm: flattened sources of /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
            pragma solidity =0.5.12;
            
            ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/lib.sol
            // This program is free software: you can redistribute it and/or modify
            // it under the terms of the GNU General Public License as published by
            // the Free Software Foundation, either version 3 of the License, or
            // (at your option) any later version.
            
            // This program is distributed in the hope that it will be useful,
            // but WITHOUT ANY WARRANTY; without even the implied warranty of
            // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            // GNU General Public License for more details.
            
            // You should have received a copy of the GNU General Public License
            // along with this program.  If not, see <http://www.gnu.org/licenses/>.
            
            /* pragma solidity 0.5.12; */
            
            contract LibNote {
                event LogNote(
                    bytes4   indexed  sig,
                    address  indexed  usr,
                    bytes32  indexed  arg1,
                    bytes32  indexed  arg2,
                    bytes             data
                ) anonymous;
            
                modifier note {
                    _;
                    assembly {
                        // log an 'anonymous' event with a constant 6 words of calldata
                        // and four indexed topics: selector, caller, arg1 and arg2
                        let mark := msize                         // end of memory ensures zero
                        mstore(0x40, add(mark, 288))              // update free memory pointer
                        mstore(mark, 0x20)                        // bytes type data offset
                        mstore(add(mark, 0x20), 224)              // bytes size (padded)
                        calldatacopy(add(mark, 0x40), 0, 224)     // bytes payload
                        log4(mark, 288,                           // calldata
                             shl(224, shr(224, calldataload(0))), // msg.sig
                             caller,                              // msg.sender
                             calldataload(4),                     // arg1
                             calldataload(36)                     // arg2
                            )
                    }
                }
            }
            
            ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
            // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico
            
            // This program is free software: you can redistribute it and/or modify
            // it under the terms of the GNU Affero General Public License as published by
            // the Free Software Foundation, either version 3 of the License, or
            // (at your option) any later version.
            //
            // This program is distributed in the hope that it will be useful,
            // but WITHOUT ANY WARRANTY; without even the implied warranty of
            // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            // GNU Affero General Public License for more details.
            //
            // You should have received a copy of the GNU Affero General Public License
            // along with this program.  If not, see <https://www.gnu.org/licenses/>.
            
            /* pragma solidity 0.5.12; */
            
            /* import "./lib.sol"; */
            
            contract Dai is LibNote {
                // --- Auth ---
                mapping (address => uint) public wards;
                function rely(address guy) external note auth { wards[guy] = 1; }
                function deny(address guy) external note auth { wards[guy] = 0; }
                modifier auth {
                    require(wards[msg.sender] == 1, "Dai/not-authorized");
                    _;
                }
            
                // --- ERC20 Data ---
                string  public constant name     = "Dai Stablecoin";
                string  public constant symbol   = "DAI";
                string  public constant version  = "1";
                uint8   public constant decimals = 18;
                uint256 public totalSupply;
            
                mapping (address => uint)                      public balanceOf;
                mapping (address => mapping (address => uint)) public allowance;
                mapping (address => uint)                      public nonces;
            
                event Approval(address indexed src, address indexed guy, uint wad);
                event Transfer(address indexed src, address indexed dst, uint wad);
            
                // --- Math ---
                function add(uint x, uint y) internal pure returns (uint z) {
                    require((z = x + y) >= x);
                }
                function sub(uint x, uint y) internal pure returns (uint z) {
                    require((z = x - y) <= x);
                }
            
                // --- EIP712 niceties ---
                bytes32 public DOMAIN_SEPARATOR;
                // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
                bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
            
                constructor(uint256 chainId_) public {
                    wards[msg.sender] = 1;
                    DOMAIN_SEPARATOR = keccak256(abi.encode(
                        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                        keccak256(bytes(name)),
                        keccak256(bytes(version)),
                        chainId_,
                        address(this)
                    ));
                }
            
                // --- Token ---
                function transfer(address dst, uint wad) external returns (bool) {
                    return transferFrom(msg.sender, dst, wad);
                }
                function transferFrom(address src, address dst, uint wad)
                    public returns (bool)
                {
                    require(balanceOf[src] >= wad, "Dai/insufficient-balance");
                    if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                        require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance");
                        allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad);
                    }
                    balanceOf[src] = sub(balanceOf[src], wad);
                    balanceOf[dst] = add(balanceOf[dst], wad);
                    emit Transfer(src, dst, wad);
                    return true;
                }
                function mint(address usr, uint wad) external auth {
                    balanceOf[usr] = add(balanceOf[usr], wad);
                    totalSupply    = add(totalSupply, wad);
                    emit Transfer(address(0), usr, wad);
                }
                function burn(address usr, uint wad) external {
                    require(balanceOf[usr] >= wad, "Dai/insufficient-balance");
                    if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) {
                        require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance");
                        allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad);
                    }
                    balanceOf[usr] = sub(balanceOf[usr], wad);
                    totalSupply    = sub(totalSupply, wad);
                    emit Transfer(usr, address(0), wad);
                }
                function approve(address usr, uint wad) external returns (bool) {
                    allowance[msg.sender][usr] = wad;
                    emit Approval(msg.sender, usr, wad);
                    return true;
                }
            
                // --- Alias ---
                function push(address usr, uint wad) external {
                    transferFrom(msg.sender, usr, wad);
                }
                function pull(address usr, uint wad) external {
                    transferFrom(usr, msg.sender, wad);
                }
                function move(address src, address dst, uint wad) external {
                    transferFrom(src, dst, wad);
                }
            
                // --- Approve by signature ---
                function permit(address holder, address spender, uint256 nonce, uint256 expiry,
                                bool allowed, uint8 v, bytes32 r, bytes32 s) external
                {
                    bytes32 digest =
                        keccak256(abi.encodePacked(
                            "\x19\x01",
                            DOMAIN_SEPARATOR,
                            keccak256(abi.encode(PERMIT_TYPEHASH,
                                                 holder,
                                                 spender,
                                                 nonce,
                                                 expiry,
                                                 allowed))
                    ));
            
                    require(holder != address(0), "Dai/invalid-address-0");
                    require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
                    require(expiry == 0 || now <= expiry, "Dai/permit-expired");
                    require(nonce == nonces[holder]++, "Dai/invalid-nonce");
                    uint wad = allowed ? uint(-1) : 0;
                    allowance[holder][spender] = wad;
                    emit Approval(holder, spender, wad);
                }
            }

            File 3 of 7: District0xNetworkToken
            pragma solidity ^0.4.11;
            
            
            library SafeMath {
              function mul(uint a, uint b) internal returns (uint) {
                uint c = a * b;
                assert(a == 0 || c / a == b);
                return c;
              }
            
              function div(uint a, uint b) internal returns (uint) {
                // assert(b > 0); // Solidity automatically throws when dividing by 0
                uint c = a / b;
                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                return c;
              }
            
              function sub(uint a, uint b) internal returns (uint) {
                assert(b <= a);
                return a - b;
              }
            
              function add(uint a, uint b) internal returns (uint) {
                uint c = a + b;
                assert(c >= a);
                return c;
              }
            
              function max64(uint64 a, uint64 b) internal constant returns (uint64) {
                return a >= b ? a : b;
              }
            
              function min64(uint64 a, uint64 b) internal constant returns (uint64) {
                return a < b ? a : b;
              }
            
              function max256(uint256 a, uint256 b) internal constant returns (uint256) {
                return a >= b ? a : b;
              }
            
              function min256(uint256 a, uint256 b) internal constant returns (uint256) {
                return a < b ? a : b;
              }
            
              function assert(bool assertion) internal {
                if (!assertion) {
                  throw;
                }
              }
            }
            
            contract Ownable {
            
                /// @dev `owner` is the only address that can call a function with this
                /// modifier
                modifier onlyOwner() {
                    require(msg.sender == owner);
                    _;
                }
            
                address public owner;
            
                /// @notice The Constructor assigns the message sender to be `owner`
                function Ownable() {
                    owner = msg.sender;
                }
            
                address public newOwner;
            
                /// @notice `owner` can step down and assign some other address to this role
                /// @param _newOwner The address of the new owner.
                function changeOwner(address _newOwner) onlyOwner {
                    newOwner = _newOwner;
                }
            
            
                function acceptOwnership() {
                    if (msg.sender == newOwner) {
                        owner = newOwner;
                    }
                }
            }
            
            contract Pausable is Ownable {
              bool public stopped;
              event onEmergencyChanged(bool isStopped);
            
              modifier stopInEmergency {
                if (stopped) {
                  throw;
                }
                _;
              }
            
              modifier onlyInEmergency {
                if (!stopped) {
                  throw;
                }
                _;
              }
            
              // called by the owner on emergency, triggers stopped state
              function emergencyStop() external onlyOwner {
                stopped = true;
                onEmergencyChanged(stopped);
              }
            
              // called by the owner on end of emergency, returns to normal state
              function release() external onlyOwner onlyInEmergency {
                stopped = false;
                onEmergencyChanged(stopped);
              }
            
            }
            
            contract ERC20Basic {
              function totalSupply() constant returns (uint);
              function balanceOf(address who) constant returns (uint);
              function transfer(address to, uint value) returns (bool);
              event Transfer(address indexed from, address indexed to, uint value);
            }
            
            contract ERC20 is ERC20Basic {
            
              mapping(address => uint) balances;
            
              function allowance(address owner, address spender) constant returns (uint);
              function transferFrom(address from, address to, uint value) returns (bool);
              function approve(address spender, uint value) returns (bool);
              function approveAndCall(address spender, uint256 value, bytes extraData) returns (bool);
              event Approval(address indexed owner, address indexed spender, uint value);
            
              function doTransfer(address _from, address _to, uint _amount) internal returns(bool);
            }
            
            contract GrantsControlled {
                modifier onlyGrantsController { if (msg.sender != grantsController) throw; _; }
            
                address public grantsController;
            
                function GrantsControlled() { grantsController = msg.sender;}
            
                function changeGrantsController(address _newController) onlyGrantsController {
                    grantsController = _newController;
                }
            }
            
            contract LimitedTransferToken is ERC20 {
              // Checks whether it can transfer or otherwise throws.
              modifier canTransfer(address _sender, uint _value) {
               if (_value > transferableTokens(_sender, uint64(now))) throw;
               _;
              }
            
              // Checks modifier and allows transfer if tokens are not locked.
              function transfer(address _to, uint _value) canTransfer(msg.sender, _value) returns (bool) {
               return super.transfer(_to, _value);
              }
            
              // Checks modifier and allows transfer if tokens are not locked.
              function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) returns (bool) {
               return super.transferFrom(_from, _to, _value);
              }
            
              // Default transferable tokens function returns all tokens for a holder (no limit).
              function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
                return balanceOf(holder);
              }
            }
            
            contract Controlled {
                /// @notice The address of the controller is the only address that can call
                ///  a function with this modifier
                modifier onlyController { if (msg.sender != controller) throw; _; }
            
                address public controller;
            
                function Controlled() { controller = msg.sender;}
            
                /// @notice Changes the controller of the contract
                /// @param _newController The new controller of the contract
                function changeController(address _newController) onlyController {
                    controller = _newController;
                }
            }
            
            contract MiniMeToken is ERC20, Controlled {
                using SafeMath for uint;
            
                string public name;                //The Token's name: e.g. DigixDAO Tokens
                uint8 public decimals;             //Number of decimals of the smallest unit
                string public symbol;              //An identifier: e.g. REP
                string public version = 'MMT_0.1'; //An arbitrary versioning scheme
            
            
                /// @dev `Checkpoint` is the structure that attaches a block number to a
                ///  given value, the block number attached is the one that last changed the
                ///  value
                struct  Checkpoint {
            
                    // `fromBlock` is the block number that the value was generated from
                    uint128 fromBlock;
            
                    // `value` is the amount of tokens at a specific block number
                    uint128 value;
                }
            
                // `parentToken` is the Token address that was cloned to produce this token;
                //  it will be 0x0 for a token that was not cloned
                MiniMeToken public parentToken;
            
                // `parentSnapShotBlock` is the block number from the Parent Token that was
                //  used to determine the initial distribution of the Clone Token
                uint public parentSnapShotBlock;
            
                // `creationBlock` is the block number that the Clone Token was created
                uint public creationBlock;
            
                // `balances` is the map that tracks the balance of each address, in this
                //  contract when the balance changes the block number that the change
                //  occurred is also included in the map
                mapping (address => Checkpoint[]) balances;
            
                // `allowed` tracks any extra transfer rights as in all ERC20 tokens
                mapping (address => mapping (address => uint256)) allowed;
            
                // Tracks the history of the `totalSupply` of the token
                Checkpoint[] totalSupplyHistory;
            
                // Flag that determines if the token is transferable or not.
                bool public transfersEnabled;
            
                // The factory used to create new clone tokens
                MiniMeTokenFactory public tokenFactory;
            
            ////////////////
            // Constructor
            ////////////////
            
                /// @notice Constructor to create a MiniMeToken
                /// @param _tokenFactory The address of the MiniMeTokenFactory contract that
                ///  will create the Clone token contracts, the token factory needs to be
                ///  deployed first
                /// @param _parentToken Address of the parent token, set to 0x0 if it is a
                ///  new token
                /// @param _parentSnapShotBlock Block of the parent token that will
                ///  determine the initial distribution of the clone token, set to 0 if it
                ///  is a new token
                /// @param _tokenName Name of the new token
                /// @param _decimalUnits Number of decimals of the new token
                /// @param _tokenSymbol Token Symbol for the new token
                /// @param _transfersEnabled If true, tokens will be able to be transferred
                function MiniMeToken(
                    address _tokenFactory,
                    address _parentToken,
                    uint _parentSnapShotBlock,
                    string _tokenName,
                    uint8 _decimalUnits,
                    string _tokenSymbol,
                    bool _transfersEnabled
                ) {
                    tokenFactory = MiniMeTokenFactory(_tokenFactory);
                    name = _tokenName;                                 // Set the name
                    decimals = _decimalUnits;                          // Set the decimals
                    symbol = _tokenSymbol;                             // Set the symbol
                    parentToken = MiniMeToken(_parentToken);
                    parentSnapShotBlock = _parentSnapShotBlock;
                    transfersEnabled = _transfersEnabled;
                    creationBlock = block.number;
                }
            
            
            ///////////////////
            // ERC20 Methods
            ///////////////////
            
                /// @notice Send `_amount` tokens to `_to` from `msg.sender`
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return Whether the transfer was successful or not
                function transfer(address _to, uint256 _amount) returns (bool success) {
                    if (!transfersEnabled) throw;
                    return doTransfer(msg.sender, _to, _amount);
                }
            
                /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
                ///  is approved by `_from`
                /// @param _from The address holding the tokens being transferred
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return True if the transfer was successful
                function transferFrom(address _from, address _to, uint256 _amount
                ) returns (bool success) {
            
                    // The controller of this contract can move tokens around at will,
                    //  this is important to recognize! Confirm that you trust the
                    //  controller of this contract, which in most situations should be
                    //  another open source smart contract or 0x0
                    if (msg.sender != controller) {
                        if (!transfersEnabled) throw;
            
                        // The standard ERC 20 transferFrom functionality
                        if (allowed[_from][msg.sender] < _amount) return false;
                        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
                    }
                    return doTransfer(_from, _to, _amount);
                }
            
                /// @dev This is the actual transfer function in the token contract, it can
                ///  only be called by other functions in this contract.
                /// @param _from The address holding the tokens being transferred
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return True if the transfer was successful
                function doTransfer(address _from, address _to, uint _amount
                ) internal returns(bool) {
            
                       if (_amount == 0) {
                           return true;
                       }
            
                       if (parentSnapShotBlock >= block.number) throw;
            
                       // Do not allow transfer to 0x0 or the token contract itself
                       if ((_to == 0) || (_to == address(this))) throw;
            
                       // If the amount being transfered is more than the balance of the
                       //  account the transfer returns false
                       var previousBalanceFrom = balanceOfAt(_from, block.number);
                       if (previousBalanceFrom < _amount) {
                           return false;
                       }
            
                       // Alerts the token controller of the transfer
                       if (isContract(controller)) {
                           if (!TokenController(controller).onTransfer(_from, _to, _amount))
                           throw;
                       }
            
                       // First update the balance array with the new value for the address
                       //  sending the tokens
                       updateValueAtNow(balances[_from], previousBalanceFrom.sub(_amount));
            
                       // Then update the balance array with the new value for the address
                       //  receiving the tokens
                       var previousBalanceTo = balanceOfAt(_to, block.number);
                       updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
            
                       // An event to make the transfer easy to find on the blockchain
                       Transfer(_from, _to, _amount);
            
                       return true;
                }
            
                /// @param _owner The address that's balance is being requested
                /// @return The balance of `_owner` at the current block
                function balanceOf(address _owner) constant returns (uint256 balance) {
                    return balanceOfAt(_owner, block.number);
                }
            
                /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
                ///  its behalf. This is a modified version of the ERC20 approve function
                ///  to be a little bit safer
                /// @param _spender The address of the account able to transfer the tokens
                /// @param _amount The amount of tokens to be approved for transfer
                /// @return True if the approval was successful
                function approve(address _spender, uint256 _amount) returns (bool success) {
                    if (!transfersEnabled) throw;
            
                    // To change the approve amount you first have to reduce the addresses`
                    //  allowance to zero by calling `approve(_spender,0)` if it is not
                    //  already 0 to mitigate the race condition described here:
                    //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                    if ((_amount!=0) && (allowed[msg.sender][_spender] !=0)) throw;
            
                    // Alerts the token controller of the approve function call
                    if (isContract(controller)) {
                        if (!TokenController(controller).onApprove(msg.sender, _spender, _amount))
                            throw;
                    }
            
                    allowed[msg.sender][_spender] = _amount;
                    Approval(msg.sender, _spender, _amount);
                    return true;
                }
            
                /// @dev This function makes it easy to read the `allowed[]` map
                /// @param _owner The address of the account that owns the token
                /// @param _spender The address of the account able to transfer the tokens
                /// @return Amount of remaining tokens of _owner that _spender is allowed
                ///  to spend
                function allowance(address _owner, address _spender
                ) constant returns (uint256 remaining) {
                    return allowed[_owner][_spender];
                }
            
                /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
                ///  its behalf, and then a function is triggered in the contract that is
                ///  being approved, `_spender`. This allows users to use their tokens to
                ///  interact with contracts in one function call instead of two
                /// @param _spender The address of the contract able to transfer the tokens
                /// @param _amount The amount of tokens to be approved for transfer
                /// @return True if the function call was successful
                function approveAndCall(address _spender, uint256 _amount, bytes _extraData
                ) returns (bool success) {
                    if (!approve(_spender, _amount)) throw;
            
                    ApproveAndCallFallBack(_spender).receiveApproval(
                        msg.sender,
                        _amount,
                        this,
                        _extraData
                    );
            
                    return true;
                }
            
                /// @dev This function makes it easy to get the total number of tokens
                /// @return The total number of tokens
                function totalSupply() constant returns (uint) {
                    return totalSupplyAt(block.number);
                }
            
            
            ////////////////
            // Query balance and totalSupply in History
            ////////////////
            
                /// @dev Queries the balance of `_owner` at a specific `_blockNumber`
                /// @param _owner The address from which the balance will be retrieved
                /// @param _blockNumber The block number when the balance is queried
                /// @return The balance at `_blockNumber`
                function balanceOfAt(address _owner, uint _blockNumber) constant
                    returns (uint) {
            
                    // These next few lines are used when the balance of the token is
                    //  requested before a check point was ever created for this token, it
                    //  requires that the `parentToken.balanceOfAt` be queried at the
                    //  genesis block for that token as this contains initial balance of
                    //  this token
                    if ((balances[_owner].length == 0)
                        || (balances[_owner][0].fromBlock > _blockNumber)) {
                        if (address(parentToken) != 0) {
                            return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
                        } else {
                            // Has no parent
                            return 0;
                        }
            
                    // This will return the expected balance during normal situations
                    } else {
                        return getValueAt(balances[_owner], _blockNumber);
                    }
                }
            
                /// @notice Total amount of tokens at a specific `_blockNumber`.
                /// @param _blockNumber The block number when the totalSupply is queried
                /// @return The total amount of tokens at `_blockNumber`
                function totalSupplyAt(uint _blockNumber) constant returns(uint) {
            
                    // These next few lines are used when the totalSupply of the token is
                    //  requested before a check point was ever created for this token, it
                    //  requires that the `parentToken.totalSupplyAt` be queried at the
                    //  genesis block for this token as that contains totalSupply of this
                    //  token at this block number.
                    if ((totalSupplyHistory.length == 0)
                        || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
                        if (address(parentToken) != 0) {
                            return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
                        } else {
                            return 0;
                        }
            
                    // This will return the expected totalSupply during normal situations
                    } else {
                        return getValueAt(totalSupplyHistory, _blockNumber);
                    }
                }
            
            ////////////////
            // Clone Token Method
            ////////////////
            
                /// @notice Creates a new clone token with the initial distribution being
                ///  this token at `_snapshotBlock`
                /// @param _cloneTokenName Name of the clone token
                /// @param _cloneDecimalUnits Number of decimals of the smallest unit
                /// @param _cloneTokenSymbol Symbol of the clone token
                /// @param _snapshotBlock Block when the distribution of the parent token is
                ///  copied to set the initial distribution of the new clone token;
                ///  if the block is zero than the actual block, the current block is used
                /// @param _transfersEnabled True if transfers are allowed in the clone
                /// @return The address of the new MiniMeToken Contract
                function createCloneToken(
                    string _cloneTokenName,
                    uint8 _cloneDecimalUnits,
                    string _cloneTokenSymbol,
                    uint _snapshotBlock,
                    bool _transfersEnabled
                    ) returns(address) {
                    if (_snapshotBlock == 0) _snapshotBlock = block.number;
                    MiniMeToken cloneToken = tokenFactory.createCloneToken(
                        this,
                        _snapshotBlock,
                        _cloneTokenName,
                        _cloneDecimalUnits,
                        _cloneTokenSymbol,
                        _transfersEnabled
                        );
            
                    cloneToken.changeController(msg.sender);
            
                    // An event to make the token easy to find on the blockchain
                    NewCloneToken(address(cloneToken), _snapshotBlock);
                    return address(cloneToken);
                }
            
            ////////////////
            // Generate and destroy tokens
            ////////////////
            
                /// @notice Generates `_amount` tokens that are assigned to `_owner`
                /// @param _owner The address that will be assigned the new tokens
                /// @param _amount The quantity of tokens generated
                /// @return True if the tokens are generated correctly
                function generateTokens(address _owner, uint _amount
                ) onlyController returns (bool) {
                    uint curTotalSupply = getValueAt(totalSupplyHistory, block.number);
                    updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
                    var previousBalanceTo = balanceOf(_owner);
                    updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount));
                    Transfer(0, _owner, _amount);
                    return true;
                }
            
            
                /// @notice Burns `_amount` tokens from `_owner`
                /// @param _owner The address that will lose the tokens
                /// @param _amount The quantity of tokens to burn
                /// @return True if the tokens are burned correctly
                function destroyTokens(address _owner, uint _amount
                ) onlyController returns (bool) {
                    uint curTotalSupply = getValueAt(totalSupplyHistory, block.number);
                    if (curTotalSupply < _amount) throw;
                    updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount));
                    var previousBalanceFrom = balanceOf(_owner);
                    if (previousBalanceFrom < _amount) throw;
                    updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount));
                    Transfer(_owner, 0, _amount);
                    return true;
                }
            
            ////////////////
            // Enable tokens transfers
            ////////////////
            
            
                /// @notice Enables token holders to transfer their tokens freely if true
                /// @param _transfersEnabled True if transfers are allowed in the clone
                function enableTransfers(bool _transfersEnabled) onlyController {
                    transfersEnabled = _transfersEnabled;
                }
            
            ////////////////
            // Internal helper functions to query and set a value in a snapshot array
            ////////////////
            
                /// @dev `getValueAt` retrieves the number of tokens at a given block number
                /// @param checkpoints The history of values being queried
                /// @param _block The block number to retrieve the value at
                /// @return The number of tokens being queried
                function getValueAt(Checkpoint[] storage checkpoints, uint _block
                ) constant internal returns (uint) {
                    if (checkpoints.length == 0) return 0;
            
                    // Shortcut for the actual value
                    if (_block >= checkpoints[checkpoints.length-1].fromBlock)
                        return checkpoints[checkpoints.length-1].value;
                    if (_block < checkpoints[0].fromBlock) return 0;
            
                    // Binary search of the value in the array
                    uint min = 0;
                    uint max = checkpoints.length-1;
                    while (max > min) {
                        uint mid = (max + min + 1)/ 2;
                        if (checkpoints[mid].fromBlock<=_block) {
                            min = mid;
                        } else {
                            max = mid-1;
                        }
                    }
                    return checkpoints[min].value;
                }
            
                /// @dev `updateValueAtNow` used to update the `balances` map and the
                ///  `totalSupplyHistory`
                /// @param checkpoints The history of data being updated
                /// @param _value The new number of tokens
                function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
                ) internal  {
                    if ((checkpoints.length == 0)
                    || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
                           Checkpoint newCheckPoint = checkpoints[ checkpoints.length++ ];
                           newCheckPoint.fromBlock =  uint128(block.number);
                           newCheckPoint.value = uint128(_value);
                       } else {
                           Checkpoint oldCheckPoint = checkpoints[checkpoints.length-1];
                           oldCheckPoint.value = uint128(_value);
                       }
                }
            
                /// @dev Internal function to determine if an address is a contract
                /// @param _addr The address being queried
                /// @return True if `_addr` is a contract
                function isContract(address _addr) constant internal returns(bool) {
                    uint size;
                    if (_addr == 0) return false;
                    assembly {
                        size := extcodesize(_addr)
                    }
                    return size>0;
                }
            
                /// @dev Helper function to return a min betwen the two uints
                function min(uint a, uint b) internal returns (uint) {
                    return a < b ? a : b;
                }
            
                /// @notice The fallback function: If the contract's controller has not been
                ///  set to 0, then the `proxyPayment` method is called which relays the
                ///  ether and creates tokens as described in the token controller contract
                function ()  payable {
                    if (isContract(controller)) {
                        if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender))
                            throw;
                    } else {
                        throw;
                    }
                }
            
                //////////
                // Safety Methods
                //////////
            
                /// @notice This method can be used by the controller to extract mistakenly
                ///  sent tokens to this contract.
                /// @param _token The address of the token contract that you want to recover
                ///  set to 0 in case you want to extract ether.
                /// @param _claimer Address that tokens will be send to
                function claimTokens(address _token, address _claimer) onlyController {
                    if (_token == 0x0) {
                        _claimer.transfer(this.balance);
                        return;
                    }
            
                    ERC20Basic token = ERC20Basic(_token);
                    uint balance = token.balanceOf(this);
                    token.transfer(_claimer, balance);
                    ClaimedTokens(_token, _claimer, balance);
                }
            
            
            ////////////////
            // Events
            ////////////////
                event ClaimedTokens(address indexed _token, address indexed _claimer, uint _amount);
                event Transfer(address indexed _from, address indexed _to, uint256 _amount);
                event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
                event Approval(
                    address indexed _owner,
                    address indexed _spender,
                    uint256 _amount
                    );
            
            }
            
            
            ////////////////
            // MiniMeTokenFactory
            ////////////////
            
            /// @dev This contract is used to generate clone contracts from a contract.
            ///  In solidity this is the way to create a contract from a contract of the
            ///  same class
            contract MiniMeTokenFactory {
            
                /// @notice Update the DApp by creating a new token with new functionalities
                ///  the msg.sender becomes the controller of this clone token
                /// @param _parentToken Address of the token being cloned
                /// @param _snapshotBlock Block of the parent token that will
                ///  determine the initial distribution of the clone token
                /// @param _tokenName Name of the new token
                /// @param _decimalUnits Number of decimals of the new token
                /// @param _tokenSymbol Token Symbol for the new token
                /// @param _transfersEnabled If true, tokens will be able to be transferred
                /// @return The address of the new token contract
                function createCloneToken(
                    address _parentToken,
                    uint _snapshotBlock,
                    string _tokenName,
                    uint8 _decimalUnits,
                    string _tokenSymbol,
                    bool _transfersEnabled
                ) returns (MiniMeToken) {
                    MiniMeToken newToken = new MiniMeToken(
                        this,
                        _parentToken,
                        _snapshotBlock,
                        _tokenName,
                        _decimalUnits,
                        _tokenSymbol,
                        _transfersEnabled
                        );
            
                    newToken.changeController(msg.sender);
                    return newToken;
                }
            }
            
            contract VestedToken is LimitedTransferToken, GrantsControlled {
              using SafeMath for uint;
            
              uint256 MAX_GRANTS_PER_ADDRESS = 20;
            
              struct TokenGrant {
                address granter;     // 20 bytes
                uint256 value;       // 32 bytes
                uint64 cliff;
                uint64 vesting;
                uint64 start;        // 3 * 8 = 24 bytes
                bool revokable;
                bool burnsOnRevoke;  // 2 * 1 = 2 bits? or 2 bytes?
              } // total 78 bytes = 3 sstore per operation (32 per sstore)
            
              mapping (address => TokenGrant[]) public grants;
            
              event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
            
              /**
               * @dev Grant tokens to a specified address
               * @param _to address The address which the tokens will be granted to.
               * @param _value uint256 The amount of tokens to be granted.
               * @param _start uint64 Time of the beginning of the grant.
               * @param _cliff uint64 Time of the cliff period.
               * @param _vesting uint64 The vesting period.
               */
              function grantVestedTokens(
                address _to,
                uint256 _value,
                uint64 _start,
                uint64 _cliff,
                uint64 _vesting,
                bool _revokable,
                bool _burnsOnRevoke
              ) onlyGrantsController public {
            
                // Check for date inconsistencies that may cause unexpected behavior
                if (_cliff < _start || _vesting < _cliff) {
                  throw;
                }
            
                if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw;   // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
            
                uint count = grants[_to].push(
                            TokenGrant(
                              _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
                              _value,
                              _cliff,
                              _vesting,
                              _start,
                              _revokable,
                              _burnsOnRevoke
                            )
                          );
            
                transfer(_to, _value);
            
                NewTokenGrant(msg.sender, _to, _value, count - 1);
              }
            
              /**
               * @dev Revoke the grant of tokens of a specifed address.
               * @param _holder The address which will have its tokens revoked.
               * @param _grantId The id of the token grant.
               */
              function revokeTokenGrant(address _holder, uint _grantId) public {
                TokenGrant grant = grants[_holder][_grantId];
            
                if (!grant.revokable) { // Check if grant was revokable
                  throw;
                }
            
                if (grant.granter != msg.sender) { // Only granter can revoke it
                  throw;
                }
            
                address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
            
                uint256 nonVested = nonVestedTokens(grant, uint64(now));
            
                // remove grant from array
                delete grants[_holder][_grantId];
                grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
                grants[_holder].length -= 1;
            
                // This will call MiniMe's doTransfer method, so token is transferred according to
                // MiniMe Token logic
                doTransfer(_holder, receiver, nonVested);
            
                Transfer(_holder, receiver, nonVested);
              }
            
              /**
               * @dev Revoke all grants of tokens of a specifed address.
               * @param _holder The address which will have its tokens revoked.
               */
                function revokeAllTokenGrants(address _holder) {
                    var grandsCount = tokenGrantsCount(_holder);
                    for (uint i = 0; i < grandsCount; i++) {
                      revokeTokenGrant(_holder, 0);
                    }
                }
            
              /**
               * @dev Calculate the total amount of transferable tokens of a holder at a given time
               * @param holder address The address of the holder
               * @param time uint64 The specific time.
               * @return An uint representing a holder's total amount of transferable tokens.
               */
              function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
                uint256 grantIndex = tokenGrantsCount(holder);
            
                if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
            
                // Iterate through all the grants the holder has, and add all non-vested tokens
                uint256 nonVested = 0;
                for (uint256 i = 0; i < grantIndex; i++) {
                  nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
                }
            
                // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
                uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
            
                // Return the minimum of how many vested can transfer and other value
                // in case there are other limiting transferability factors (default is balanceOf)
                return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));
              }
            
              /**
               * @dev Check the amount of grants that an address has.
               * @param _holder The holder of the grants.
               * @return A uint representing the total amount of grants.
               */
              function tokenGrantsCount(address _holder) constant returns (uint index) {
                return grants[_holder].length;
              }
            
              /**
               * @dev Calculate amount of vested tokens at a specifc time.
               * @param tokens uint256 The amount of tokens grantted.
               * @param time uint64 The time to be checked
               * @param start uint64 A time representing the begining of the grant
               * @param cliff uint64 The cliff period.
               * @param vesting uint64 The vesting period.
               * @return An uint representing the amount of vested tokensof a specif grant.
               *  transferableTokens
               *   |                         _/--------   vestedTokens rect
               *   |                       _/
               *   |                     _/
               *   |                   _/
               *   |                 _/
               *   |                /
               *   |              .|
               *   |            .  |
               *   |          .    |
               *   |        .      |
               *   |      .        |
               *   |    .          |
               *   +===+===========+---------+----------> time
               *      Start       Clift    Vesting
               */
              function calculateVestedTokens(
                uint256 tokens,
                uint256 time,
                uint256 start,
                uint256 cliff,
                uint256 vesting) constant returns (uint256)
                {
                  // Shortcuts for before cliff and after vesting cases.
                  if (time < cliff) return 0;
                  if (time >= vesting) return tokens;
            
                  // Interpolate all vested tokens.
                  // As before cliff the shortcut returns 0, we can use just calculate a value
                  // in the vesting rect (as shown in above's figure)
            
                  // vestedTokens = tokens * (time - start) / (vesting - start)
                  uint256 vestedTokens = SafeMath.div(
                                                SafeMath.mul(
                                                  tokens,
                                                  SafeMath.sub(time, start)
                                                  ),
                                                SafeMath.sub(vesting, start)
                                                );
            
                  return vestedTokens;
              }
            
              /**
               * @dev Get all information about a specifc grant.
               * @param _holder The address which will have its tokens revoked.
               * @param _grantId The id of the token grant.
               * @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
               * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
               */
              function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
                TokenGrant grant = grants[_holder][_grantId];
            
                granter = grant.granter;
                value = grant.value;
                start = grant.start;
                cliff = grant.cliff;
                vesting = grant.vesting;
                revokable = grant.revokable;
                burnsOnRevoke = grant.burnsOnRevoke;
            
                vested = vestedTokens(grant, uint64(now));
              }
            
              /**
               * @dev Get the amount of vested tokens at a specific time.
               * @param grant TokenGrant The grant to be checked.
               * @param time The time to be checked
               * @return An uint representing the amount of vested tokens of a specific grant at a specific time.
               */
              function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
                return calculateVestedTokens(
                  grant.value,
                  uint256(time),
                  uint256(grant.start),
                  uint256(grant.cliff),
                  uint256(grant.vesting)
                );
              }
            
              /**
               * @dev Calculate the amount of non vested tokens at a specific time.
               * @param grant TokenGrant The grant to be checked.
               * @param time uint64 The time to be checked
               * @return An uint representing the amount of non vested tokens of a specifc grant on the
               * passed time frame.
               */
              function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
                return grant.value.sub(vestedTokens(grant, time));
              }
            
              /**
               * @dev Calculate the date when the holder can trasfer all its tokens
               * @param holder address The address of the holder
               * @return An uint representing the date of the last transferable tokens.
               */
              function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
                date = uint64(now);
                uint256 grantIndex = grants[holder].length;
                for (uint256 i = 0; i < grantIndex; i++) {
                  date = SafeMath.max64(grants[holder][i].vesting, date);
                }
              }
            }
            
            contract ApproveAndCallFallBack {
                function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
            }
            
            
            contract TokenController {
                /// @notice Called when `_owner` sends ether to the MiniMe Token contract
                /// @param _owner The address that sent the ether to create tokens
                /// @return True if the ether is accepted, false if it throws
                function proxyPayment(address _owner) payable returns(bool);
            
                /// @notice Notifies the controller about a token transfer allowing the
                ///  controller to react if desired
                /// @param _from The origin of the transfer
                /// @param _to The destination of the transfer
                /// @param _amount The amount of the transfer
                /// @return False if the controller does not authorize the transfer
                function onTransfer(address _from, address _to, uint _amount) returns(bool);
            
                /// @notice Notifies the controller about an approval allowing the
                ///  controller to react if desired
                /// @param _owner The address that calls `approve()`
                /// @param _spender The spender in the `approve()` call
                /// @param _amount The amount in the `approve()` call
                /// @return False if the controller does not authorize the approval
                function onApprove(address _owner, address _spender, uint _amount)
                    returns(bool);
            }
            
            contract District0xNetworkToken is MiniMeToken, VestedToken {
                function District0xNetworkToken(address _controller, address _tokenFactory)
                    MiniMeToken(
                        _tokenFactory,
                        0x0,                        // no parent token
                        0,                          // no snapshot block number from parent
                        "district0x Network Token", // Token name
                        18,                         // Decimals
                        "DNT",                      // Symbol
                        true                        // Enable transfers
                        )
                {
                    changeController(_controller);
                    changeGrantsController(_controller);
                }
            }
            
            contract HasNoTokens is Ownable {
            
              District0xNetworkToken public district0xNetworkToken;
            
             /**
              * @dev Reject all ERC23 compatible tokens
              * @param from_ address The address that is transferring the tokens
              * @param value_ uint256 the amount of the specified token
              * @param data_ Bytes The data passed from the caller.
              */
              function tokenFallback(address from_, uint256 value_, bytes data_) external {
                throw;
              }
            
              function isTokenSaleToken(address tokenAddr) returns(bool);
            
              /**
               * @dev Reclaim all ERC20Basic compatible tokens
               * @param tokenAddr address The address of the token contract
               */
              function reclaimToken(address tokenAddr) external onlyOwner {
                require(!isTokenSaleToken(tokenAddr));
                ERC20Basic tokenInst = ERC20Basic(tokenAddr);
                uint256 balance = tokenInst.balanceOf(this);
                tokenInst.transfer(msg.sender, balance);
              }
            }
            
            
            contract District0xContribution is Pausable, HasNoTokens, TokenController {
                using SafeMath for uint;
            
                District0xNetworkToken public district0xNetworkToken;
                address public multisigWallet;                                      // Wallet that receives all sale funds
                address public founder1;                                            // Wallet of founder 1
                address public founder2;                                            // Wallet of founder 2
                address public earlySponsor;                                        // Wallet of early sponsor
                address[] public advisers;                                          // 4 Wallets of advisors
            
                uint public constant FOUNDER1_STAKE = 119000000 ether;              // 119M DNT
                uint public constant FOUNDER2_STAKE = 79000000 ether;               // 79M  DNT
                uint public constant EARLY_CONTRIBUTOR_STAKE = 5000000 ether;       // 5M   DNT
                uint public constant ADVISER_STAKE = 5000000 ether;                 // 5M   DNT
                uint public constant ADVISER_STAKE2 = 1000000 ether;                // 1M   DNT
                uint public constant COMMUNITY_ADVISERS_STAKE = 5000000 ether;      // 5M   DNT
                uint public constant CONTRIB_PERIOD1_STAKE = 600000000 ether;       // 600M DNT
                uint public constant CONTRIB_PERIOD2_STAKE = 140000000 ether;       // 140M DNT
                uint public constant CONTRIB_PERIOD3_STAKE = 40000000 ether;        // 40M  DNT
            
                uint public minContribAmount = 0.01 ether;                          // 0.01 ether
                uint public maxGasPrice = 50000000000;                              // 50 GWei
            
                uint public constant TEAM_VESTING_CLIFF = 24 weeks;                 // 6 months vesting cliff for founders and advisors, except community advisors
                uint public constant TEAM_VESTING_PERIOD = 96 weeks;                // 2 years vesting period for founders and advisors, except community advisors
            
                uint public constant EARLY_CONTRIBUTOR_VESTING_CLIFF = 12 weeks;    // 3 months vesting cliff for early sponsor
                uint public constant EARLY_CONTRIBUTOR_VESTING_PERIOD = 24 weeks;   // 6 months vesting cliff for early sponsor
            
                bool public tokenTransfersEnabled = false;                          // DNT token transfers will be enabled manually
                                                                                    // after first contribution period
                                                                                    // Can't be disabled back
                struct Contributor {
                    uint amount;                        // Amount of ETH contributed by an address in given contribution period
                    bool isCompensated;                 // Whether this contributor received DNT token for ETH contribution
                    uint amountCompensated;             // Amount of DNT received. Not really needed to store,
                                                        // but stored for accounting and security purposes
                }
            
                uint public softCapAmount;                                 // Soft cap of contribution period in wei
                uint public afterSoftCapDuration;                          // Number of seconds to the end of sale from the moment of reaching soft cap (unless reaching hardcap)
                uint public hardCapAmount;                                 // When reached this amount of wei, the contribution will end instantly
                uint public startTime;                                     // Start time of contribution period in UNIX time
                uint public endTime;                                       // End time of contribution period in UNIX time
                bool public isEnabled;                                     // If contribution period was enabled by multisignature
                bool public softCapReached;                                // If soft cap was reached
                bool public hardCapReached;                                // If hard cap was reached
                uint public totalContributed;                              // Total amount of ETH contributed in given period
                address[] public contributorsKeys;                         // Addresses of all contributors in given contribution period
                mapping (address => Contributor) public contributors;
            
                event onContribution(uint totalContributed, address indexed contributor, uint amount,
                    uint contributorsCount);
                event onSoftCapReached(uint endTime);
                event onHardCapReached(uint endTime);
                event onCompensated(address indexed contributor, uint amount);
            
                modifier onlyMultisig() {
                    require(multisigWallet == msg.sender);
                    _;
                }
            
                function District0xContribution(
                    address _multisigWallet,
                    address _founder1,
                    address _founder2,
                    address _earlySponsor,
                    address[] _advisers
                ) {
                    require(_advisers.length == 5);
                    multisigWallet = _multisigWallet;
                    founder1 = _founder1;
                    founder2 = _founder2;
                    earlySponsor = _earlySponsor;
                    advisers = _advisers;
                }
            
                // @notice Returns true if contribution period is currently running
                function isContribPeriodRunning() constant returns (bool) {
                    return !hardCapReached &&
                           isEnabled &&
                           startTime <= now &&
                           endTime > now;
                }
            
                function contribute()
                    payable
                    stopInEmergency
                {
                    contributeWithAddress(msg.sender);
                }
            
                // @notice Function to participate in contribution period
                //  Amounts from the same address should be added up
                //  If soft or hard cap is reached, end time should be modified
                //  Funds should be transferred into multisig wallet
                // @param contributor Address that will receive DNT token
                function contributeWithAddress(address contributor)
                    payable
                    stopInEmergency
                {
                    require(tx.gasprice <= maxGasPrice);
                    require(msg.value >= minContribAmount);
                    require(isContribPeriodRunning());
            
                    uint contribValue = msg.value;
                    uint excessContribValue = 0;
            
                    uint oldTotalContributed = totalContributed;
            
                    totalContributed = oldTotalContributed.add(contribValue);
            
                    uint newTotalContributed = totalContributed;
            
                    // Soft cap was reached
                    if (newTotalContributed >= softCapAmount &&
                        oldTotalContributed < softCapAmount)
                    {
                        softCapReached = true;
                        endTime = afterSoftCapDuration.add(now);
                        onSoftCapReached(endTime);
                    }
                    // Hard cap was reached
                    if (newTotalContributed >= hardCapAmount &&
                        oldTotalContributed < hardCapAmount)
                    {
                        hardCapReached = true;
                        endTime = now;
                        onHardCapReached(endTime);
            
                        // Everything above hard cap will be sent back to contributor
                        excessContribValue = newTotalContributed.sub(hardCapAmount);
                        contribValue = contribValue.sub(excessContribValue);
            
                        totalContributed = hardCapAmount;
                    }
            
                    if (contributors[contributor].amount == 0) {
                        contributorsKeys.push(contributor);
                    }
            
                    contributors[contributor].amount = contributors[contributor].amount.add(contribValue);
            
                    multisigWallet.transfer(contribValue);
                    if (excessContribValue > 0) {
                        msg.sender.transfer(excessContribValue);
                    }
                    onContribution(newTotalContributed, contributor, contribValue, contributorsKeys.length);
                }
            
                // @notice This method is called by owner after contribution period ends, to distribute DNT in proportional manner
                //  Each contributor should receive DNT just once even if this method is called multiple times
                //  In case of many contributors must be able to compensate contributors in paginational way, otherwise might
                //  run out of gas if wanted to compensate all on one method call. Therefore parameters offset and limit
                // @param periodIndex Index of contribution period (0-2)
                // @param offset Number of first contributors to skip.
                // @param limit Max number of contributors compensated on this call
                function compensateContributors(uint offset, uint limit)
                    onlyOwner
                {
                    require(isEnabled);
                    require(endTime < now);
            
                    uint i = offset;
                    uint compensatedCount = 0;
                    uint contributorsCount = contributorsKeys.length;
            
                    uint ratio = CONTRIB_PERIOD1_STAKE
                        .mul(1000000000000000000)
                        .div(totalContributed);
            
                    while (i < contributorsCount && compensatedCount < limit) {
                        address contributorAddress = contributorsKeys[i];
                        if (!contributors[contributorAddress].isCompensated) {
                            uint amountContributed = contributors[contributorAddress].amount;
                            contributors[contributorAddress].isCompensated = true;
            
                            contributors[contributorAddress].amountCompensated =
                                amountContributed.mul(ratio).div(1000000000000000000);
            
                            district0xNetworkToken.transfer(contributorAddress, contributors[contributorAddress].amountCompensated);
                            onCompensated(contributorAddress, contributors[contributorAddress].amountCompensated);
            
                            compensatedCount++;
                        }
                        i++;
                    }
                }
            
                // @notice Method for setting up contribution period
                //  Only owner should be able to execute
                //  Setting first contribution period sets up vesting for founders & advisors
                //  Contribution period should still not be enabled after calling this method
                // @param softCapAmount Soft Cap in wei
                // @param afterSoftCapDuration Number of seconds till the end of sale in the moment of reaching soft cap (unless reaching hard cap)
                // @param hardCapAmount Hard Cap in wei
                // @param startTime Contribution start time in UNIX time
                // @param endTime Contribution end time in UNIX time
                function setContribPeriod(
                    uint _softCapAmount,
                    uint _afterSoftCapDuration,
                    uint _hardCapAmount,
                    uint _startTime,
                    uint _endTime
                )
                    onlyOwner
                {
                    require(_softCapAmount > 0);
                    require(_hardCapAmount > _softCapAmount);
                    require(_afterSoftCapDuration > 0);
                    require(_startTime > now);
                    require(_endTime > _startTime);
                    require(!isEnabled);
            
                    softCapAmount = _softCapAmount;
                    afterSoftCapDuration = _afterSoftCapDuration;
                    hardCapAmount = _hardCapAmount;
                    startTime = _startTime;
                    endTime = _endTime;
            
                    district0xNetworkToken.revokeAllTokenGrants(founder1);
                    district0xNetworkToken.revokeAllTokenGrants(founder2);
                    district0xNetworkToken.revokeAllTokenGrants(earlySponsor);
            
                    for (uint j = 0; j < advisers.length; j++) {
                        district0xNetworkToken.revokeAllTokenGrants(advisers[j]);
                    }
            
                    uint64 vestingDate = uint64(startTime.add(TEAM_VESTING_PERIOD));
                    uint64 cliffDate = uint64(startTime.add(TEAM_VESTING_CLIFF));
                    uint64 earlyContribVestingDate = uint64(startTime.add(EARLY_CONTRIBUTOR_VESTING_PERIOD));
                    uint64 earlyContribCliffDate = uint64(startTime.add(EARLY_CONTRIBUTOR_VESTING_CLIFF));
                    uint64 startDate = uint64(startTime);
            
                    district0xNetworkToken.grantVestedTokens(founder1, FOUNDER1_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(founder2, FOUNDER2_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(earlySponsor, EARLY_CONTRIBUTOR_STAKE, startDate, earlyContribCliffDate, earlyContribVestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[0], ADVISER_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[1], ADVISER_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[2], ADVISER_STAKE2, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[3], ADVISER_STAKE2, startDate, cliffDate, vestingDate, true, false);
            
                    // Community advisors stake has no vesting, but we set it up this way, so we can revoke it in case of
                    // re-setting up contribution period
                    district0xNetworkToken.grantVestedTokens(advisers[4], COMMUNITY_ADVISERS_STAKE, startDate, startDate, startDate, true, false);
                }
            
                // @notice Enables contribution period
                //  Must be executed by multisignature
                function enableContribPeriod()
                    onlyMultisig
                {
                    require(startTime > now);
                    isEnabled = true;
                }
            
                // @notice Sets new min. contribution amount
                //  Only owner can execute
                //  Cannot be executed while contribution period is running
                // @param _minContribAmount new min. amount
                function setMinContribAmount(uint _minContribAmount)
                    onlyOwner
                {
                    require(_minContribAmount > 0);
                    require(startTime > now);
                    minContribAmount = _minContribAmount;
                }
            
                // @notice Sets new max gas price for contribution
                //  Only owner can execute
                //  Cannot be executed while contribution period is running
                // @param _minContribAmount new min. amount
                function setMaxGasPrice(uint _maxGasPrice)
                    onlyOwner
                {
                    require(_maxGasPrice > 0);
                    require(startTime > now);
                    maxGasPrice = _maxGasPrice;
                }
            
                // @notice Sets District0xNetworkToken contract
                //  Generates all DNT tokens and assigns them to this contract
                //  If token contract has already generated tokens, do not generate again
                // @param _district0xNetworkToken District0xNetworkToken address
                function setDistrict0xNetworkToken(address _district0xNetworkToken)
                    onlyOwner
                {
                    require(_district0xNetworkToken != 0x0);
                    require(!isEnabled);
                    district0xNetworkToken = District0xNetworkToken(_district0xNetworkToken);
                    if (district0xNetworkToken.totalSupply() == 0) {
                        district0xNetworkToken.generateTokens(this, FOUNDER1_STAKE
                            .add(FOUNDER2_STAKE)
                            .add(EARLY_CONTRIBUTOR_STAKE)
                            .add(ADVISER_STAKE.mul(2))
                            .add(ADVISER_STAKE2.mul(2))
                            .add(COMMUNITY_ADVISERS_STAKE)
                            .add(CONTRIB_PERIOD1_STAKE));
            
                        district0xNetworkToken.generateTokens(multisigWallet, CONTRIB_PERIOD2_STAKE
                            .add(CONTRIB_PERIOD3_STAKE));
                    }
                }
            
                // @notice Enables transfers of DNT
                //  Will be executed after first contribution period by owner
                function enableDistrict0xNetworkTokenTransfers()
                    onlyOwner
                {
                    require(endTime < now);
                    tokenTransfersEnabled = true;
                }
            
                // @notice Method to claim tokens accidentally sent to a DNT contract
                //  Only multisig wallet can execute
                // @param _token Address of claimed ERC20 Token
                function claimTokensFromTokenDistrict0xNetworkToken(address _token)
                    onlyMultisig
                {
                    district0xNetworkToken.claimTokens(_token, multisigWallet);
                }
            
                // @notice Kill method should not really be needed, but just in case
                function kill(address _to) onlyMultisig external {
                    suicide(_to);
                }
            
                function()
                    payable
                    stopInEmergency
                {
                    contributeWithAddress(msg.sender);
                }
            
                // MiniMe Controller default settings for allowing token transfers.
                function proxyPayment(address _owner) payable public returns (bool) {
                    throw;
                }
            
                // Before transfers are enabled for everyone, only this contract is allowed to distribute DNT
                function onTransfer(address _from, address _to, uint _amount) public returns (bool) {
                    return tokenTransfersEnabled || _from == address(this) || _to == address(this);
                }
            
                function onApprove(address _owner, address _spender, uint _amount) public returns (bool) {
                    return tokenTransfersEnabled;
                }
            
                function isTokenSaleToken(address tokenAddr) returns(bool) {
                    return district0xNetworkToken == tokenAddr;
                }
            
                /*
                 Following constant methods are used for tests and contribution web app
                 They don't impact logic of contribution contract, therefor DOES NOT NEED TO BE AUDITED
                 */
            
                // Used by contribution front-end to obtain contribution period properties
                function getContribPeriod()
                    constant
                    returns (bool[3] boolValues, uint[8] uintValues)
                {
                    boolValues[0] = isEnabled;
                    boolValues[1] = softCapReached;
                    boolValues[2] = hardCapReached;
            
                    uintValues[0] = softCapAmount;
                    uintValues[1] = afterSoftCapDuration;
                    uintValues[2] = hardCapAmount;
                    uintValues[3] = startTime;
                    uintValues[4] = endTime;
                    uintValues[5] = totalContributed;
                    uintValues[6] = contributorsKeys.length;
                    uintValues[7] = CONTRIB_PERIOD1_STAKE;
            
                    return (boolValues, uintValues);
                }
            
                // Used by contribution front-end to obtain contribution contract properties
                function getConfiguration()
                    constant
                    returns (bool, address, address, address, address, address[] _advisers, bool, uint)
                {
                    _advisers = new address[](advisers.length);
                    for (uint i = 0; i < advisers.length; i++) {
                        _advisers[i] = advisers[i];
                    }
                    return (stopped, multisigWallet, founder1, founder2, earlySponsor, _advisers, tokenTransfersEnabled,
                        maxGasPrice);
                }
            
                // Used by contribution front-end to obtain contributor's properties
                function getContributor(address contributorAddress)
                    constant
                    returns(uint, bool, uint)
                {
                    Contributor contributor = contributors[contributorAddress];
                    return (contributor.amount, contributor.isCompensated, contributor.amountCompensated);
                }
            
                // Function to verify if all contributors were compensated
                function getUncompensatedContributors(uint offset, uint limit)
                    constant
                    returns (uint[] contributorIndexes)
                {
                    uint contributorsCount = contributorsKeys.length;
            
                    if (limit == 0) {
                        limit = contributorsCount;
                    }
            
                    uint i = offset;
                    uint resultsCount = 0;
                    uint[] memory _contributorIndexes = new uint[](limit);
            
                    while (i < contributorsCount && resultsCount < limit) {
                        if (!contributors[contributorsKeys[i]].isCompensated) {
                            _contributorIndexes[resultsCount] = i;
                            resultsCount++;
                        }
                        i++;
                    }
            
                    contributorIndexes = new uint[](resultsCount);
                    for (i = 0; i < resultsCount; i++) {
                        contributorIndexes[i] = _contributorIndexes[i];
                    }
                    return contributorIndexes;
                }
            
                function getNow()
                    constant
                    returns(uint)
                {
                    return now;
                }
            }

            File 4 of 7: HOPToken
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.2;
            import "./MerkleProof.sol";
            import "@openzeppelin/contracts/access/Ownable.sol";
            import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
            import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
            import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
            import "@openzeppelin/contracts/utils/structs/BitMaps.sol";
            /**
             * @dev An ERC20 token for HOP.
             *      Besides the addition of voting capabilities, we make a couple of customisations:
             *       - Airdrop claim functionality via `claimTokens`. At creation time the tokens that
             *         should be available for the airdrop are transferred to the token contract address;
             *         airdrop claims are made from this balance.
             *       - Support for the owner (the DAO) to mint new tokens.
             */
            contract HOPToken is ERC20, ERC20Permit, ERC20Votes, Ownable {
                using BitMaps for BitMaps.BitMap;
                bytes32 public merkleRoot;
                uint256 public claimPeriodEnds; // Timestamp
                BitMaps.BitMap private claimed;
                event MerkleRootChanged(bytes32 merkleRoot);
                event Claim(address indexed claimant, uint256 amount);
                /**
                 * @dev Constructor.
                 * @param freeSupply The number of tokens to issue to the contract deployer.
                 * @param airdropSupply The number of tokens to reserve for the airdrop.
                 * @param _claimPeriodEnds The timestamp at which tokens are no longer claimable.
                 */
                constructor(
                    uint256 freeSupply,
                    uint256 airdropSupply,
                    uint256 _claimPeriodEnds
                )
                    ERC20("Hop", "HOP")
                    ERC20Permit("Hop")
                {
                    _mint(msg.sender, freeSupply);
                    _mint(address(this), airdropSupply);
                    claimPeriodEnds = _claimPeriodEnds;
                }
                /**
                 * @dev Claims airdropped tokens.
                 * @param amount The amount of the claim being made.
                 * @param delegate The address the tokenholder wants to delegate their votes to.
                 * @param merkleProof A merkle proof proving the claim is valid.
                 */
                function claimTokens(uint256 amount, address delegate, bytes32[] calldata merkleProof) external {
                    bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount));
                    (bool valid, uint256 index) = MerkleProof.verify(merkleProof, merkleRoot, leaf);
                    require(valid, "HOP: Valid proof required.");
                    require(!isClaimed(index), "HOP: Tokens already claimed.");
                    
                    claimed.set(index);
                    emit Claim(msg.sender, amount);
                    _delegate(msg.sender, delegate);
                    _transfer(address(this), msg.sender, amount);
                }
                /**
                 * @dev Allows the owner to sweep unclaimed tokens after the claim period ends.
                 * @param dest The address to sweep the tokens to.
                 */
                function sweep(address dest) external onlyOwner {
                    require(block.timestamp > claimPeriodEnds, "HOP: Claim period not yet ended");
                    _transfer(address(this), dest, balanceOf(address(this)));
                }
                /**
                 * @dev Returns true if the claim at the given index in the merkle tree has already been made.
                 * @param index The index into the merkle tree.
                 */
                function isClaimed(uint256 index) public view returns (bool) {
                    return claimed.get(index);
                }
                /**
                 * @dev Sets the merkle root. Only callable if the root is not yet set.
                 * @param _merkleRoot The merkle root to set.
                 */
                function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
                    require(merkleRoot == bytes32(0), "HOP: Merkle root already set");
                    merkleRoot = _merkleRoot;
                    emit MerkleRootChanged(_merkleRoot);
                }
                /**
                 * @dev Mints new tokens.
                 * @param dest The address to mint the new tokens to.
                 * @param amount The quantity of tokens to mint.
                 */
                function mint(address dest, uint256 amount) external onlyOwner {
                    _mint(dest, amount);
                }
                /**
                 * @dev Burns the owner's tokens.
                 * @param amount The quantity of tokens to burn.
                 */
                function burn(uint256 amount) external onlyOwner {
                    _burn(owner(), amount);
                }
                // The following functions are overrides required by Solidity.
                function _afterTokenTransfer(address from, address to, uint256 amount)
                    internal
                    override(ERC20, ERC20Votes)
                {
                    super._afterTokenTransfer(from, to, amount);
                }
                function _mint(address to, uint256 amount)
                    internal
                    override(ERC20, ERC20Votes)
                {
                    super._mint(to, amount);
                }
                function _burn(address account, uint256 amount)
                    internal
                    override(ERC20, ERC20Votes)
                {
                    super._burn(account, amount);
                }
            }
            // SPDX-License-Identifier: MIT
            // Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/cryptography/MerkleProof.sol
            pragma solidity ^0.8.0;
            /**
             * @dev These functions deal with verification of Merkle Trees proofs.
             *
             * The proofs can be generated using the JavaScript library
             * https://github.com/miguelmota/merkletreejs[merkletreejs].
             * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
             *
             * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
             */
            library MerkleProof {
                /**
                 * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
                 * defined by `root`. For this, a `proof` must be provided, containing
                 * sibling hashes on the branch from the leaf to the root of the tree. Each
                 * pair of leaves and each pair of pre-images are assumed to be sorted.
                 */
                function verify(
                    bytes32[] memory proof,
                    bytes32 root,
                    bytes32 leaf
                ) internal pure returns (bool, uint256) {
                    bytes32 computedHash = leaf;
                    uint256 index = 0;
                    for (uint256 i = 0; i < proof.length; i++) {
                        index *= 2;
                        bytes32 proofElement = proof[i];
                        if (computedHash <= proofElement) {
                            // Hash(current computed hash + current element of the proof)
                            computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
                        } else {
                            // Hash(current element of the proof + current computed hash)
                            computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
                            index += 1;
                        }
                    }
                    // Check if the computed hash (root) is equal to the provided root
                    return (computedHash == root, index);
                }
            }// SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
            pragma solidity ^0.8.0;
            import "../utils/Context.sol";
            /**
             * @dev Contract module which provides a basic access control mechanism, where
             * there is an account (an owner) that can be granted exclusive access to
             * specific functions.
             *
             * By default, the owner account will be the one that deploys the contract. This
             * can later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract Ownable is Context {
                address private _owner;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                constructor() {
                    _transferOwnership(_msgSender());
                }
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    _;
                }
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby removing any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    _transferOwnership(address(0));
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Can only be called by the current owner.
                 */
                function transferOwnership(address newOwner) public virtual onlyOwner {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    _transferOwnership(newOwner);
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Internal function without access restriction.
                 */
                function _transferOwnership(address newOwner) internal virtual {
                    address oldOwner = _owner;
                    _owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
             * to implement supply mechanisms].
             *
             * We have followed general OpenZeppelin Contracts guidelines: functions revert
             * instead returning `false` on failure. This behavior is nonetheless
             * conventional and does not conflict with the expectations of ERC20
             * applications.
             *
             * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
             * This allows applications to reconstruct the allowance for all accounts just
             * by listening to said events. Other implementations of the EIP may not emit
             * these events, as it isn't required by the specification.
             *
             * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
             * functions have been added to mitigate the well-known issues around setting
             * allowances. See {IERC20-approve}.
             */
            contract ERC20 is Context, IERC20, IERC20Metadata {
                mapping(address => uint256) private _balances;
                mapping(address => mapping(address => uint256)) private _allowances;
                uint256 private _totalSupply;
                string private _name;
                string private _symbol;
                /**
                 * @dev Sets the values for {name} and {symbol}.
                 *
                 * The default value of {decimals} is 18. To select a different value for
                 * {decimals} you should overload it.
                 *
                 * All two of these values are immutable: they can only be set once during
                 * construction.
                 */
                constructor(string memory name_, string memory symbol_) {
                    _name = name_;
                    _symbol = symbol_;
                }
                /**
                 * @dev Returns the name of the token.
                 */
                function name() public view virtual override returns (string memory) {
                    return _name;
                }
                /**
                 * @dev Returns the symbol of the token, usually a shorter version of the
                 * name.
                 */
                function symbol() public view virtual override returns (string memory) {
                    return _symbol;
                }
                /**
                 * @dev Returns the number of decimals used to get its user representation.
                 * For example, if `decimals` equals `2`, a balance of `505` tokens should
                 * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                 *
                 * Tokens usually opt for a value of 18, imitating the relationship between
                 * Ether and Wei. This is the value {ERC20} uses, unless this function is
                 * overridden;
                 *
                 * NOTE: This information is only used for _display_ purposes: it in
                 * no way affects any of the arithmetic of the contract, including
                 * {IERC20-balanceOf} and {IERC20-transfer}.
                 */
                function decimals() public view virtual override returns (uint8) {
                    return 18;
                }
                /**
                 * @dev See {IERC20-totalSupply}.
                 */
                function totalSupply() public view virtual override returns (uint256) {
                    return _totalSupply;
                }
                /**
                 * @dev See {IERC20-balanceOf}.
                 */
                function balanceOf(address account) public view virtual override returns (uint256) {
                    return _balances[account];
                }
                /**
                 * @dev See {IERC20-transfer}.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - the caller must have a balance of at least `amount`.
                 */
                function transfer(address to, uint256 amount) public virtual override returns (bool) {
                    address owner = _msgSender();
                    _transfer(owner, to, amount);
                    return true;
                }
                /**
                 * @dev See {IERC20-allowance}.
                 */
                function allowance(address owner, address spender) public view virtual override returns (uint256) {
                    return _allowances[owner][spender];
                }
                /**
                 * @dev See {IERC20-approve}.
                 *
                 * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                 * `transferFrom`. This is semantically equivalent to an infinite approval.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function approve(address spender, uint256 amount) public virtual override returns (bool) {
                    address owner = _msgSender();
                    _approve(owner, spender, amount);
                    return true;
                }
                /**
                 * @dev See {IERC20-transferFrom}.
                 *
                 * Emits an {Approval} event indicating the updated allowance. This is not
                 * required by the EIP. See the note at the beginning of {ERC20}.
                 *
                 * NOTE: Does not update the allowance if the current allowance
                 * is the maximum `uint256`.
                 *
                 * Requirements:
                 *
                 * - `from` and `to` cannot be the zero address.
                 * - `from` must have a balance of at least `amount`.
                 * - the caller must have allowance for ``from``'s tokens of at least
                 * `amount`.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 amount
                ) public virtual override returns (bool) {
                    address spender = _msgSender();
                    _spendAllowance(from, spender, amount);
                    _transfer(from, to, amount);
                    return true;
                }
                /**
                 * @dev Atomically increases the allowance granted to `spender` by the caller.
                 *
                 * This is an alternative to {approve} that can be used as a mitigation for
                 * problems described in {IERC20-approve}.
                 *
                 * Emits an {Approval} event indicating the updated allowance.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                    address owner = _msgSender();
                    _approve(owner, spender, _allowances[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 = _allowances[owner][spender];
                    require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                    unchecked {
                        _approve(owner, spender, currentAllowance - subtractedValue);
                    }
                    return true;
                }
                /**
                 * @dev Moves `amount` of tokens from `sender` to `recipient`.
                 *
                 * 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;
                    }
                    _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;
                    _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;
                    }
                    _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 Spend `amount` form the allowance of `owner` toward `spender`.
                 *
                 * 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 v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
            pragma solidity ^0.8.0;
            import "./draft-IERC20Permit.sol";
            import "../ERC20.sol";
            import "../../../utils/cryptography/draft-EIP712.sol";
            import "../../../utils/cryptography/ECDSA.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 immutable _PERMIT_TYPEHASH =
                    keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                /**
                 * @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) (token/ERC20/extensions/ERC20Votes.sol)
            pragma solidity ^0.8.0;
            import "./draft-ERC20Permit.sol";
            import "../../../utils/math/Math.sol";
            import "../../../governance/utils/IVotes.sol";
            import "../../../utils/math/SafeCast.sol";
            import "../../../utils/cryptography/ECDSA.sol";
            /**
             * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
             * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
             *
             * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
             *
             * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
             * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
             * power can be queried through the public accessors {getVotes} and {getPastVotes}.
             *
             * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
             * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
             *
             * _Available since v4.2._
             */
            abstract contract ERC20Votes is IVotes, ERC20Permit {
                struct Checkpoint {
                    uint32 fromBlock;
                    uint224 votes;
                }
                bytes32 private constant _DELEGATION_TYPEHASH =
                    keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
                mapping(address => address) private _delegates;
                mapping(address => Checkpoint[]) private _checkpoints;
                Checkpoint[] private _totalSupplyCheckpoints;
                /**
                 * @dev Get the `pos`-th checkpoint for `account`.
                 */
                function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
                    return _checkpoints[account][pos];
                }
                /**
                 * @dev Get number of checkpoints for `account`.
                 */
                function numCheckpoints(address account) public view virtual returns (uint32) {
                    return SafeCast.toUint32(_checkpoints[account].length);
                }
                /**
                 * @dev Get the address `account` is currently delegating to.
                 */
                function delegates(address account) public view virtual override returns (address) {
                    return _delegates[account];
                }
                /**
                 * @dev Gets the current votes balance for `account`
                 */
                function getVotes(address account) public view virtual override returns (uint256) {
                    uint256 pos = _checkpoints[account].length;
                    return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
                }
                /**
                 * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
                 *
                 * Requirements:
                 *
                 * - `blockNumber` must have been already mined
                 */
                function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
                    require(blockNumber < block.number, "ERC20Votes: block not yet mined");
                    return _checkpointsLookup(_checkpoints[account], blockNumber);
                }
                /**
                 * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
                 * It is but NOT the sum of all the delegated votes!
                 *
                 * Requirements:
                 *
                 * - `blockNumber` must have been already mined
                 */
                function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
                    require(blockNumber < block.number, "ERC20Votes: block not yet mined");
                    return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
                }
                /**
                 * @dev Lookup a value in a list of (sorted) checkpoints.
                 */
                function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
                    // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
                    //
                    // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
                    // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
                    // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
                    // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
                    // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
                    // out of bounds (in which case we're looking too far in the past and the result is 0).
                    // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
                    // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
                    // the same.
                    uint256 high = ckpts.length;
                    uint256 low = 0;
                    while (low < high) {
                        uint256 mid = Math.average(low, high);
                        if (ckpts[mid].fromBlock > blockNumber) {
                            high = mid;
                        } else {
                            low = mid + 1;
                        }
                    }
                    return high == 0 ? 0 : ckpts[high - 1].votes;
                }
                /**
                 * @dev Delegate votes from the sender to `delegatee`.
                 */
                function delegate(address delegatee) public virtual override {
                    _delegate(_msgSender(), delegatee);
                }
                /**
                 * @dev Delegates votes from signer to `delegatee`
                 */
                function delegateBySig(
                    address delegatee,
                    uint256 nonce,
                    uint256 expiry,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) public virtual override {
                    require(block.timestamp <= expiry, "ERC20Votes: signature expired");
                    address signer = ECDSA.recover(
                        _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
                        v,
                        r,
                        s
                    );
                    require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
                    _delegate(signer, delegatee);
                }
                /**
                 * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
                 */
                function _maxSupply() internal view virtual returns (uint224) {
                    return type(uint224).max;
                }
                /**
                 * @dev Snapshots the totalSupply after it has been increased.
                 */
                function _mint(address account, uint256 amount) internal virtual override {
                    super._mint(account, amount);
                    require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
                    _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
                }
                /**
                 * @dev Snapshots the totalSupply after it has been decreased.
                 */
                function _burn(address account, uint256 amount) internal virtual override {
                    super._burn(account, amount);
                    _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
                }
                /**
                 * @dev Move voting power when tokens are transferred.
                 *
                 * Emits a {DelegateVotesChanged} event.
                 */
                function _afterTokenTransfer(
                    address from,
                    address to,
                    uint256 amount
                ) internal virtual override {
                    super._afterTokenTransfer(from, to, amount);
                    _moveVotingPower(delegates(from), delegates(to), amount);
                }
                /**
                 * @dev Change delegation for `delegator` to `delegatee`.
                 *
                 * Emits events {DelegateChanged} and {DelegateVotesChanged}.
                 */
                function _delegate(address delegator, address delegatee) internal virtual {
                    address currentDelegate = delegates(delegator);
                    uint256 delegatorBalance = balanceOf(delegator);
                    _delegates[delegator] = delegatee;
                    emit DelegateChanged(delegator, currentDelegate, delegatee);
                    _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
                }
                function _moveVotingPower(
                    address src,
                    address dst,
                    uint256 amount
                ) private {
                    if (src != dst && amount > 0) {
                        if (src != address(0)) {
                            (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
                            emit DelegateVotesChanged(src, oldWeight, newWeight);
                        }
                        if (dst != address(0)) {
                            (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
                            emit DelegateVotesChanged(dst, oldWeight, newWeight);
                        }
                    }
                }
                function _writeCheckpoint(
                    Checkpoint[] storage ckpts,
                    function(uint256, uint256) view returns (uint256) op,
                    uint256 delta
                ) private returns (uint256 oldWeight, uint256 newWeight) {
                    uint256 pos = ckpts.length;
                    oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
                    newWeight = op(oldWeight, delta);
                    if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
                        ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
                    } else {
                        ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
                    }
                }
                function _add(uint256 a, uint256 b) private pure returns (uint256) {
                    return a + b;
                }
                function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
                    return a - b;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
             * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
             */
            library BitMaps {
                struct BitMap {
                    mapping(uint256 => uint256) _data;
                }
                /**
                 * @dev Returns whether the bit at `index` is set.
                 */
                function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
                    uint256 bucket = index >> 8;
                    uint256 mask = 1 << (index & 0xff);
                    return bitmap._data[bucket] & mask != 0;
                }
                /**
                 * @dev Sets the bit at `index` to the boolean `value`.
                 */
                function setTo(
                    BitMap storage bitmap,
                    uint256 index,
                    bool value
                ) internal {
                    if (value) {
                        set(bitmap, index);
                    } else {
                        unset(bitmap, index);
                    }
                }
                /**
                 * @dev Sets the bit at `index`.
                 */
                function set(BitMap storage bitmap, uint256 index) internal {
                    uint256 bucket = index >> 8;
                    uint256 mask = 1 << (index & 0xff);
                    bitmap._data[bucket] |= mask;
                }
                /**
                 * @dev Unsets the bit at `index`.
                 */
                function unset(BitMap storage bitmap, uint256 index) internal {
                    uint256 bucket = index >> 8;
                    uint256 mask = 1 << (index & 0xff);
                    bitmap._data[bucket] &= ~mask;
                }
            }
            // 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.5.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20 {
                /**
                 * @dev Returns the amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` tokens from the caller's account to `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);
                /**
                 * @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);
            }
            // 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 (token/ERC20/extensions/draft-IERC20Permit.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
             * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
             *
             * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
             * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
             * need to send a transaction, and thus is not required to hold Ether at all.
             */
            interface IERC20Permit {
                /**
                 * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                 * given ``owner``'s signed approval.
                 *
                 * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                 * ordering also apply here.
                 *
                 * Emits an {Approval} event.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 * - `deadline` must be a timestamp in the future.
                 * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                 * over the EIP712-formatted function arguments.
                 * - the signature must use ``owner``'s current nonce (see {nonces}).
                 *
                 * For more information on the signature format, see the
                 * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                 * section].
                 */
                function permit(
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) external;
                /**
                 * @dev Returns the current nonce for `owner`. This value must be
                 * included whenever a signature is generated for {permit}.
                 *
                 * Every successful call to {permit} increases ``owner``'s nonce by one. This
                 * prevents a signature from being used multiple times.
                 */
                function nonces(address owner) external view returns (uint256);
                /**
                 * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                 */
                // solhint-disable-next-line func-name-mixedcase
                function DOMAIN_SEPARATOR() external view returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
            pragma solidity ^0.8.0;
            import "./ECDSA.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].
             *
             * _Available since v3.4._
             */
            abstract contract EIP712 {
                /* solhint-disable var-name-mixedcase */
                // 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 _CACHED_DOMAIN_SEPARATOR;
                uint256 private immutable _CACHED_CHAIN_ID;
                address private immutable _CACHED_THIS;
                bytes32 private immutable _HASHED_NAME;
                bytes32 private immutable _HASHED_VERSION;
                bytes32 private immutable _TYPE_HASH;
                /* solhint-enable var-name-mixedcase */
                /**
                 * @dev Initializes the domain separator and parameter caches.
                 *
                 * The meaning of `name` and `version` is specified in
                 * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                 *
                 * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                 * - `version`: the current major version of the signing domain.
                 *
                 * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                 * contract upgrade].
                 */
                constructor(string memory name, string memory version) {
                    bytes32 hashedName = keccak256(bytes(name));
                    bytes32 hashedVersion = keccak256(bytes(version));
                    bytes32 typeHash = keccak256(
                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                    );
                    _HASHED_NAME = hashedName;
                    _HASHED_VERSION = hashedVersion;
                    _CACHED_CHAIN_ID = block.chainid;
                    _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
                    _CACHED_THIS = address(this);
                    _TYPE_HASH = typeHash;
                }
                /**
                 * @dev Returns the domain separator for the current chain.
                 */
                function _domainSeparatorV4() internal view returns (bytes32) {
                    if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
                        return _CACHED_DOMAIN_SEPARATOR;
                    } else {
                        return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
                    }
                }
                function _buildDomainSeparator(
                    bytes32 typeHash,
                    bytes32 nameHash,
                    bytes32 versionHash
                ) private view returns (bytes32) {
                    return keccak256(abi.encode(typeHash, nameHash, versionHash, 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);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.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
                }
                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");
                    } else if (error == RecoverError.InvalidSignatureV) {
                        revert("ECDSA: invalid signature 'v' 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) {
                    // Check the signature length
                    // - case 65: r,s,v signature (standard)
                    // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
                    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.
                        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 if (signature.length == 64) {
                        bytes32 r;
                        bytes32 vs;
                        // ecrecover takes the signature parameters, and the only way to get them
                        // currently is to use assembly.
                        assembly {
                            r := mload(add(signature, 0x20))
                            vs := mload(add(signature, 0x40))
                        }
                        return tryRecover(hash, r, vs);
                    } 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 (v != 27 && v != 28) {
                        return (address(0), RecoverError.InvalidSignatureV);
                    }
                    // 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) {
                    // 32 is the length in bytes of hash,
                    // enforced by the type signature above
                    return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
            32", hash));
                }
                /**
                 * @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) {
                    return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
                }
            }
            // 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 (utils/Strings.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev String operations.
             */
            library Strings {
                bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
                /**
                 * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                 */
                function toString(uint256 value) internal pure returns (string memory) {
                    // Inspired by OraclizeAPI's implementation - MIT licence
                    // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                    if (value == 0) {
                        return "0";
                    }
                    uint256 temp = value;
                    uint256 digits;
                    while (temp != 0) {
                        digits++;
                        temp /= 10;
                    }
                    bytes memory buffer = new bytes(digits);
                    while (value != 0) {
                        digits -= 1;
                        buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                        value /= 10;
                    }
                    return string(buffer);
                }
                /**
                 * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                 */
                function toHexString(uint256 value) internal pure returns (string memory) {
                    if (value == 0) {
                        return "0x00";
                    }
                    uint256 temp = value;
                    uint256 length = 0;
                    while (temp != 0) {
                        length++;
                        temp >>= 8;
                    }
                    return toHexString(value, length);
                }
                /**
                 * @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] = _HEX_SYMBOLS[value & 0xf];
                        value >>= 4;
                    }
                    require(value == 0, "Strings: hex length insufficient");
                    return string(buffer);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Standard math utilities missing in the Solidity language.
             */
            library Math {
                /**
                 * @dev Returns the largest of two numbers.
                 */
                function max(uint256 a, uint256 b) internal pure returns (uint256) {
                    return a >= b ? a : b;
                }
                /**
                 * @dev Returns the smallest of two numbers.
                 */
                function min(uint256 a, uint256 b) internal pure returns (uint256) {
                    return a < b ? a : b;
                }
                /**
                 * @dev Returns the average of two numbers. The result is rounded towards
                 * zero.
                 */
                function average(uint256 a, uint256 b) internal pure returns (uint256) {
                    // (a + b) / 2 can overflow.
                    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 / b + (a % b == 0 ? 0 : 1);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
             *
             * _Available since v4.5._
             */
            interface IVotes {
                /**
                 * @dev Emitted when an account changes their delegate.
                 */
                event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
                /**
                 * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
                 */
                event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
                /**
                 * @dev Returns the current amount of votes that `account` has.
                 */
                function getVotes(address account) external view returns (uint256);
                /**
                 * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
                 */
                function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
                /**
                 * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
                 *
                 * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
                 * Votes that have not been delegated are still part of total supply, even though they would not participate in a
                 * vote.
                 */
                function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
                /**
                 * @dev Returns the delegate that `account` has chosen.
                 */
                function delegates(address account) external view returns (address);
                /**
                 * @dev Delegates votes from the sender to `delegatee`.
                 */
                function delegate(address delegatee) external;
                /**
                 * @dev Delegates votes from signer to `delegatee`.
                 */
                function delegateBySig(
                    address delegatee,
                    uint256 nonce,
                    uint256 expiry,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) external;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
             * checks.
             *
             * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
             * easily result in undesired exploitation or bugs, since developers usually
             * assume that overflows raise errors. `SafeCast` restores this intuition by
             * reverting the transaction when such an operation overflows.
             *
             * Using this library instead of the unchecked operations eliminates an entire
             * class of bugs, so it's recommended to use it always.
             *
             * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
             * all math on `uint256` and `int256` and then downcasting.
             */
            library SafeCast {
                /**
                 * @dev Returns the downcasted uint224 from uint256, reverting on
                 * overflow (when the input is greater than largest uint224).
                 *
                 * Counterpart to Solidity's `uint224` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 224 bits
                 */
                function toUint224(uint256 value) internal pure returns (uint224) {
                    require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                    return uint224(value);
                }
                /**
                 * @dev Returns the downcasted uint128 from uint256, reverting on
                 * overflow (when the input is greater than largest uint128).
                 *
                 * Counterpart to Solidity's `uint128` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 128 bits
                 */
                function toUint128(uint256 value) internal pure returns (uint128) {
                    require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                    return uint128(value);
                }
                /**
                 * @dev Returns the downcasted uint96 from uint256, reverting on
                 * overflow (when the input is greater than largest uint96).
                 *
                 * Counterpart to Solidity's `uint96` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 96 bits
                 */
                function toUint96(uint256 value) internal pure returns (uint96) {
                    require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                    return uint96(value);
                }
                /**
                 * @dev Returns the downcasted uint64 from uint256, reverting on
                 * overflow (when the input is greater than largest uint64).
                 *
                 * Counterpart to Solidity's `uint64` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 64 bits
                 */
                function toUint64(uint256 value) internal pure returns (uint64) {
                    require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                    return uint64(value);
                }
                /**
                 * @dev Returns the downcasted uint32 from uint256, reverting on
                 * overflow (when the input is greater than largest uint32).
                 *
                 * Counterpart to Solidity's `uint32` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 32 bits
                 */
                function toUint32(uint256 value) internal pure returns (uint32) {
                    require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                    return uint32(value);
                }
                /**
                 * @dev Returns the downcasted uint16 from uint256, reverting on
                 * overflow (when the input is greater than largest uint16).
                 *
                 * Counterpart to Solidity's `uint16` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 16 bits
                 */
                function toUint16(uint256 value) internal pure returns (uint16) {
                    require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                    return uint16(value);
                }
                /**
                 * @dev Returns the downcasted uint8 from uint256, reverting on
                 * overflow (when the input is greater than largest uint8).
                 *
                 * Counterpart to Solidity's `uint8` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 8 bits.
                 */
                function toUint8(uint256 value) internal pure returns (uint8) {
                    require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                    return uint8(value);
                }
                /**
                 * @dev Converts a signed int256 into an unsigned uint256.
                 *
                 * Requirements:
                 *
                 * - input must be greater than or equal to 0.
                 */
                function toUint256(int256 value) internal pure returns (uint256) {
                    require(value >= 0, "SafeCast: value must be positive");
                    return uint256(value);
                }
                /**
                 * @dev Returns the downcasted int128 from int256, reverting on
                 * overflow (when the input is less than smallest int128 or
                 * greater than largest int128).
                 *
                 * Counterpart to Solidity's `int128` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 128 bits
                 *
                 * _Available since v3.1._
                 */
                function toInt128(int256 value) internal pure returns (int128) {
                    require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
                    return int128(value);
                }
                /**
                 * @dev Returns the downcasted int64 from int256, reverting on
                 * overflow (when the input is less than smallest int64 or
                 * greater than largest int64).
                 *
                 * Counterpart to Solidity's `int64` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 64 bits
                 *
                 * _Available since v3.1._
                 */
                function toInt64(int256 value) internal pure returns (int64) {
                    require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
                    return int64(value);
                }
                /**
                 * @dev Returns the downcasted int32 from int256, reverting on
                 * overflow (when the input is less than smallest int32 or
                 * greater than largest int32).
                 *
                 * Counterpart to Solidity's `int32` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 32 bits
                 *
                 * _Available since v3.1._
                 */
                function toInt32(int256 value) internal pure returns (int32) {
                    require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
                    return int32(value);
                }
                /**
                 * @dev Returns the downcasted int16 from int256, reverting on
                 * overflow (when the input is less than smallest int16 or
                 * greater than largest int16).
                 *
                 * Counterpart to Solidity's `int16` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 16 bits
                 *
                 * _Available since v3.1._
                 */
                function toInt16(int256 value) internal pure returns (int16) {
                    require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
                    return int16(value);
                }
                /**
                 * @dev Returns the downcasted int8 from int256, reverting on
                 * overflow (when the input is less than smallest int8 or
                 * greater than largest int8).
                 *
                 * Counterpart to Solidity's `int8` operator.
                 *
                 * Requirements:
                 *
                 * - input must fit into 8 bits.
                 *
                 * _Available since v3.1._
                 */
                function toInt8(int256 value) internal pure returns (int8) {
                    require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
                    return int8(value);
                }
                /**
                 * @dev Converts an unsigned uint256 into a signed int256.
                 *
                 * Requirements:
                 *
                 * - input must be less than or equal to maxInt256.
                 */
                function toInt256(uint256 value) internal pure returns (int256) {
                    // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                    require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                    return int256(value);
                }
            }
            

            File 5 of 7: Imx
            // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
            // Copyright 2020 Compound Labs, Inc.
            // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
            // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
            // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
            // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
            // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
            pragma solidity =0.6.6;
            pragma experimental ABIEncoderV2;
            contract Imx {
                /// @notice EIP-20 token name for this token
                string public constant name = "Impermax";
                /// @notice EIP-20 token symbol for this token
                string public constant symbol = "IMX";
                /// @notice EIP-20 token decimals for this token
                uint8 public constant decimals = 18;
                /// @notice Total number of tokens in circulation
                uint public constant totalSupply = 100_000_000e18; // 100 million Imx
                /// @notice Allowance amounts on behalf of others
                mapping (address => mapping (address => uint96)) internal allowances;
                /// @notice Official record of token balances for each account
                mapping (address => uint96) internal balances;
                /// @notice A record of each accounts delegate
                mapping (address => address) public delegates;
                /// @notice A checkpoint for marking number of votes from a given block
                struct Checkpoint {
                    uint32 fromBlock;
                    uint96 votes;
                }
                /// @notice A record of votes checkpoints for each account, by index
                mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
                /// @notice The number of checkpoints for each account
                mapping (address => uint32) public numCheckpoints;
                /// @notice The EIP-712 typehash for the contract's domain
                bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
                /// @notice The EIP-712 typehash for the delegation struct used by the contract
                bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
                /// @notice A record of states for signing / validating signatures
                mapping (address => uint) public nonces;
                /// @notice An event thats emitted when an account changes its delegate
                event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
                /// @notice An event thats emitted when a delegate account's vote balance changes
                event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
                /// @notice The standard EIP-20 transfer event
                event Transfer(address indexed from, address indexed to, uint256 amount);
                /// @notice The standard EIP-20 approval event
                event Approval(address indexed owner, address indexed spender, uint256 amount);
                /**
                 * @notice Construct a new Imx token
                 * @param account The initial account to grant all the tokens
                 */
                constructor(address account) public {
                    balances[account] = uint96(totalSupply);
                    emit Transfer(address(0), account, totalSupply);
                }
                /**
                 * @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
                 * @param account The address of the account holding the funds
                 * @param spender The address of the account spending the funds
                 * @return The number of tokens approved
                 */
                function allowance(address account, address spender) external view returns (uint) {
                    return allowances[account][spender];
                }
                /**
                 * @notice Approve `spender` to transfer up to `amount` from `src`
                 * @dev This will overwrite the approval amount for `spender`
                 *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
                 * @param spender The address of the account which may transfer tokens
                 * @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
                 * @return Whether or not the approval succeeded
                 */
                function approve(address spender, uint rawAmount) external returns (bool) {
                    uint96 amount;
                    if (rawAmount == uint(-1)) {
                        amount = uint96(-1);
                    } else {
                        amount = safe96(rawAmount, "Imx::approve: amount exceeds 96 bits");
                    }
                    allowances[msg.sender][spender] = amount;
                    emit Approval(msg.sender, spender, amount);
                    return true;
                }
            \t
                /**
                 * @notice Get the number of tokens held by the `account`
                 * @param account The address of the account to get the balance of
                 * @return The number of tokens held
                 */
                function balanceOf(address account) external view returns (uint) {
                    return balances[account];
                }
                /**
                 * @notice Transfer `amount` tokens from `msg.sender` to `dst`
                 * @param dst The address of the destination account
                 * @param rawAmount The number of tokens to transfer
                 * @return Whether or not the transfer succeeded
                 */
                function transfer(address dst, uint rawAmount) external returns (bool) {
                    uint96 amount = safe96(rawAmount, "Imx::transfer: amount exceeds 96 bits");
                    _transferTokens(msg.sender, dst, amount);
                    return true;
                }
                /**
                 * @notice Transfer `amount` tokens from `src` to `dst`
                 * @param src The address of the source account
                 * @param dst The address of the destination account
                 * @param rawAmount The number of tokens to transfer
                 * @return Whether or not the transfer succeeded
                 */
                function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
                    address spender = msg.sender;
                    uint96 spenderAllowance = allowances[src][spender];
                    uint96 amount = safe96(rawAmount, "Imx::approve: amount exceeds 96 bits");
                    if (spender != src && spenderAllowance != uint96(-1)) {
                        uint96 newAllowance = sub96(spenderAllowance, amount, "Imx::transferFrom: transfer amount exceeds spender allowance");
                        allowances[src][spender] = newAllowance;
                        emit Approval(src, spender, newAllowance);
                    }
                    _transferTokens(src, dst, amount);
                    return true;
                }
                /**
                 * @notice Delegate votes from `msg.sender` to `delegatee`
                 * @param delegatee The address to delegate votes to
                 */
                function delegate(address delegatee) public {
                    return _delegate(msg.sender, delegatee);
                }
                /**
                 * @notice Delegates votes from signatory to `delegatee`
                 * @param delegatee The address to delegate votes to
                 * @param nonce The contract state required to match the signature
                 * @param expiry The time at which to expire the signature
                 * @param v The recovery byte of the signature
                 * @param r Half of the ECDSA signature pair
                 * @param s Half of the ECDSA signature pair
                 */
                function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
                    bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
                    bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
                    bytes32 digest = keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
                    address signatory = ecrecover(digest, v, r, s);
                    require(signatory != address(0), "Imx::delegateBySig: invalid signature");
                    require(nonce == nonces[signatory]++, "Imx::delegateBySig: invalid nonce");
                    require(now <= expiry, "Imx::delegateBySig: signature expired");
                    return _delegate(signatory, delegatee);
                }
                /**
                 * @notice Gets the current votes balance for `account`
                 * @param account The address to get votes balance
                 * @return The number of current votes for `account`
                 */
                function getCurrentVotes(address account) external view returns (uint96) {
                    uint32 nCheckpoints = numCheckpoints[account];
                    return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
                }
                /**
                 * @notice Determine the prior number of votes for an account as of a block number
                 * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
                 * @param account The address of the account to check
                 * @param blockNumber The block number to get the vote balance at
                 * @return The number of votes the account had as of the given block
                 */
                function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
                    require(blockNumber < block.number, "Imx::getPriorVotes: not yet determined");
                    uint32 nCheckpoints = numCheckpoints[account];
                    if (nCheckpoints == 0) {
                        return 0;
                    }
                    // First check most recent balance
                    if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
                        return checkpoints[account][nCheckpoints - 1].votes;
                    }
                    // Next check implicit zero balance
                    if (checkpoints[account][0].fromBlock > blockNumber) {
                        return 0;
                    }
                    uint32 lower = 0;
                    uint32 upper = nCheckpoints - 1;
                    while (upper > lower) {
                        uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
                        Checkpoint memory cp = checkpoints[account][center];
                        if (cp.fromBlock == blockNumber) {
                            return cp.votes;
                        } else if (cp.fromBlock < blockNumber) {
                            lower = center;
                        } else {
                            upper = center - 1;
                        }
                    }
                    return checkpoints[account][lower].votes;
                }
                function _delegate(address delegator, address delegatee) internal {
                    address currentDelegate = delegates[delegator];
                    uint96 delegatorBalance = balances[delegator];
                    delegates[delegator] = delegatee;
                    emit DelegateChanged(delegator, currentDelegate, delegatee);
                    _moveDelegates(currentDelegate, delegatee, delegatorBalance);
                }
                function _transferTokens(address src, address dst, uint96 amount) internal {
                    require(src != address(0), "Imx::_transferTokens: cannot transfer from the zero address");
                    require(dst != address(0), "Imx::_transferTokens: cannot transfer to the zero address");
                    balances[src] = sub96(balances[src], amount, "Imx::_transferTokens: transfer amount exceeds balance");
                    balances[dst] = add96(balances[dst], amount, "Imx::_transferTokens: transfer amount overflows");
                    emit Transfer(src, dst, amount);
                    _moveDelegates(delegates[src], delegates[dst], amount);
                }
                function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
                    if (srcRep != dstRep && amount > 0) {
                        if (srcRep != address(0)) {
                            uint32 srcRepNum = numCheckpoints[srcRep];
                            uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                            uint96 srcRepNew = sub96(srcRepOld, amount, "Imx::_moveVotes: vote amount underflows");
                            _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
                        }
                        if (dstRep != address(0)) {
                            uint32 dstRepNum = numCheckpoints[dstRep];
                            uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                            uint96 dstRepNew = add96(dstRepOld, amount, "Imx::_moveVotes: vote amount overflows");
                            _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
                        }
                    }
                }
                function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
                  uint32 blockNumber = safe32(block.number, "Imx::_writeCheckpoint: block number exceeds 32 bits");
                  if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
                      checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
                  } else {
                      checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
                      numCheckpoints[delegatee] = nCheckpoints + 1;
                  }
                  emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
                }
                function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
                    require(n < 2**32, errorMessage);
                    return uint32(n);
                }
                function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
                    require(n < 2**96, errorMessage);
                    return uint96(n);
                }
                function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
                    uint96 c = a + b;
                    require(c >= a, errorMessage);
                    return c;
                }
                function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
                    require(b <= a, errorMessage);
                    return a - b;
                }
                function getChainId() internal pure returns (uint) {
                    uint256 chainId;
                    assembly { chainId := chainid() }
                    return chainId;
                }
            }

            File 6 of 7: AaveTokenV3
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {BaseAaveTokenV2} from './BaseAaveTokenV2.sol';
            import {BaseDelegation} from './BaseDelegation.sol';
            contract AaveTokenV3 is BaseAaveTokenV2, BaseDelegation {
              /**
               * @dev initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy
               */
              function initialize() external virtual initializer {}
              function _afterTokenTransfer(
                address from,
                address to,
                uint256 fromBalanceBefore,
                uint256 toBalanceBefore,
                uint256 amount
              ) internal override {
                _delegationChangeOnTransfer(from, to, fromBalanceBefore, toBalanceBefore, amount);
              }
              function _getDelegationState(address user)
                internal
                view
                override
                returns (DelegationState memory)
              {
                DelegationAwareBalance memory userState = _balances[user];
                return
                  DelegationState({
                    delegatedPropositionBalance: userState.delegatedPropositionBalance,
                    delegatedVotingBalance: userState.delegatedVotingBalance,
                    delegationMode: userState.delegationMode
                  });
              }
              function _getBalance(address user) internal view override returns (uint256) {
                return _balances[user].balance;
              }
              function _setDelegationState(address user, DelegationState memory delegationState)
                internal
                override
              {
                DelegationAwareBalance storage userState = _balances[user];
                userState.delegatedPropositionBalance = delegationState.delegatedPropositionBalance;
                userState.delegatedVotingBalance = delegationState.delegatedVotingBalance;
                userState.delegationMode = delegationState.delegationMode;
              }
              function _incrementNonces(address user) internal override returns (uint256) {
                unchecked {
                  // Does not make sense to check because it's not realistic to reach uint256.max in nonce
                  return _nonces[user]++;
                }
              }
              function _getDomainSeparator() internal view override returns (bytes32) {
                return DOMAIN_SEPARATOR();
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
            import {VersionedInitializable} from './utils/VersionedInitializable.sol';
            import {EIP712} from './utils/EIP712.sol';
            import {BaseAaveToken} from './BaseAaveToken.sol';
            abstract contract BaseAaveTokenV2 is BaseAaveToken, VersionedInitializable, EIP712 {
              /// @dev owner => next valid nonce to submit with permit()
              mapping(address => uint256) public _nonces;
              ///////// @dev DEPRECATED from AaveToken v1  //////////////////////////
              //////// kept for backwards compatibility with old storage layout ////
              uint256[3] private ______DEPRECATED_FROM_AAVE_V1;
              ///////// @dev END OF DEPRECATED from AaveToken v1  //////////////////////////
              // deprecated in favor to OZ EIP712
              bytes32 private __DEPRECATED_DOMAIN_SEPARATOR;
              ///////// @dev DEPRECATED from AaveToken v2  //////////////////////////
              //////// kept for backwards compatibility with old storage layout ////
              uint256[4] private ______DEPRECATED_FROM_AAVE_V2;
              ///////// @dev END OF DEPRECATED from AaveToken v2  //////////////////////////
              bytes32 public constant PERMIT_TYPEHASH =
                keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
              uint256 public constant REVISION = 4;
              constructor() EIP712('Aave token V3', '2') {}
              function DOMAIN_SEPARATOR() public view returns (bytes32) {
                return _domainSeparatorV4();
              }
              /**
               * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
               * @param owner the owner of the funds
               * @param spender the spender
               * @param value the amount
               * @param deadline the deadline timestamp, type(uint256).max for no deadline
               * @param v signature param
               * @param s signature param
               * @param r signature param
               */
              function permit(
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
              ) external {
                require(owner != address(0), 'INVALID_OWNER');
                //solium-disable-next-line
                require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
                uint256 currentValidNonce = _nonces[owner];
                bytes32 digest = _hashTypedDataV4(
                  keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
                );
                require(owner == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
                unchecked {
                  // does not make sense to check because it's not realistic to reach uint256.max in nonce
                  _nonces[owner] = currentValidNonce + 1;
                }
                _approve(owner, spender, value);
              }
              /**
               * @dev returns the revision of the implementation contract
               */
              function getRevision() internal pure override returns (uint256) {
                return REVISION;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
            import {SafeCast72} from './utils/SafeCast72.sol';
            import {IGovernancePowerDelegationToken} from './interfaces/IGovernancePowerDelegationToken.sol';
            import {DelegationMode} from './DelegationAwareBalance.sol';
            /**
             * @notice The contract implements generic delegation functionality for the upcoming governance v3
             * @author BGD Labs
             * @dev to make it's pluggable to any exising token it has a set of virtual functions
             *   for simple access to balances and permit functionality
             * @dev ************ IMPORTANT SECURITY CONSIDERATION ************
             *   current version of the token can be used only with asset which has 18 decimals
             *   and possible totalSupply lower then 4722366482869645213696,
             *   otherwise at least POWER_SCALE_FACTOR should be adjusted !!!
             *   *************************************************************
             */
            abstract contract BaseDelegation is IGovernancePowerDelegationToken {
              struct DelegationState {
                uint72 delegatedPropositionBalance;
                uint72 delegatedVotingBalance;
                DelegationMode delegationMode;
              }
              mapping(address => address) internal _votingDelegatee;
              mapping(address => address) internal _propositionDelegatee;
              /** @dev we assume that for the governance system delegation with 18 decimals of precision is not needed,
               *   by this constant we reduce it by 10, to 8 decimals.
               *   In case of Aave token this will allow to work with up to 47'223'664'828'696,45213696 total supply
               *   If your token already have less then 10 decimals, please change it to appropriate.
               */
              uint256 public constant POWER_SCALE_FACTOR = 1e10;
              bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH =
                keccak256(
                  'DelegateByType(address delegator,address delegatee,uint8 delegationType,uint256 nonce,uint256 deadline)'
                );
              bytes32 public constant DELEGATE_TYPEHASH =
                keccak256('Delegate(address delegator,address delegatee,uint256 nonce,uint256 deadline)');
              /**
               * @notice returns eip-2612 compatible domain separator
               * @dev we expect that existing tokens, ie Aave, already have, so we want to reuse
               * @return domain separator
               */
              function _getDomainSeparator() internal view virtual returns (bytes32);
              /**
               * @notice gets the delegation state of a user
               * @param user address
               * @return state of a user's delegation
               */
              function _getDelegationState(address user) internal view virtual returns (DelegationState memory);
              /**
               * @notice returns the token balance of a user
               * @param user address
               * @return current nonce before increase
               */
              function _getBalance(address user) internal view virtual returns (uint256);
              /**
               * @notice increases and return the current nonce of a user
               * @dev should use `return nonce++;` pattern
               * @param user address
               * @return current nonce before increase
               */
              function _incrementNonces(address user) internal virtual returns (uint256);
              /**
               * @notice sets the delegation state of a user
               * @param user address
               * @param delegationState state of a user's delegation
               */
              function _setDelegationState(address user, DelegationState memory delegationState)
                internal
                virtual;
              /// @inheritdoc IGovernancePowerDelegationToken
              function delegateByType(address delegatee, GovernancePowerType delegationType)
                external
                virtual
                override
              {
                _delegateByType(msg.sender, delegatee, delegationType);
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function delegate(address delegatee) external override {
                _delegateByType(msg.sender, delegatee, GovernancePowerType.VOTING);
                _delegateByType(msg.sender, delegatee, GovernancePowerType.PROPOSITION);
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function getDelegateeByType(address delegator, GovernancePowerType delegationType)
                external
                view
                override
                returns (address)
              {
                return _getDelegateeByType(delegator, _getDelegationState(delegator), delegationType);
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function getDelegates(address delegator) external view override returns (address, address) {
                DelegationState memory delegatorBalance = _getDelegationState(delegator);
                return (
                  _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.VOTING),
                  _getDelegateeByType(delegator, delegatorBalance, GovernancePowerType.PROPOSITION)
                );
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function getPowerCurrent(address user, GovernancePowerType delegationType)
                public
                view
                virtual
                override
                returns (uint256)
              {
                DelegationState memory userState = _getDelegationState(user);
                uint256 userOwnPower = uint8(userState.delegationMode) & (uint8(delegationType) + 1) == 0
                  ? _getBalance(user)
                  : 0;
                uint256 userDelegatedPower = _getDelegatedPowerByType(userState, delegationType);
                return userOwnPower + userDelegatedPower;
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function getPowersCurrent(address user) external view override returns (uint256, uint256) {
                return (
                  getPowerCurrent(user, GovernancePowerType.VOTING),
                  getPowerCurrent(user, GovernancePowerType.PROPOSITION)
                );
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function metaDelegateByType(
                address delegator,
                address delegatee,
                GovernancePowerType delegationType,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
              ) external override {
                require(delegator != address(0), 'INVALID_OWNER');
                //solium-disable-next-line
                require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
                bytes32 digest = ECDSA.toTypedDataHash(
                  _getDomainSeparator(),
                  keccak256(
                    abi.encode(
                      DELEGATE_BY_TYPE_TYPEHASH,
                      delegator,
                      delegatee,
                      delegationType,
                      _incrementNonces(delegator),
                      deadline
                    )
                  )
                );
                require(delegator == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
                _delegateByType(delegator, delegatee, delegationType);
              }
              /// @inheritdoc IGovernancePowerDelegationToken
              function metaDelegate(
                address delegator,
                address delegatee,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
              ) external override {
                require(delegator != address(0), 'INVALID_OWNER');
                //solium-disable-next-line
                require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
                bytes32 digest = ECDSA.toTypedDataHash(
                  _getDomainSeparator(),
                  keccak256(
                    abi.encode(DELEGATE_TYPEHASH, delegator, delegatee, _incrementNonces(delegator), deadline)
                  )
                );
                require(delegator == ECDSA.recover(digest, v, r, s), 'INVALID_SIGNATURE');
                _delegateByType(delegator, delegatee, GovernancePowerType.VOTING);
                _delegateByType(delegator, delegatee, GovernancePowerType.PROPOSITION);
              }
              /**
               * @dev Modifies the delegated power of a `delegatee` account by type (VOTING, PROPOSITION).
               * Passing the impact on the delegation of `delegatee` account before and after to reduce conditionals and not lose
               * any precision.
               * @param impactOnDelegationBefore how much impact a balance of another account had over the delegation of a `delegatee`
               * before an action.
               * For example, if the action is a delegation from one account to another, the impact before the action will be 0.
               * @param impactOnDelegationAfter how much impact a balance of another account will have  over the delegation of a `delegatee`
               * after an action.
               * For example, if the action is a delegation from one account to another, the impact after the action will be the whole balance
               * of the account changing the delegatee.
               * @param delegatee the user whom delegated governance power will be changed
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               **/
              function _governancePowerTransferByType(
                uint256 impactOnDelegationBefore,
                uint256 impactOnDelegationAfter,
                address delegatee,
                GovernancePowerType delegationType
              ) internal {
                if (delegatee == address(0)) return;
                if (impactOnDelegationBefore == impactOnDelegationAfter) return;
                // we use uint72, because this is the most optimal for AaveTokenV3
                // To make delegated balance fit into uint72 we're decreasing precision of delegated balance by POWER_SCALE_FACTOR
                uint72 impactOnDelegationBefore72 = SafeCast72.toUint72(
                  impactOnDelegationBefore / POWER_SCALE_FACTOR
                );
                uint72 impactOnDelegationAfter72 = SafeCast72.toUint72(
                  impactOnDelegationAfter / POWER_SCALE_FACTOR
                );
                DelegationState memory delegateeState = _getDelegationState(delegatee);
                if (delegationType == GovernancePowerType.VOTING) {
                  delegateeState.delegatedVotingBalance =
                    delegateeState.delegatedVotingBalance -
                    impactOnDelegationBefore72 +
                    impactOnDelegationAfter72;
                } else {
                  delegateeState.delegatedPropositionBalance =
                    delegateeState.delegatedPropositionBalance -
                    impactOnDelegationBefore72 +
                    impactOnDelegationAfter72;
                }
                _setDelegationState(delegatee, delegateeState);
              }
              /**
               * @dev performs all state changes related delegation changes on transfer
               * @param from token sender
               * @param to token recipient
               * @param fromBalanceBefore balance of the sender before transfer
               * @param toBalanceBefore balance of the recipient before transfer
               * @param amount amount of tokens sent
               **/
              function _delegationChangeOnTransfer(
                address from,
                address to,
                uint256 fromBalanceBefore,
                uint256 toBalanceBefore,
                uint256 amount
              ) internal {
                if (from == to) {
                  return;
                }
                if (from != address(0)) {
                  DelegationState memory fromUserState = _getDelegationState(from);
                  uint256 fromBalanceAfter = fromBalanceBefore - amount;
                  if (fromUserState.delegationMode != DelegationMode.NO_DELEGATION) {
                    _governancePowerTransferByType(
                      fromBalanceBefore,
                      fromBalanceAfter,
                      _getDelegateeByType(from, fromUserState, GovernancePowerType.VOTING),
                      GovernancePowerType.VOTING
                    );
                    _governancePowerTransferByType(
                      fromBalanceBefore,
                      fromBalanceAfter,
                      _getDelegateeByType(from, fromUserState, GovernancePowerType.PROPOSITION),
                      GovernancePowerType.PROPOSITION
                    );
                  }
                }
                if (to != address(0)) {
                  DelegationState memory toUserState = _getDelegationState(to);
                  uint256 toBalanceAfter = toBalanceBefore + amount;
                  if (toUserState.delegationMode != DelegationMode.NO_DELEGATION) {
                    _governancePowerTransferByType(
                      toBalanceBefore,
                      toBalanceAfter,
                      _getDelegateeByType(to, toUserState, GovernancePowerType.VOTING),
                      GovernancePowerType.VOTING
                    );
                    _governancePowerTransferByType(
                      toBalanceBefore,
                      toBalanceAfter,
                      _getDelegateeByType(to, toUserState, GovernancePowerType.PROPOSITION),
                      GovernancePowerType.PROPOSITION
                    );
                  }
                }
              }
              /**
               * @dev Extracts from state and returns delegated governance power (Voting, Proposition)
               * @param userState the current state of a user
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               **/
              function _getDelegatedPowerByType(
                DelegationState memory userState,
                GovernancePowerType delegationType
              ) internal pure returns (uint256) {
                return
                  POWER_SCALE_FACTOR *
                  (
                    delegationType == GovernancePowerType.VOTING
                      ? userState.delegatedVotingBalance
                      : userState.delegatedPropositionBalance
                  );
              }
              /**
               * @dev Extracts from state and returns the delegatee of a delegator by type of governance power (Voting, Proposition)
               * - If the delegator doesn't have any delegatee, returns address(0)
               * @param delegator delegator
               * @param userState the current state of a user
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               **/
              function _getDelegateeByType(
                address delegator,
                DelegationState memory userState,
                GovernancePowerType delegationType
              ) internal view returns (address) {
                if (delegationType == GovernancePowerType.VOTING) {
                  return
                    /// With the & operation, we cover both VOTING_DELEGATED delegation and FULL_POWER_DELEGATED
                    /// as VOTING_DELEGATED is equivalent to 01 in binary and FULL_POWER_DELEGATED is equivalent to 11
                    (uint8(userState.delegationMode) & uint8(DelegationMode.VOTING_DELEGATED)) != 0
                      ? _votingDelegatee[delegator]
                      : address(0);
                }
                return
                  userState.delegationMode >= DelegationMode.PROPOSITION_DELEGATED
                    ? _propositionDelegatee[delegator]
                    : address(0);
              }
              /**
               * @dev Changes user's delegatee address by type of governance power (Voting, Proposition)
               * @param delegator delegator
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               * @param _newDelegatee the new delegatee
               **/
              function _updateDelegateeByType(
                address delegator,
                GovernancePowerType delegationType,
                address _newDelegatee
              ) internal {
                address newDelegatee = _newDelegatee == delegator ? address(0) : _newDelegatee;
                if (delegationType == GovernancePowerType.VOTING) {
                  _votingDelegatee[delegator] = newDelegatee;
                } else {
                  _propositionDelegatee[delegator] = newDelegatee;
                }
              }
              /**
               * @dev Updates the specific flag which signaling about existence of delegation of governance power (Voting, Proposition)
               * @param userState a user state to change
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               * @param willDelegate next state of delegation
               **/
              function _updateDelegationModeByType(
                DelegationState memory userState,
                GovernancePowerType delegationType,
                bool willDelegate
              ) internal pure returns (DelegationState memory) {
                if (willDelegate) {
                  // Because GovernancePowerType starts from 0, we should add 1 first, then we apply bitwise OR
                  userState.delegationMode = DelegationMode(
                    uint8(userState.delegationMode) | (uint8(delegationType) + 1)
                  );
                } else {
                  // First bitwise NEGATION, ie was 01, after XOR with 11 will be 10,
                  // then bitwise AND, which means it will keep only another delegation type if it exists
                  userState.delegationMode = DelegationMode(
                    uint8(userState.delegationMode) &
                      ((uint8(delegationType) + 1) ^ uint8(DelegationMode.FULL_POWER_DELEGATED))
                  );
                }
                return userState;
              }
              /**
               * @dev This is the equivalent of an ERC20 transfer(), but for a power type: an atomic transfer of a balance (power).
               * When needed, it decreases the power of the `delegator` and when needed, it increases the power of the `delegatee`
               * @param delegator delegator
               * @param _delegatee the user which delegated power will change
               * @param delegationType the type of delegation (VOTING, PROPOSITION)
               **/
              function _delegateByType(
                address delegator,
                address _delegatee,
                GovernancePowerType delegationType
              ) internal {
                // Here we unify the property that delegating power to address(0) == delegating power to yourself == no delegation
                // So from now on, not being delegating is (exclusively) that delegatee == address(0)
                address delegatee = _delegatee == delegator ? address(0) : _delegatee;
                // We read the whole struct before validating delegatee, because in the optimistic case
                // (_delegatee != currentDelegatee) we will reuse userState in the rest of the function
                DelegationState memory delegatorState = _getDelegationState(delegator);
                address currentDelegatee = _getDelegateeByType(delegator, delegatorState, delegationType);
                if (delegatee == currentDelegatee) return;
                bool delegatingNow = currentDelegatee != address(0);
                bool willDelegateAfter = delegatee != address(0);
                uint256 delegatorBalance = _getBalance(delegator);
                if (delegatingNow) {
                  _governancePowerTransferByType(delegatorBalance, 0, currentDelegatee, delegationType);
                }
                if (willDelegateAfter) {
                  _governancePowerTransferByType(0, delegatorBalance, delegatee, delegationType);
                }
                _updateDelegateeByType(delegator, delegationType, delegatee);
                if (willDelegateAfter != delegatingNow) {
                  _setDelegationState(
                    delegator,
                    _updateDelegationModeByType(delegatorState, delegationType, willDelegateAfter)
                  );
                }
                emit DelegateChanged(delegator, delegatee, delegationType);
              }
            }
            // 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: agpl-3.0
            pragma solidity ^0.8.0;
            /**
             * @title VersionedInitializable
             *
             * @dev Helper contract to support initializer functions. To use it, replace
             * the constructor with a function that has the `initializer` modifier.
             * WARNING: Unlike constructors, initializer functions must be manually
             * invoked. This applies both to deploying an Initializable contract, as well
             * as extending an Initializable contract via inheritance.
             * WARNING: When used with inheritance, manual care must be taken to not invoke
             * a parent initializer twice, or ensure that all initializers are idempotent,
             * because this is not dealt with automatically as with constructors.
             *
             * @author Aave, inspired by the OpenZeppelin Initializable contract
             */
            abstract contract VersionedInitializable {
              /**
               * @dev Indicates that the contract has been initialized.
               */
              uint256 internal lastInitializedRevision = 0;
              /**
               * @dev Modifier to use in the initializer function of a contract.
               */
              modifier initializer() {
                uint256 revision = getRevision();
                require(revision > lastInitializedRevision, 'Contract instance has already been initialized');
                lastInitializedRevision = revision;
                _;
              }
              /// @dev returns the revision number of the contract.
              /// Needs to be defined in the inherited class as a constant.
              function getRevision() internal pure virtual returns (uint256);
              // Reserved storage space to allow for layout changes in the future.
              uint256[50] private ______gap;
            }
            // SPDX-License-Identifier: MIT
            // Contract modified from OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) to remove local
            // fallback storage variables, so contract does not affect on existing storage layout. This works as its used on contracts
            // that have name and revision < 32 bytes
            pragma solidity ^0.8.10;
            import {ECDSA} from 'openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol';
            import {ShortStrings, ShortString} from 'openzeppelin-contracts/contracts/utils/ShortStrings.sol';
            import {IERC5267} from 'openzeppelin-contracts/contracts/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;
              /**
               * @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].
               */
              /// @dev BGD: removed usage of fallback variables to not modify previous storage layout. As we know that the length of
              ///           name and version will not be bigger than 32 bytes we use toShortString as there is no need to use the fallback system.
              constructor(string memory name, string memory version) {
                _name = name.toShortString();
                _version = version.toShortString();
                _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
                returns (
                  bytes1 fields,
                  string memory name,
                  string memory version,
                  uint256 chainId,
                  address verifyingContract,
                  bytes32 salt,
                  uint256[] memory extensions
                )
              {
                return (
                  hex'0f', // 01111
                  _EIP712Name(),
                  _EIP712Version(),
                  block.chainid,
                  address(this),
                  bytes32(0),
                  new uint256[](0)
                );
              }
              /**
               * @dev The name parameter for the EIP712 domain.
               *
               * NOTE: By default this function reads _name which is an immutable value.
               * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
               *
               * _Available since v5.0._
               */
              /// @dev BGD: we use toString instead of toStringWithFallback as we dont have fallback, to not modify previous storage layout
              // solhint-disable-next-line func-name-mixedcase
              function _EIP712Name() internal view returns (string memory) {
                return _name.toString(); // _name.toStringWithFallback(_nameFallback);
              }
              /**
               * @dev The version parameter for the EIP712 domain.
               *
               * NOTE: By default this function reads _version which is an immutable value.
               * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
               *
               * _Available since v5.0._
               */
              /// @dev BGD: we use toString instead of toStringWithFallback as we dont have fallback, to not modify previous storage layout
              // solhint-disable-next-line func-name-mixedcase
              function _EIP712Version() internal view returns (string memory) {
                return _version.toString();
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {Context} from 'openzeppelin-contracts/contracts/utils/Context.sol';
            import {IERC20} from 'openzeppelin-contracts/contracts/token/ERC20/IERC20.sol';
            import {IERC20Metadata} from 'openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol';
            import {DelegationMode} from './DelegationAwareBalance.sol';
            // Inspired by OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
            abstract contract BaseAaveToken is Context, IERC20Metadata {
              struct DelegationAwareBalance {
                uint104 balance;
                uint72 delegatedPropositionBalance;
                uint72 delegatedVotingBalance;
                DelegationMode delegationMode;
              }
              mapping(address => DelegationAwareBalance) internal _balances;
              mapping(address => mapping(address => uint256)) internal _allowances;
              uint256 internal _totalSupply;
              string internal _name;
              string internal _symbol;
              // @dev DEPRECATED
              // kept for backwards compatibility with old storage layout
              uint8 private ______DEPRECATED_OLD_ERC20_DECIMALS;
              /**
               * @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;
              }
              function decimals() public view virtual override returns (uint8) {
                return 18;
              }
              function totalSupply() public view virtual override returns (uint256) {
                return _totalSupply;
              }
              function balanceOf(address account) public view virtual override returns (uint256) {
                return _balances[account].balance;
              }
              function transfer(address to, uint256 amount) public virtual override returns (bool) {
                address owner = _msgSender();
                _transfer(owner, to, amount);
                return true;
              }
              function allowance(address owner, address spender)
                public
                view
                virtual
                override
                returns (uint256)
              {
                return _allowances[owner][spender];
              }
              function approve(address spender, uint256 amount) public virtual override returns (bool) {
                address owner = _msgSender();
                _approve(owner, spender, amount);
                return true;
              }
              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;
              }
              function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                address owner = _msgSender();
                _approve(owner, spender, _allowances[owner][spender] + addedValue);
                return true;
              }
              function decreaseAllowance(address spender, uint256 subtractedValue)
                public
                virtual
                returns (bool)
              {
                address owner = _msgSender();
                uint256 currentAllowance = _allowances[owner][spender];
                require(currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero');
                unchecked {
                  _approve(owner, spender, currentAllowance - subtractedValue);
                }
                return true;
              }
              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');
                if (from != to) {
                  uint104 fromBalanceBefore = _balances[from].balance;
                  uint104 toBalanceBefore = _balances[to].balance;
                  require(fromBalanceBefore >= amount, 'ERC20: transfer amount exceeds balance');
                  unchecked {
                    _balances[from].balance = fromBalanceBefore - uint104(amount);
                  }
                  _balances[to].balance = toBalanceBefore + uint104(amount);
                  _afterTokenTransfer(from, to, fromBalanceBefore, toBalanceBefore, amount);
                }
                emit Transfer(from, to, amount);
              }
              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);
              }
              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 after token transfer hook, added for delegation system
               * @param from token sender
               * @param to token recipient
               * @param fromBalanceBefore balance of the sender before transfer
               * @param toBalanceBefore balance of the recipient before transfer
               * @param amount amount of tokens sent
               **/
              function _afterTokenTransfer(
                address from,
                address to,
                uint256 fromBalanceBefore,
                uint256 toBalanceBefore,
                uint256 amount
              ) internal virtual {}
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /** @notice influenced by OpenZeppelin SafeCast lib, which is missing to uint72 cast
             * @author BGD Labs
             */
            library SafeCast72 {
              /**
               * @dev Returns the downcasted uint72 from uint256, reverting on
               * overflow (when the input is greater than largest uint72).
               *
               * Counterpart to Solidity's `uint16` operator.
               *
               * Requirements:
               *
               * - input must fit into 72 bits
               */
              function toUint72(uint256 value) internal pure returns (uint72) {
                require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
                return uint72(value);
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface IGovernancePowerDelegationToken {
              enum GovernancePowerType {
                VOTING,
                PROPOSITION
              }
              /**
               * @dev emitted when a user delegates to another
               * @param delegator the user which delegated governance power
               * @param delegatee the delegatee
               * @param delegationType the type of delegation (VOTING, PROPOSITION)
               **/
              event DelegateChanged(
                address indexed delegator,
                address indexed delegatee,
                GovernancePowerType delegationType
              );
              // @dev we removed DelegatedPowerChanged event because to reconstruct the full state of the system,
              // is enough to have Transfer and DelegateChanged TODO: document it
              /**
               * @dev delegates the specific power to a delegatee
               * @param delegatee the user which delegated power will change
               * @param delegationType the type of delegation (VOTING, PROPOSITION)
               **/
              function delegateByType(address delegatee, GovernancePowerType delegationType) external;
              /**
               * @dev delegates all the governance powers to a specific user
               * @param delegatee the user to which the powers will be delegated
               **/
              function delegate(address delegatee) external;
              /**
               * @dev returns the delegatee of an user
               * @param delegator the address of the delegator
               * @param delegationType the type of delegation (VOTING, PROPOSITION)
               * @return address of the specified delegatee
               **/
              function getDelegateeByType(address delegator, GovernancePowerType delegationType)
                external
                view
                returns (address);
              /**
               * @dev returns delegates of an user
               * @param delegator the address of the delegator
               * @return a tuple of addresses the VOTING and PROPOSITION delegatee
               **/
              function getDelegates(address delegator)
                external
                view
                returns (address, address);
              /**
               * @dev returns the current voting or proposition power of a user.
               * @param user the user
               * @param delegationType the type of delegation (VOTING, PROPOSITION)
               * @return the current voting or proposition power of a user
               **/
              function getPowerCurrent(address user, GovernancePowerType delegationType)
                external
                view
                returns (uint256);
              /**
               * @dev returns the current voting or proposition power of a user.
               * @param user the user
               * @return the current voting and proposition power of a user
               **/
              function getPowersCurrent(address user)
                external
                view
                returns (uint256, uint256);
              /**
               * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
               * @param delegator the owner of the funds
               * @param delegatee the user to who owner delegates his governance power
               * @param delegationType the type of governance power delegation (VOTING, PROPOSITION)
               * @param deadline the deadline timestamp, type(uint256).max for no deadline
               * @param v signature param
               * @param s signature param
               * @param r signature param
               */
              function metaDelegateByType(
                address delegator,
                address delegatee,
                GovernancePowerType delegationType,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
              ) external;
              /**
               * @dev implements the permit function as for https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
               * @param delegator the owner of the funds
               * @param delegatee the user to who delegator delegates his voting and proposition governance power
               * @param deadline the deadline timestamp, type(uint256).max for no deadline
               * @param v signature param
               * @param s signature param
               * @param r signature param
               */
              function metaDelegate(
                address delegator,
                address delegatee,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
              ) external;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            enum DelegationMode {
              NO_DELEGATION,
              VOTING_DELEGATED,
              PROPOSITION_DELEGATED,
              FULL_POWER_DELEGATED
            }
            // 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 (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) (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 (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
                    }
                }
            }
            

            File 7 of 7: District0xContribution
            pragma solidity ^0.4.11;
            
            
            library SafeMath {
              function mul(uint a, uint b) internal returns (uint) {
                uint c = a * b;
                assert(a == 0 || c / a == b);
                return c;
              }
            
              function div(uint a, uint b) internal returns (uint) {
                // assert(b > 0); // Solidity automatically throws when dividing by 0
                uint c = a / b;
                // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                return c;
              }
            
              function sub(uint a, uint b) internal returns (uint) {
                assert(b <= a);
                return a - b;
              }
            
              function add(uint a, uint b) internal returns (uint) {
                uint c = a + b;
                assert(c >= a);
                return c;
              }
            
              function max64(uint64 a, uint64 b) internal constant returns (uint64) {
                return a >= b ? a : b;
              }
            
              function min64(uint64 a, uint64 b) internal constant returns (uint64) {
                return a < b ? a : b;
              }
            
              function max256(uint256 a, uint256 b) internal constant returns (uint256) {
                return a >= b ? a : b;
              }
            
              function min256(uint256 a, uint256 b) internal constant returns (uint256) {
                return a < b ? a : b;
              }
            
              function assert(bool assertion) internal {
                if (!assertion) {
                  throw;
                }
              }
            }
            
            contract Ownable {
            
                /// @dev `owner` is the only address that can call a function with this
                /// modifier
                modifier onlyOwner() {
                    require(msg.sender == owner);
                    _;
                }
            
                address public owner;
            
                /// @notice The Constructor assigns the message sender to be `owner`
                function Ownable() {
                    owner = msg.sender;
                }
            
                address public newOwner;
            
                /// @notice `owner` can step down and assign some other address to this role
                /// @param _newOwner The address of the new owner.
                function changeOwner(address _newOwner) onlyOwner {
                    newOwner = _newOwner;
                }
            
            
                function acceptOwnership() {
                    if (msg.sender == newOwner) {
                        owner = newOwner;
                    }
                }
            }
            
            contract Pausable is Ownable {
              bool public stopped;
              event onEmergencyChanged(bool isStopped);
            
              modifier stopInEmergency {
                if (stopped) {
                  throw;
                }
                _;
              }
            
              modifier onlyInEmergency {
                if (!stopped) {
                  throw;
                }
                _;
              }
            
              // called by the owner on emergency, triggers stopped state
              function emergencyStop() external onlyOwner {
                stopped = true;
                onEmergencyChanged(stopped);
              }
            
              // called by the owner on end of emergency, returns to normal state
              function release() external onlyOwner onlyInEmergency {
                stopped = false;
                onEmergencyChanged(stopped);
              }
            
            }
            
            contract ERC20Basic {
              function totalSupply() constant returns (uint);
              function balanceOf(address who) constant returns (uint);
              function transfer(address to, uint value) returns (bool);
              event Transfer(address indexed from, address indexed to, uint value);
            }
            
            contract ERC20 is ERC20Basic {
            
              mapping(address => uint) balances;
            
              function allowance(address owner, address spender) constant returns (uint);
              function transferFrom(address from, address to, uint value) returns (bool);
              function approve(address spender, uint value) returns (bool);
              function approveAndCall(address spender, uint256 value, bytes extraData) returns (bool);
              event Approval(address indexed owner, address indexed spender, uint value);
            
              function doTransfer(address _from, address _to, uint _amount) internal returns(bool);
            }
            
            contract GrantsControlled {
                modifier onlyGrantsController { if (msg.sender != grantsController) throw; _; }
            
                address public grantsController;
            
                function GrantsControlled() { grantsController = msg.sender;}
            
                function changeGrantsController(address _newController) onlyGrantsController {
                    grantsController = _newController;
                }
            }
            
            contract LimitedTransferToken is ERC20 {
              // Checks whether it can transfer or otherwise throws.
              modifier canTransfer(address _sender, uint _value) {
               if (_value > transferableTokens(_sender, uint64(now))) throw;
               _;
              }
            
              // Checks modifier and allows transfer if tokens are not locked.
              function transfer(address _to, uint _value) canTransfer(msg.sender, _value) returns (bool) {
               return super.transfer(_to, _value);
              }
            
              // Checks modifier and allows transfer if tokens are not locked.
              function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) returns (bool) {
               return super.transferFrom(_from, _to, _value);
              }
            
              // Default transferable tokens function returns all tokens for a holder (no limit).
              function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
                return balanceOf(holder);
              }
            }
            
            contract Controlled {
                /// @notice The address of the controller is the only address that can call
                ///  a function with this modifier
                modifier onlyController { if (msg.sender != controller) throw; _; }
            
                address public controller;
            
                function Controlled() { controller = msg.sender;}
            
                /// @notice Changes the controller of the contract
                /// @param _newController The new controller of the contract
                function changeController(address _newController) onlyController {
                    controller = _newController;
                }
            }
            
            contract MiniMeToken is ERC20, Controlled {
                using SafeMath for uint;
            
                string public name;                //The Token's name: e.g. DigixDAO Tokens
                uint8 public decimals;             //Number of decimals of the smallest unit
                string public symbol;              //An identifier: e.g. REP
                string public version = 'MMT_0.1'; //An arbitrary versioning scheme
            
            
                /// @dev `Checkpoint` is the structure that attaches a block number to a
                ///  given value, the block number attached is the one that last changed the
                ///  value
                struct  Checkpoint {
            
                    // `fromBlock` is the block number that the value was generated from
                    uint128 fromBlock;
            
                    // `value` is the amount of tokens at a specific block number
                    uint128 value;
                }
            
                // `parentToken` is the Token address that was cloned to produce this token;
                //  it will be 0x0 for a token that was not cloned
                MiniMeToken public parentToken;
            
                // `parentSnapShotBlock` is the block number from the Parent Token that was
                //  used to determine the initial distribution of the Clone Token
                uint public parentSnapShotBlock;
            
                // `creationBlock` is the block number that the Clone Token was created
                uint public creationBlock;
            
                // `balances` is the map that tracks the balance of each address, in this
                //  contract when the balance changes the block number that the change
                //  occurred is also included in the map
                mapping (address => Checkpoint[]) balances;
            
                // `allowed` tracks any extra transfer rights as in all ERC20 tokens
                mapping (address => mapping (address => uint256)) allowed;
            
                // Tracks the history of the `totalSupply` of the token
                Checkpoint[] totalSupplyHistory;
            
                // Flag that determines if the token is transferable or not.
                bool public transfersEnabled;
            
                // The factory used to create new clone tokens
                MiniMeTokenFactory public tokenFactory;
            
            ////////////////
            // Constructor
            ////////////////
            
                /// @notice Constructor to create a MiniMeToken
                /// @param _tokenFactory The address of the MiniMeTokenFactory contract that
                ///  will create the Clone token contracts, the token factory needs to be
                ///  deployed first
                /// @param _parentToken Address of the parent token, set to 0x0 if it is a
                ///  new token
                /// @param _parentSnapShotBlock Block of the parent token that will
                ///  determine the initial distribution of the clone token, set to 0 if it
                ///  is a new token
                /// @param _tokenName Name of the new token
                /// @param _decimalUnits Number of decimals of the new token
                /// @param _tokenSymbol Token Symbol for the new token
                /// @param _transfersEnabled If true, tokens will be able to be transferred
                function MiniMeToken(
                    address _tokenFactory,
                    address _parentToken,
                    uint _parentSnapShotBlock,
                    string _tokenName,
                    uint8 _decimalUnits,
                    string _tokenSymbol,
                    bool _transfersEnabled
                ) {
                    tokenFactory = MiniMeTokenFactory(_tokenFactory);
                    name = _tokenName;                                 // Set the name
                    decimals = _decimalUnits;                          // Set the decimals
                    symbol = _tokenSymbol;                             // Set the symbol
                    parentToken = MiniMeToken(_parentToken);
                    parentSnapShotBlock = _parentSnapShotBlock;
                    transfersEnabled = _transfersEnabled;
                    creationBlock = block.number;
                }
            
            
            ///////////////////
            // ERC20 Methods
            ///////////////////
            
                /// @notice Send `_amount` tokens to `_to` from `msg.sender`
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return Whether the transfer was successful or not
                function transfer(address _to, uint256 _amount) returns (bool success) {
                    if (!transfersEnabled) throw;
                    return doTransfer(msg.sender, _to, _amount);
                }
            
                /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
                ///  is approved by `_from`
                /// @param _from The address holding the tokens being transferred
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return True if the transfer was successful
                function transferFrom(address _from, address _to, uint256 _amount
                ) returns (bool success) {
            
                    // The controller of this contract can move tokens around at will,
                    //  this is important to recognize! Confirm that you trust the
                    //  controller of this contract, which in most situations should be
                    //  another open source smart contract or 0x0
                    if (msg.sender != controller) {
                        if (!transfersEnabled) throw;
            
                        // The standard ERC 20 transferFrom functionality
                        if (allowed[_from][msg.sender] < _amount) return false;
                        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
                    }
                    return doTransfer(_from, _to, _amount);
                }
            
                /// @dev This is the actual transfer function in the token contract, it can
                ///  only be called by other functions in this contract.
                /// @param _from The address holding the tokens being transferred
                /// @param _to The address of the recipient
                /// @param _amount The amount of tokens to be transferred
                /// @return True if the transfer was successful
                function doTransfer(address _from, address _to, uint _amount
                ) internal returns(bool) {
            
                       if (_amount == 0) {
                           return true;
                       }
            
                       if (parentSnapShotBlock >= block.number) throw;
            
                       // Do not allow transfer to 0x0 or the token contract itself
                       if ((_to == 0) || (_to == address(this))) throw;
            
                       // If the amount being transfered is more than the balance of the
                       //  account the transfer returns false
                       var previousBalanceFrom = balanceOfAt(_from, block.number);
                       if (previousBalanceFrom < _amount) {
                           return false;
                       }
            
                       // Alerts the token controller of the transfer
                       if (isContract(controller)) {
                           if (!TokenController(controller).onTransfer(_from, _to, _amount))
                           throw;
                       }
            
                       // First update the balance array with the new value for the address
                       //  sending the tokens
                       updateValueAtNow(balances[_from], previousBalanceFrom.sub(_amount));
            
                       // Then update the balance array with the new value for the address
                       //  receiving the tokens
                       var previousBalanceTo = balanceOfAt(_to, block.number);
                       updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
            
                       // An event to make the transfer easy to find on the blockchain
                       Transfer(_from, _to, _amount);
            
                       return true;
                }
            
                /// @param _owner The address that's balance is being requested
                /// @return The balance of `_owner` at the current block
                function balanceOf(address _owner) constant returns (uint256 balance) {
                    return balanceOfAt(_owner, block.number);
                }
            
                /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
                ///  its behalf. This is a modified version of the ERC20 approve function
                ///  to be a little bit safer
                /// @param _spender The address of the account able to transfer the tokens
                /// @param _amount The amount of tokens to be approved for transfer
                /// @return True if the approval was successful
                function approve(address _spender, uint256 _amount) returns (bool success) {
                    if (!transfersEnabled) throw;
            
                    // To change the approve amount you first have to reduce the addresses`
                    //  allowance to zero by calling `approve(_spender,0)` if it is not
                    //  already 0 to mitigate the race condition described here:
                    //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                    if ((_amount!=0) && (allowed[msg.sender][_spender] !=0)) throw;
            
                    // Alerts the token controller of the approve function call
                    if (isContract(controller)) {
                        if (!TokenController(controller).onApprove(msg.sender, _spender, _amount))
                            throw;
                    }
            
                    allowed[msg.sender][_spender] = _amount;
                    Approval(msg.sender, _spender, _amount);
                    return true;
                }
            
                /// @dev This function makes it easy to read the `allowed[]` map
                /// @param _owner The address of the account that owns the token
                /// @param _spender The address of the account able to transfer the tokens
                /// @return Amount of remaining tokens of _owner that _spender is allowed
                ///  to spend
                function allowance(address _owner, address _spender
                ) constant returns (uint256 remaining) {
                    return allowed[_owner][_spender];
                }
            
                /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
                ///  its behalf, and then a function is triggered in the contract that is
                ///  being approved, `_spender`. This allows users to use their tokens to
                ///  interact with contracts in one function call instead of two
                /// @param _spender The address of the contract able to transfer the tokens
                /// @param _amount The amount of tokens to be approved for transfer
                /// @return True if the function call was successful
                function approveAndCall(address _spender, uint256 _amount, bytes _extraData
                ) returns (bool success) {
                    if (!approve(_spender, _amount)) throw;
            
                    ApproveAndCallFallBack(_spender).receiveApproval(
                        msg.sender,
                        _amount,
                        this,
                        _extraData
                    );
            
                    return true;
                }
            
                /// @dev This function makes it easy to get the total number of tokens
                /// @return The total number of tokens
                function totalSupply() constant returns (uint) {
                    return totalSupplyAt(block.number);
                }
            
            
            ////////////////
            // Query balance and totalSupply in History
            ////////////////
            
                /// @dev Queries the balance of `_owner` at a specific `_blockNumber`
                /// @param _owner The address from which the balance will be retrieved
                /// @param _blockNumber The block number when the balance is queried
                /// @return The balance at `_blockNumber`
                function balanceOfAt(address _owner, uint _blockNumber) constant
                    returns (uint) {
            
                    // These next few lines are used when the balance of the token is
                    //  requested before a check point was ever created for this token, it
                    //  requires that the `parentToken.balanceOfAt` be queried at the
                    //  genesis block for that token as this contains initial balance of
                    //  this token
                    if ((balances[_owner].length == 0)
                        || (balances[_owner][0].fromBlock > _blockNumber)) {
                        if (address(parentToken) != 0) {
                            return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
                        } else {
                            // Has no parent
                            return 0;
                        }
            
                    // This will return the expected balance during normal situations
                    } else {
                        return getValueAt(balances[_owner], _blockNumber);
                    }
                }
            
                /// @notice Total amount of tokens at a specific `_blockNumber`.
                /// @param _blockNumber The block number when the totalSupply is queried
                /// @return The total amount of tokens at `_blockNumber`
                function totalSupplyAt(uint _blockNumber) constant returns(uint) {
            
                    // These next few lines are used when the totalSupply of the token is
                    //  requested before a check point was ever created for this token, it
                    //  requires that the `parentToken.totalSupplyAt` be queried at the
                    //  genesis block for this token as that contains totalSupply of this
                    //  token at this block number.
                    if ((totalSupplyHistory.length == 0)
                        || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
                        if (address(parentToken) != 0) {
                            return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
                        } else {
                            return 0;
                        }
            
                    // This will return the expected totalSupply during normal situations
                    } else {
                        return getValueAt(totalSupplyHistory, _blockNumber);
                    }
                }
            
            ////////////////
            // Clone Token Method
            ////////////////
            
                /// @notice Creates a new clone token with the initial distribution being
                ///  this token at `_snapshotBlock`
                /// @param _cloneTokenName Name of the clone token
                /// @param _cloneDecimalUnits Number of decimals of the smallest unit
                /// @param _cloneTokenSymbol Symbol of the clone token
                /// @param _snapshotBlock Block when the distribution of the parent token is
                ///  copied to set the initial distribution of the new clone token;
                ///  if the block is zero than the actual block, the current block is used
                /// @param _transfersEnabled True if transfers are allowed in the clone
                /// @return The address of the new MiniMeToken Contract
                function createCloneToken(
                    string _cloneTokenName,
                    uint8 _cloneDecimalUnits,
                    string _cloneTokenSymbol,
                    uint _snapshotBlock,
                    bool _transfersEnabled
                    ) returns(address) {
                    if (_snapshotBlock == 0) _snapshotBlock = block.number;
                    MiniMeToken cloneToken = tokenFactory.createCloneToken(
                        this,
                        _snapshotBlock,
                        _cloneTokenName,
                        _cloneDecimalUnits,
                        _cloneTokenSymbol,
                        _transfersEnabled
                        );
            
                    cloneToken.changeController(msg.sender);
            
                    // An event to make the token easy to find on the blockchain
                    NewCloneToken(address(cloneToken), _snapshotBlock);
                    return address(cloneToken);
                }
            
            ////////////////
            // Generate and destroy tokens
            ////////////////
            
                /// @notice Generates `_amount` tokens that are assigned to `_owner`
                /// @param _owner The address that will be assigned the new tokens
                /// @param _amount The quantity of tokens generated
                /// @return True if the tokens are generated correctly
                function generateTokens(address _owner, uint _amount
                ) onlyController returns (bool) {
                    uint curTotalSupply = getValueAt(totalSupplyHistory, block.number);
                    updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
                    var previousBalanceTo = balanceOf(_owner);
                    updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount));
                    Transfer(0, _owner, _amount);
                    return true;
                }
            
            
                /// @notice Burns `_amount` tokens from `_owner`
                /// @param _owner The address that will lose the tokens
                /// @param _amount The quantity of tokens to burn
                /// @return True if the tokens are burned correctly
                function destroyTokens(address _owner, uint _amount
                ) onlyController returns (bool) {
                    uint curTotalSupply = getValueAt(totalSupplyHistory, block.number);
                    if (curTotalSupply < _amount) throw;
                    updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount));
                    var previousBalanceFrom = balanceOf(_owner);
                    if (previousBalanceFrom < _amount) throw;
                    updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount));
                    Transfer(_owner, 0, _amount);
                    return true;
                }
            
            ////////////////
            // Enable tokens transfers
            ////////////////
            
            
                /// @notice Enables token holders to transfer their tokens freely if true
                /// @param _transfersEnabled True if transfers are allowed in the clone
                function enableTransfers(bool _transfersEnabled) onlyController {
                    transfersEnabled = _transfersEnabled;
                }
            
            ////////////////
            // Internal helper functions to query and set a value in a snapshot array
            ////////////////
            
                /// @dev `getValueAt` retrieves the number of tokens at a given block number
                /// @param checkpoints The history of values being queried
                /// @param _block The block number to retrieve the value at
                /// @return The number of tokens being queried
                function getValueAt(Checkpoint[] storage checkpoints, uint _block
                ) constant internal returns (uint) {
                    if (checkpoints.length == 0) return 0;
            
                    // Shortcut for the actual value
                    if (_block >= checkpoints[checkpoints.length-1].fromBlock)
                        return checkpoints[checkpoints.length-1].value;
                    if (_block < checkpoints[0].fromBlock) return 0;
            
                    // Binary search of the value in the array
                    uint min = 0;
                    uint max = checkpoints.length-1;
                    while (max > min) {
                        uint mid = (max + min + 1)/ 2;
                        if (checkpoints[mid].fromBlock<=_block) {
                            min = mid;
                        } else {
                            max = mid-1;
                        }
                    }
                    return checkpoints[min].value;
                }
            
                /// @dev `updateValueAtNow` used to update the `balances` map and the
                ///  `totalSupplyHistory`
                /// @param checkpoints The history of data being updated
                /// @param _value The new number of tokens
                function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
                ) internal  {
                    if ((checkpoints.length == 0)
                    || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
                           Checkpoint newCheckPoint = checkpoints[ checkpoints.length++ ];
                           newCheckPoint.fromBlock =  uint128(block.number);
                           newCheckPoint.value = uint128(_value);
                       } else {
                           Checkpoint oldCheckPoint = checkpoints[checkpoints.length-1];
                           oldCheckPoint.value = uint128(_value);
                       }
                }
            
                /// @dev Internal function to determine if an address is a contract
                /// @param _addr The address being queried
                /// @return True if `_addr` is a contract
                function isContract(address _addr) constant internal returns(bool) {
                    uint size;
                    if (_addr == 0) return false;
                    assembly {
                        size := extcodesize(_addr)
                    }
                    return size>0;
                }
            
                /// @dev Helper function to return a min betwen the two uints
                function min(uint a, uint b) internal returns (uint) {
                    return a < b ? a : b;
                }
            
                /// @notice The fallback function: If the contract's controller has not been
                ///  set to 0, then the `proxyPayment` method is called which relays the
                ///  ether and creates tokens as described in the token controller contract
                function ()  payable {
                    if (isContract(controller)) {
                        if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender))
                            throw;
                    } else {
                        throw;
                    }
                }
            
                //////////
                // Safety Methods
                //////////
            
                /// @notice This method can be used by the controller to extract mistakenly
                ///  sent tokens to this contract.
                /// @param _token The address of the token contract that you want to recover
                ///  set to 0 in case you want to extract ether.
                /// @param _claimer Address that tokens will be send to
                function claimTokens(address _token, address _claimer) onlyController {
                    if (_token == 0x0) {
                        _claimer.transfer(this.balance);
                        return;
                    }
            
                    ERC20Basic token = ERC20Basic(_token);
                    uint balance = token.balanceOf(this);
                    token.transfer(_claimer, balance);
                    ClaimedTokens(_token, _claimer, balance);
                }
            
            
            ////////////////
            // Events
            ////////////////
                event ClaimedTokens(address indexed _token, address indexed _claimer, uint _amount);
                event Transfer(address indexed _from, address indexed _to, uint256 _amount);
                event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
                event Approval(
                    address indexed _owner,
                    address indexed _spender,
                    uint256 _amount
                    );
            
            }
            
            
            ////////////////
            // MiniMeTokenFactory
            ////////////////
            
            /// @dev This contract is used to generate clone contracts from a contract.
            ///  In solidity this is the way to create a contract from a contract of the
            ///  same class
            contract MiniMeTokenFactory {
            
                /// @notice Update the DApp by creating a new token with new functionalities
                ///  the msg.sender becomes the controller of this clone token
                /// @param _parentToken Address of the token being cloned
                /// @param _snapshotBlock Block of the parent token that will
                ///  determine the initial distribution of the clone token
                /// @param _tokenName Name of the new token
                /// @param _decimalUnits Number of decimals of the new token
                /// @param _tokenSymbol Token Symbol for the new token
                /// @param _transfersEnabled If true, tokens will be able to be transferred
                /// @return The address of the new token contract
                function createCloneToken(
                    address _parentToken,
                    uint _snapshotBlock,
                    string _tokenName,
                    uint8 _decimalUnits,
                    string _tokenSymbol,
                    bool _transfersEnabled
                ) returns (MiniMeToken) {
                    MiniMeToken newToken = new MiniMeToken(
                        this,
                        _parentToken,
                        _snapshotBlock,
                        _tokenName,
                        _decimalUnits,
                        _tokenSymbol,
                        _transfersEnabled
                        );
            
                    newToken.changeController(msg.sender);
                    return newToken;
                }
            }
            
            contract VestedToken is LimitedTransferToken, GrantsControlled {
              using SafeMath for uint;
            
              uint256 MAX_GRANTS_PER_ADDRESS = 20;
            
              struct TokenGrant {
                address granter;     // 20 bytes
                uint256 value;       // 32 bytes
                uint64 cliff;
                uint64 vesting;
                uint64 start;        // 3 * 8 = 24 bytes
                bool revokable;
                bool burnsOnRevoke;  // 2 * 1 = 2 bits? or 2 bytes?
              } // total 78 bytes = 3 sstore per operation (32 per sstore)
            
              mapping (address => TokenGrant[]) public grants;
            
              event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
            
              /**
               * @dev Grant tokens to a specified address
               * @param _to address The address which the tokens will be granted to.
               * @param _value uint256 The amount of tokens to be granted.
               * @param _start uint64 Time of the beginning of the grant.
               * @param _cliff uint64 Time of the cliff period.
               * @param _vesting uint64 The vesting period.
               */
              function grantVestedTokens(
                address _to,
                uint256 _value,
                uint64 _start,
                uint64 _cliff,
                uint64 _vesting,
                bool _revokable,
                bool _burnsOnRevoke
              ) onlyGrantsController public {
            
                // Check for date inconsistencies that may cause unexpected behavior
                if (_cliff < _start || _vesting < _cliff) {
                  throw;
                }
            
                if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw;   // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
            
                uint count = grants[_to].push(
                            TokenGrant(
                              _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
                              _value,
                              _cliff,
                              _vesting,
                              _start,
                              _revokable,
                              _burnsOnRevoke
                            )
                          );
            
                transfer(_to, _value);
            
                NewTokenGrant(msg.sender, _to, _value, count - 1);
              }
            
              /**
               * @dev Revoke the grant of tokens of a specifed address.
               * @param _holder The address which will have its tokens revoked.
               * @param _grantId The id of the token grant.
               */
              function revokeTokenGrant(address _holder, uint _grantId) public {
                TokenGrant grant = grants[_holder][_grantId];
            
                if (!grant.revokable) { // Check if grant was revokable
                  throw;
                }
            
                if (grant.granter != msg.sender) { // Only granter can revoke it
                  throw;
                }
            
                address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
            
                uint256 nonVested = nonVestedTokens(grant, uint64(now));
            
                // remove grant from array
                delete grants[_holder][_grantId];
                grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
                grants[_holder].length -= 1;
            
                // This will call MiniMe's doTransfer method, so token is transferred according to
                // MiniMe Token logic
                doTransfer(_holder, receiver, nonVested);
            
                Transfer(_holder, receiver, nonVested);
              }
            
              /**
               * @dev Revoke all grants of tokens of a specifed address.
               * @param _holder The address which will have its tokens revoked.
               */
                function revokeAllTokenGrants(address _holder) {
                    var grandsCount = tokenGrantsCount(_holder);
                    for (uint i = 0; i < grandsCount; i++) {
                      revokeTokenGrant(_holder, 0);
                    }
                }
            
              /**
               * @dev Calculate the total amount of transferable tokens of a holder at a given time
               * @param holder address The address of the holder
               * @param time uint64 The specific time.
               * @return An uint representing a holder's total amount of transferable tokens.
               */
              function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
                uint256 grantIndex = tokenGrantsCount(holder);
            
                if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
            
                // Iterate through all the grants the holder has, and add all non-vested tokens
                uint256 nonVested = 0;
                for (uint256 i = 0; i < grantIndex; i++) {
                  nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
                }
            
                // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
                uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
            
                // Return the minimum of how many vested can transfer and other value
                // in case there are other limiting transferability factors (default is balanceOf)
                return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));
              }
            
              /**
               * @dev Check the amount of grants that an address has.
               * @param _holder The holder of the grants.
               * @return A uint representing the total amount of grants.
               */
              function tokenGrantsCount(address _holder) constant returns (uint index) {
                return grants[_holder].length;
              }
            
              /**
               * @dev Calculate amount of vested tokens at a specifc time.
               * @param tokens uint256 The amount of tokens grantted.
               * @param time uint64 The time to be checked
               * @param start uint64 A time representing the begining of the grant
               * @param cliff uint64 The cliff period.
               * @param vesting uint64 The vesting period.
               * @return An uint representing the amount of vested tokensof a specif grant.
               *  transferableTokens
               *   |                         _/--------   vestedTokens rect
               *   |                       _/
               *   |                     _/
               *   |                   _/
               *   |                 _/
               *   |                /
               *   |              .|
               *   |            .  |
               *   |          .    |
               *   |        .      |
               *   |      .        |
               *   |    .          |
               *   +===+===========+---------+----------> time
               *      Start       Clift    Vesting
               */
              function calculateVestedTokens(
                uint256 tokens,
                uint256 time,
                uint256 start,
                uint256 cliff,
                uint256 vesting) constant returns (uint256)
                {
                  // Shortcuts for before cliff and after vesting cases.
                  if (time < cliff) return 0;
                  if (time >= vesting) return tokens;
            
                  // Interpolate all vested tokens.
                  // As before cliff the shortcut returns 0, we can use just calculate a value
                  // in the vesting rect (as shown in above's figure)
            
                  // vestedTokens = tokens * (time - start) / (vesting - start)
                  uint256 vestedTokens = SafeMath.div(
                                                SafeMath.mul(
                                                  tokens,
                                                  SafeMath.sub(time, start)
                                                  ),
                                                SafeMath.sub(vesting, start)
                                                );
            
                  return vestedTokens;
              }
            
              /**
               * @dev Get all information about a specifc grant.
               * @param _holder The address which will have its tokens revoked.
               * @param _grantId The id of the token grant.
               * @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
               * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
               */
              function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
                TokenGrant grant = grants[_holder][_grantId];
            
                granter = grant.granter;
                value = grant.value;
                start = grant.start;
                cliff = grant.cliff;
                vesting = grant.vesting;
                revokable = grant.revokable;
                burnsOnRevoke = grant.burnsOnRevoke;
            
                vested = vestedTokens(grant, uint64(now));
              }
            
              /**
               * @dev Get the amount of vested tokens at a specific time.
               * @param grant TokenGrant The grant to be checked.
               * @param time The time to be checked
               * @return An uint representing the amount of vested tokens of a specific grant at a specific time.
               */
              function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
                return calculateVestedTokens(
                  grant.value,
                  uint256(time),
                  uint256(grant.start),
                  uint256(grant.cliff),
                  uint256(grant.vesting)
                );
              }
            
              /**
               * @dev Calculate the amount of non vested tokens at a specific time.
               * @param grant TokenGrant The grant to be checked.
               * @param time uint64 The time to be checked
               * @return An uint representing the amount of non vested tokens of a specifc grant on the
               * passed time frame.
               */
              function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
                return grant.value.sub(vestedTokens(grant, time));
              }
            
              /**
               * @dev Calculate the date when the holder can trasfer all its tokens
               * @param holder address The address of the holder
               * @return An uint representing the date of the last transferable tokens.
               */
              function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
                date = uint64(now);
                uint256 grantIndex = grants[holder].length;
                for (uint256 i = 0; i < grantIndex; i++) {
                  date = SafeMath.max64(grants[holder][i].vesting, date);
                }
              }
            }
            
            contract ApproveAndCallFallBack {
                function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
            }
            
            
            contract TokenController {
                /// @notice Called when `_owner` sends ether to the MiniMe Token contract
                /// @param _owner The address that sent the ether to create tokens
                /// @return True if the ether is accepted, false if it throws
                function proxyPayment(address _owner) payable returns(bool);
            
                /// @notice Notifies the controller about a token transfer allowing the
                ///  controller to react if desired
                /// @param _from The origin of the transfer
                /// @param _to The destination of the transfer
                /// @param _amount The amount of the transfer
                /// @return False if the controller does not authorize the transfer
                function onTransfer(address _from, address _to, uint _amount) returns(bool);
            
                /// @notice Notifies the controller about an approval allowing the
                ///  controller to react if desired
                /// @param _owner The address that calls `approve()`
                /// @param _spender The spender in the `approve()` call
                /// @param _amount The amount in the `approve()` call
                /// @return False if the controller does not authorize the approval
                function onApprove(address _owner, address _spender, uint _amount)
                    returns(bool);
            }
            
            contract District0xNetworkToken is MiniMeToken, VestedToken {
                function District0xNetworkToken(address _controller, address _tokenFactory)
                    MiniMeToken(
                        _tokenFactory,
                        0x0,                        // no parent token
                        0,                          // no snapshot block number from parent
                        "district0x Network Token", // Token name
                        18,                         // Decimals
                        "DNT",                      // Symbol
                        true                        // Enable transfers
                        )
                {
                    changeController(_controller);
                    changeGrantsController(_controller);
                }
            }
            
            contract HasNoTokens is Ownable {
            
              District0xNetworkToken public district0xNetworkToken;
            
             /**
              * @dev Reject all ERC23 compatible tokens
              * @param from_ address The address that is transferring the tokens
              * @param value_ uint256 the amount of the specified token
              * @param data_ Bytes The data passed from the caller.
              */
              function tokenFallback(address from_, uint256 value_, bytes data_) external {
                throw;
              }
            
              function isTokenSaleToken(address tokenAddr) returns(bool);
            
              /**
               * @dev Reclaim all ERC20Basic compatible tokens
               * @param tokenAddr address The address of the token contract
               */
              function reclaimToken(address tokenAddr) external onlyOwner {
                require(!isTokenSaleToken(tokenAddr));
                ERC20Basic tokenInst = ERC20Basic(tokenAddr);
                uint256 balance = tokenInst.balanceOf(this);
                tokenInst.transfer(msg.sender, balance);
              }
            }
            
            
            contract District0xContribution is Pausable, HasNoTokens, TokenController {
                using SafeMath for uint;
            
                District0xNetworkToken public district0xNetworkToken;
                address public multisigWallet;                                      // Wallet that receives all sale funds
                address public founder1;                                            // Wallet of founder 1
                address public founder2;                                            // Wallet of founder 2
                address public earlySponsor;                                        // Wallet of early sponsor
                address[] public advisers;                                          // 4 Wallets of advisors
            
                uint public constant FOUNDER1_STAKE = 119000000 ether;              // 119M DNT
                uint public constant FOUNDER2_STAKE = 79000000 ether;               // 79M  DNT
                uint public constant EARLY_CONTRIBUTOR_STAKE = 5000000 ether;       // 5M   DNT
                uint public constant ADVISER_STAKE = 5000000 ether;                 // 5M   DNT
                uint public constant ADVISER_STAKE2 = 1000000 ether;                // 1M   DNT
                uint public constant COMMUNITY_ADVISERS_STAKE = 5000000 ether;      // 5M   DNT
                uint public constant CONTRIB_PERIOD1_STAKE = 600000000 ether;       // 600M DNT
                uint public constant CONTRIB_PERIOD2_STAKE = 140000000 ether;       // 140M DNT
                uint public constant CONTRIB_PERIOD3_STAKE = 40000000 ether;        // 40M  DNT
            
                uint public minContribAmount = 0.01 ether;                          // 0.01 ether
                uint public maxGasPrice = 50000000000;                              // 50 GWei
            
                uint public constant TEAM_VESTING_CLIFF = 24 weeks;                 // 6 months vesting cliff for founders and advisors, except community advisors
                uint public constant TEAM_VESTING_PERIOD = 96 weeks;                // 2 years vesting period for founders and advisors, except community advisors
            
                uint public constant EARLY_CONTRIBUTOR_VESTING_CLIFF = 12 weeks;    // 3 months vesting cliff for early sponsor
                uint public constant EARLY_CONTRIBUTOR_VESTING_PERIOD = 24 weeks;   // 6 months vesting cliff for early sponsor
            
                bool public tokenTransfersEnabled = false;                          // DNT token transfers will be enabled manually
                                                                                    // after first contribution period
                                                                                    // Can't be disabled back
                struct Contributor {
                    uint amount;                        // Amount of ETH contributed by an address in given contribution period
                    bool isCompensated;                 // Whether this contributor received DNT token for ETH contribution
                    uint amountCompensated;             // Amount of DNT received. Not really needed to store,
                                                        // but stored for accounting and security purposes
                }
            
                uint public softCapAmount;                                 // Soft cap of contribution period in wei
                uint public afterSoftCapDuration;                          // Number of seconds to the end of sale from the moment of reaching soft cap (unless reaching hardcap)
                uint public hardCapAmount;                                 // When reached this amount of wei, the contribution will end instantly
                uint public startTime;                                     // Start time of contribution period in UNIX time
                uint public endTime;                                       // End time of contribution period in UNIX time
                bool public isEnabled;                                     // If contribution period was enabled by multisignature
                bool public softCapReached;                                // If soft cap was reached
                bool public hardCapReached;                                // If hard cap was reached
                uint public totalContributed;                              // Total amount of ETH contributed in given period
                address[] public contributorsKeys;                         // Addresses of all contributors in given contribution period
                mapping (address => Contributor) public contributors;
            
                event onContribution(uint totalContributed, address indexed contributor, uint amount,
                    uint contributorsCount);
                event onSoftCapReached(uint endTime);
                event onHardCapReached(uint endTime);
                event onCompensated(address indexed contributor, uint amount);
            
                modifier onlyMultisig() {
                    require(multisigWallet == msg.sender);
                    _;
                }
            
                function District0xContribution(
                    address _multisigWallet,
                    address _founder1,
                    address _founder2,
                    address _earlySponsor,
                    address[] _advisers
                ) {
                    require(_advisers.length == 5);
                    multisigWallet = _multisigWallet;
                    founder1 = _founder1;
                    founder2 = _founder2;
                    earlySponsor = _earlySponsor;
                    advisers = _advisers;
                }
            
                // @notice Returns true if contribution period is currently running
                function isContribPeriodRunning() constant returns (bool) {
                    return !hardCapReached &&
                           isEnabled &&
                           startTime <= now &&
                           endTime > now;
                }
            
                function contribute()
                    payable
                    stopInEmergency
                {
                    contributeWithAddress(msg.sender);
                }
            
                // @notice Function to participate in contribution period
                //  Amounts from the same address should be added up
                //  If soft or hard cap is reached, end time should be modified
                //  Funds should be transferred into multisig wallet
                // @param contributor Address that will receive DNT token
                function contributeWithAddress(address contributor)
                    payable
                    stopInEmergency
                {
                    require(tx.gasprice <= maxGasPrice);
                    require(msg.value >= minContribAmount);
                    require(isContribPeriodRunning());
            
                    uint contribValue = msg.value;
                    uint excessContribValue = 0;
            
                    uint oldTotalContributed = totalContributed;
            
                    totalContributed = oldTotalContributed.add(contribValue);
            
                    uint newTotalContributed = totalContributed;
            
                    // Soft cap was reached
                    if (newTotalContributed >= softCapAmount &&
                        oldTotalContributed < softCapAmount)
                    {
                        softCapReached = true;
                        endTime = afterSoftCapDuration.add(now);
                        onSoftCapReached(endTime);
                    }
                    // Hard cap was reached
                    if (newTotalContributed >= hardCapAmount &&
                        oldTotalContributed < hardCapAmount)
                    {
                        hardCapReached = true;
                        endTime = now;
                        onHardCapReached(endTime);
            
                        // Everything above hard cap will be sent back to contributor
                        excessContribValue = newTotalContributed.sub(hardCapAmount);
                        contribValue = contribValue.sub(excessContribValue);
            
                        totalContributed = hardCapAmount;
                    }
            
                    if (contributors[contributor].amount == 0) {
                        contributorsKeys.push(contributor);
                    }
            
                    contributors[contributor].amount = contributors[contributor].amount.add(contribValue);
            
                    multisigWallet.transfer(contribValue);
                    if (excessContribValue > 0) {
                        msg.sender.transfer(excessContribValue);
                    }
                    onContribution(newTotalContributed, contributor, contribValue, contributorsKeys.length);
                }
            
                // @notice This method is called by owner after contribution period ends, to distribute DNT in proportional manner
                //  Each contributor should receive DNT just once even if this method is called multiple times
                //  In case of many contributors must be able to compensate contributors in paginational way, otherwise might
                //  run out of gas if wanted to compensate all on one method call. Therefore parameters offset and limit
                // @param periodIndex Index of contribution period (0-2)
                // @param offset Number of first contributors to skip.
                // @param limit Max number of contributors compensated on this call
                function compensateContributors(uint offset, uint limit)
                    onlyOwner
                {
                    require(isEnabled);
                    require(endTime < now);
            
                    uint i = offset;
                    uint compensatedCount = 0;
                    uint contributorsCount = contributorsKeys.length;
            
                    uint ratio = CONTRIB_PERIOD1_STAKE
                        .mul(1000000000000000000)
                        .div(totalContributed);
            
                    while (i < contributorsCount && compensatedCount < limit) {
                        address contributorAddress = contributorsKeys[i];
                        if (!contributors[contributorAddress].isCompensated) {
                            uint amountContributed = contributors[contributorAddress].amount;
                            contributors[contributorAddress].isCompensated = true;
            
                            contributors[contributorAddress].amountCompensated =
                                amountContributed.mul(ratio).div(1000000000000000000);
            
                            district0xNetworkToken.transfer(contributorAddress, contributors[contributorAddress].amountCompensated);
                            onCompensated(contributorAddress, contributors[contributorAddress].amountCompensated);
            
                            compensatedCount++;
                        }
                        i++;
                    }
                }
            
                // @notice Method for setting up contribution period
                //  Only owner should be able to execute
                //  Setting first contribution period sets up vesting for founders & advisors
                //  Contribution period should still not be enabled after calling this method
                // @param softCapAmount Soft Cap in wei
                // @param afterSoftCapDuration Number of seconds till the end of sale in the moment of reaching soft cap (unless reaching hard cap)
                // @param hardCapAmount Hard Cap in wei
                // @param startTime Contribution start time in UNIX time
                // @param endTime Contribution end time in UNIX time
                function setContribPeriod(
                    uint _softCapAmount,
                    uint _afterSoftCapDuration,
                    uint _hardCapAmount,
                    uint _startTime,
                    uint _endTime
                )
                    onlyOwner
                {
                    require(_softCapAmount > 0);
                    require(_hardCapAmount > _softCapAmount);
                    require(_afterSoftCapDuration > 0);
                    require(_startTime > now);
                    require(_endTime > _startTime);
                    require(!isEnabled);
            
                    softCapAmount = _softCapAmount;
                    afterSoftCapDuration = _afterSoftCapDuration;
                    hardCapAmount = _hardCapAmount;
                    startTime = _startTime;
                    endTime = _endTime;
            
                    district0xNetworkToken.revokeAllTokenGrants(founder1);
                    district0xNetworkToken.revokeAllTokenGrants(founder2);
                    district0xNetworkToken.revokeAllTokenGrants(earlySponsor);
            
                    for (uint j = 0; j < advisers.length; j++) {
                        district0xNetworkToken.revokeAllTokenGrants(advisers[j]);
                    }
            
                    uint64 vestingDate = uint64(startTime.add(TEAM_VESTING_PERIOD));
                    uint64 cliffDate = uint64(startTime.add(TEAM_VESTING_CLIFF));
                    uint64 earlyContribVestingDate = uint64(startTime.add(EARLY_CONTRIBUTOR_VESTING_PERIOD));
                    uint64 earlyContribCliffDate = uint64(startTime.add(EARLY_CONTRIBUTOR_VESTING_CLIFF));
                    uint64 startDate = uint64(startTime);
            
                    district0xNetworkToken.grantVestedTokens(founder1, FOUNDER1_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(founder2, FOUNDER2_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(earlySponsor, EARLY_CONTRIBUTOR_STAKE, startDate, earlyContribCliffDate, earlyContribVestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[0], ADVISER_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[1], ADVISER_STAKE, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[2], ADVISER_STAKE2, startDate, cliffDate, vestingDate, true, false);
                    district0xNetworkToken.grantVestedTokens(advisers[3], ADVISER_STAKE2, startDate, cliffDate, vestingDate, true, false);
            
                    // Community advisors stake has no vesting, but we set it up this way, so we can revoke it in case of
                    // re-setting up contribution period
                    district0xNetworkToken.grantVestedTokens(advisers[4], COMMUNITY_ADVISERS_STAKE, startDate, startDate, startDate, true, false);
                }
            
                // @notice Enables contribution period
                //  Must be executed by multisignature
                function enableContribPeriod()
                    onlyMultisig
                {
                    require(startTime > now);
                    isEnabled = true;
                }
            
                // @notice Sets new min. contribution amount
                //  Only owner can execute
                //  Cannot be executed while contribution period is running
                // @param _minContribAmount new min. amount
                function setMinContribAmount(uint _minContribAmount)
                    onlyOwner
                {
                    require(_minContribAmount > 0);
                    require(startTime > now);
                    minContribAmount = _minContribAmount;
                }
            
                // @notice Sets new max gas price for contribution
                //  Only owner can execute
                //  Cannot be executed while contribution period is running
                // @param _minContribAmount new min. amount
                function setMaxGasPrice(uint _maxGasPrice)
                    onlyOwner
                {
                    require(_maxGasPrice > 0);
                    require(startTime > now);
                    maxGasPrice = _maxGasPrice;
                }
            
                // @notice Sets District0xNetworkToken contract
                //  Generates all DNT tokens and assigns them to this contract
                //  If token contract has already generated tokens, do not generate again
                // @param _district0xNetworkToken District0xNetworkToken address
                function setDistrict0xNetworkToken(address _district0xNetworkToken)
                    onlyOwner
                {
                    require(_district0xNetworkToken != 0x0);
                    require(!isEnabled);
                    district0xNetworkToken = District0xNetworkToken(_district0xNetworkToken);
                    if (district0xNetworkToken.totalSupply() == 0) {
                        district0xNetworkToken.generateTokens(this, FOUNDER1_STAKE
                            .add(FOUNDER2_STAKE)
                            .add(EARLY_CONTRIBUTOR_STAKE)
                            .add(ADVISER_STAKE.mul(2))
                            .add(ADVISER_STAKE2.mul(2))
                            .add(COMMUNITY_ADVISERS_STAKE)
                            .add(CONTRIB_PERIOD1_STAKE));
            
                        district0xNetworkToken.generateTokens(multisigWallet, CONTRIB_PERIOD2_STAKE
                            .add(CONTRIB_PERIOD3_STAKE));
                    }
                }
            
                // @notice Enables transfers of DNT
                //  Will be executed after first contribution period by owner
                function enableDistrict0xNetworkTokenTransfers()
                    onlyOwner
                {
                    require(endTime < now);
                    tokenTransfersEnabled = true;
                }
            
                // @notice Method to claim tokens accidentally sent to a DNT contract
                //  Only multisig wallet can execute
                // @param _token Address of claimed ERC20 Token
                function claimTokensFromTokenDistrict0xNetworkToken(address _token)
                    onlyMultisig
                {
                    district0xNetworkToken.claimTokens(_token, multisigWallet);
                }
            
                // @notice Kill method should not really be needed, but just in case
                function kill(address _to) onlyMultisig external {
                    suicide(_to);
                }
            
                function()
                    payable
                    stopInEmergency
                {
                    contributeWithAddress(msg.sender);
                }
            
                // MiniMe Controller default settings for allowing token transfers.
                function proxyPayment(address _owner) payable public returns (bool) {
                    throw;
                }
            
                // Before transfers are enabled for everyone, only this contract is allowed to distribute DNT
                function onTransfer(address _from, address _to, uint _amount) public returns (bool) {
                    return tokenTransfersEnabled || _from == address(this) || _to == address(this);
                }
            
                function onApprove(address _owner, address _spender, uint _amount) public returns (bool) {
                    return tokenTransfersEnabled;
                }
            
                function isTokenSaleToken(address tokenAddr) returns(bool) {
                    return district0xNetworkToken == tokenAddr;
                }
            
                /*
                 Following constant methods are used for tests and contribution web app
                 They don't impact logic of contribution contract, therefor DOES NOT NEED TO BE AUDITED
                 */
            
                // Used by contribution front-end to obtain contribution period properties
                function getContribPeriod()
                    constant
                    returns (bool[3] boolValues, uint[8] uintValues)
                {
                    boolValues[0] = isEnabled;
                    boolValues[1] = softCapReached;
                    boolValues[2] = hardCapReached;
            
                    uintValues[0] = softCapAmount;
                    uintValues[1] = afterSoftCapDuration;
                    uintValues[2] = hardCapAmount;
                    uintValues[3] = startTime;
                    uintValues[4] = endTime;
                    uintValues[5] = totalContributed;
                    uintValues[6] = contributorsKeys.length;
                    uintValues[7] = CONTRIB_PERIOD1_STAKE;
            
                    return (boolValues, uintValues);
                }
            
                // Used by contribution front-end to obtain contribution contract properties
                function getConfiguration()
                    constant
                    returns (bool, address, address, address, address, address[] _advisers, bool, uint)
                {
                    _advisers = new address[](advisers.length);
                    for (uint i = 0; i < advisers.length; i++) {
                        _advisers[i] = advisers[i];
                    }
                    return (stopped, multisigWallet, founder1, founder2, earlySponsor, _advisers, tokenTransfersEnabled,
                        maxGasPrice);
                }
            
                // Used by contribution front-end to obtain contributor's properties
                function getContributor(address contributorAddress)
                    constant
                    returns(uint, bool, uint)
                {
                    Contributor contributor = contributors[contributorAddress];
                    return (contributor.amount, contributor.isCompensated, contributor.amountCompensated);
                }
            
                // Function to verify if all contributors were compensated
                function getUncompensatedContributors(uint offset, uint limit)
                    constant
                    returns (uint[] contributorIndexes)
                {
                    uint contributorsCount = contributorsKeys.length;
            
                    if (limit == 0) {
                        limit = contributorsCount;
                    }
            
                    uint i = offset;
                    uint resultsCount = 0;
                    uint[] memory _contributorIndexes = new uint[](limit);
            
                    while (i < contributorsCount && resultsCount < limit) {
                        if (!contributors[contributorsKeys[i]].isCompensated) {
                            _contributorIndexes[resultsCount] = i;
                            resultsCount++;
                        }
                        i++;
                    }
            
                    contributorIndexes = new uint[](resultsCount);
                    for (i = 0; i < resultsCount; i++) {
                        contributorIndexes[i] = _contributorIndexes[i];
                    }
                    return contributorIndexes;
                }
            
                function getNow()
                    constant
                    returns(uint)
                {
                    return now;
                }
            }