// File: contracts/AirdropToken.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.7.4;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

import './interfaces/IJDFIStakingPool.sol';

contract AirdropToken is ERC20 {
  address private immutable _deployer;
  address private _jdfiStakingPool;

  constructor () ERC20('JusDeFi Airdrop', 'JDFI/A') {
    _deployer = msg.sender;
    _mint(msg.sender, 10020 ether);
  }

  /**
   * @notice set the JDFIStakingPool address once it is deployed
   * @param jdfiStakingPool JDFIStakingPool address
   */
  function setJDFIStakingPool (address jdfiStakingPool) external {
    require(msg.sender == _deployer, 'JusDeFi: sender must be deployer');
    require(_jdfiStakingPool == address(0), 'JusDeFi: JDFI Staking Pool contract has already been set');
    _jdfiStakingPool = jdfiStakingPool;
  }

  /**
   * @notice airdrop tokens to given accounts in given quantities
   * @dev _mint and _burn are used in place of _transfer due to gas considerations
   * @param accounts airdrop recipients
   * @param amounts airdrop quantities
   */
  function airdrop (address[] calldata accounts, uint[] calldata amounts) external {
    require(accounts.length == amounts.length, 'JusDeFi: array lengths do not match');

    uint length = accounts.length;
    uint initialSupply = totalSupply();

    for (uint i; i < length; i++) {
      _mint(accounts[i], amounts[i]);
    }

    _burn(msg.sender, totalSupply() - initialSupply);
  }

  /**
   * @notice exchange tokens for locked JDFI/S
   * @dev JDFI/S is locked in JDFIStakingPool _beforeTokenTransfer hook
   */
  function exchange () external {
    uint amount = balanceOf(msg.sender);
    _burn(msg.sender, amount);
    IJDFIStakingPool(_jdfiStakingPool).stake(amount);
    IJDFIStakingPool(_jdfiStakingPool).transfer(msg.sender, amount);
  }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/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 private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name, string memory symbol) {
        _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 internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

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

// File: contracts/interfaces/IJDFIStakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import './IStakingPool.sol';

interface IJDFIStakingPool is IStakingPool {
  function stake (uint amount) external;
  function unstake (uint amount) external;
}

// File: @openzeppelin/contracts/GSN/Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: @openzeppelin/contracts/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain`call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
      return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        return _functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        return _functionCallWithValue(target, data, value, errorMessage);
    }

    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: contracts/interfaces/IStakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

interface IStakingPool is IERC20 {
  function distributeRewards (uint amount) external;
}

// File: contracts/JusDeFi.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IWETH.sol';
import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol';

import './interfaces/IJusDeFi.sol';
import './interfaces/IStakingPool.sol';
import './interfaces/IJDFIStakingPool.sol';
import './FeePool.sol';
import './DevStakingPool.sol';
import './JDFIStakingPool.sol';
import './UNIV2StakingPool.sol';

contract JusDeFi is IJusDeFi, ERC20 {
  using FixedPoint for FixedPoint.uq112x112;
  using FixedPoint for FixedPoint.uq144x112;
  using SafeMath for uint;

  // _weth and _uniswapPair cannot be immutable because they are referenced in _beforeTokenTransfer
  address private _weth;
  address private immutable _uniswapRouter;
  address public _uniswapPair;

  address payable override public _feePool;
  address public immutable _devStakingPool;
  address public immutable _jdfiStakingPool;
  address public immutable _univ2StakingPool;

  uint private constant LIQUIDITY_EVENT_PERIOD = 3 days;
  bool public _liquidityEventOpen;
  uint public immutable _liquidityEventClosedAt;

  mapping (address => bool) private _implicitApprovalWhitelist;

  uint private constant RESERVE_TEAM = 1980 ether;
  uint private constant RESERVE_JUSTICE = 10020 ether;
  uint private constant RESERVE_LIQUIDITY_EVENT = 10000 ether;
  uint private constant REWARDS_SEED = 2000 ether;

  uint private constant JDFI_PER_ETH = 4;

  uint private constant ORACLE_PERIOD = 5 minutes;

  FixedPoint.uq112x112 private _priceAverage;
  uint private _priceCumulativeLast;
  uint32 private _blockTimestampLast;

  constructor (
    address airdropToken,
    address uniswapRouter
  )
    ERC20('JusDeFi', 'JDFI')
  {
    address weth = IUniswapV2Router02(uniswapRouter).WETH();
    _weth = weth;

    address uniswapPair = IUniswapV2Factory(
      IUniswapV2Router02(uniswapRouter).factory()
    ).createPair(weth, address(this));

    _uniswapRouter = uniswapRouter;
    _uniswapPair = uniswapPair;

    address devStakingPool = address(new DevStakingPool(weth));
    _devStakingPool = devStakingPool;
    address jdfiStakingPool = address(new JDFIStakingPool(airdropToken, RESERVE_LIQUIDITY_EVENT, weth, devStakingPool));
    _jdfiStakingPool = jdfiStakingPool;
    address univ2StakingPool = address(new UNIV2StakingPool(uniswapPair, uniswapRouter));
    _univ2StakingPool = univ2StakingPool;

    // mint staked JDFI after-the-fact to match minted JDFI/S
    _mint(jdfiStakingPool, RESERVE_LIQUIDITY_EVENT);

    // mint JDFI for conversion to locked JDFI/S
    _mint(airdropToken, RESERVE_JUSTICE);

    // mint team JDFI
    _mint(msg.sender, RESERVE_TEAM);

    // transfer all minted JDFI/E to sender
    IStakingPool(devStakingPool).transfer(msg.sender, IStakingPool(devStakingPool).balanceOf(address(this)));

    _liquidityEventClosedAt = block.timestamp + LIQUIDITY_EVENT_PERIOD;
    _liquidityEventOpen = true;

    // enable trusted addresses to transfer tokens without approval
    _implicitApprovalWhitelist[jdfiStakingPool] = true;
    _implicitApprovalWhitelist[univ2StakingPool] = true;
    _implicitApprovalWhitelist[uniswapRouter] = true;
  }

  /**
   * @notice get average JDFI price over the last ORACLE_PERIOD
   * @dev adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
   * @param amount quantity of ETH used for purchase
   * @return uint quantity of JDFI purchased, or zero if ORACLE_PERIOD has passed since las tupdate
   */
  function consult (uint amount) override external view returns (uint) {
    if (block.timestamp - uint(_blockTimestampLast) > ORACLE_PERIOD) {
      return 0;
    } else {
      return _priceAverage.mul(amount).decode144();
    }
  }

  /**
   * @notice OpenZeppelin ERC20#transferFrom: enable transfers by staking pools without allowance
   * @param from sender
   * @param to recipient
   * @param amount quantity transferred
   */
  function transferFrom (address from, address to, uint amount) override(IERC20, ERC20) public returns (bool) {
    if (_implicitApprovalWhitelist[msg.sender]) {
      _transfer(from, to, amount);
      return true;
    } else {
      return super.transferFrom(from, to, amount);
    }
  }

  /**
   * @notice burn tokens held by sender
   * @param amount quantity of tokens to burn
   */
  function burn (uint amount) override external {
    _burn(msg.sender, amount);
  }

  /**
   * @notice transfer tokens, deducting fee
   * @param account recipient of transfer
   * @param amount quantity of tokens to transfer, before deduction
   */
  function burnAndTransfer (address account, uint amount) override external {
    uint withheld = FeePool(_feePool).calculateWithholding(amount);
    _transfer(msg.sender, _feePool, withheld);
    _burn(_feePool, withheld / 2);
    _transfer(msg.sender, account, amount - withheld);
  }

  /**
   * @notice deposit ETH to receive JDFI/S at rate of 1:4
   */
  function liquidityEventDeposit () external payable {
    require(_liquidityEventOpen, 'JusDeFi: liquidity event has closed');

    try IStakingPool(_jdfiStakingPool).transfer(msg.sender, msg.value * JDFI_PER_ETH) returns (bool) {} catch {
      revert('JusDeFi: deposit amount surpasses available supply');
    }
  }

  /**
   * @notice close liquidity event, add Uniswap liquidity, burn undistributed JDFI
   */
  function liquidityEventClose () external {
    require(block.timestamp >= _liquidityEventClosedAt, 'JusDeFi: liquidity event still in progress');
    require(_liquidityEventOpen, 'JusDeFi: liquidity event has already ended');
    _liquidityEventOpen = false;

    uint remaining = IStakingPool(_jdfiStakingPool).balanceOf(address(this));
    uint distributed = RESERVE_LIQUIDITY_EVENT - remaining;

    // require minimum deposit to avoid nonspecific Uniswap error: ds-math-sub-underflow
    require(distributed >= 1 ether, 'JusDeFi: insufficient liquidity added');

    // prepare Uniswap for minting my FeePool
    IUniswapV2Pair pair = IUniswapV2Pair(_uniswapPair);

    address weth = _weth;
    IWETH(weth).deposit{ value: distributed / JDFI_PER_ETH }();
    IWETH(weth).transfer(address(pair), distributed / JDFI_PER_ETH);
    _mint(address(pair), distributed);

    _feePool = payable(new FeePool(
      _jdfiStakingPool,
      _univ2StakingPool,
      _uniswapRouter,
      _uniswapPair
    ));

    // UNI-V2 has been minted, so price is available
    _priceCumulativeLast =  address(this) > _weth ? pair.price0CumulativeLast() : pair.price1CumulativeLast();
    _blockTimestampLast = UniswapV2OracleLibrary.currentBlockTimestamp();

    // unstake and burn (including fee accrued on unstaking)
    IJDFIStakingPool(_jdfiStakingPool).unstake(remaining);
    _burn(address(this), balanceOf(address(this)));
    _burn(_feePool, balanceOf(_feePool));

    // seed staking pools
    _mint(_feePool, REWARDS_SEED);
  }

  /**
   * @notice OpenZeppelin ERC20 hook: prevent transfers during liquidity event, update oracle price
   * @dev adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
   * @param from sender
   * @param to recipient
   * @param amount quantity transferred
   */
  function _beforeTokenTransfer (address from, address to, uint amount) override internal {
    require(!_liquidityEventOpen, 'JusDeFi: liquidity event still in progress');
    super._beforeTokenTransfer(from, to, amount);

    address pair = _uniswapPair;

    if (from == pair || (to == pair && from != address(0))) {
      (
        uint price0Cumulative,
        uint price1Cumulative,
        uint32 blockTimestamp
      ) = UniswapV2OracleLibrary.currentCumulativePrices(pair);

      uint32 timeElapsed = blockTimestamp - _blockTimestampLast; // overflow is desired

      // only store the ETH -> JDFI price
      uint priceCumulative = address(this) > _weth ? price0Cumulative : price1Cumulative;

      if (timeElapsed >= ORACLE_PERIOD) {
        // overflow is desired, casting never truncates
        // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
        _priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - _priceCumulativeLast) / timeElapsed));

        _priceCumulativeLast = priceCumulative;
        _blockTimestampLast = blockTimestamp;
      }
    }
  }
}

// File: @uniswap/lib/contracts/libraries/FixedPoint.sol



pragma solidity >=0.4.0;

// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
    // range: [0, 2**112 - 1]
    // resolution: 1 / 2**112
    struct uq112x112 {
        uint224 _x;
    }

    // range: [0, 2**144 - 1]
    // resolution: 1 / 2**112
    struct uq144x112 {
        uint _x;
    }

    uint8 private constant RESOLUTION = 112;

    // encode a uint112 as a UQ112x112
    function encode(uint112 x) internal pure returns (uq112x112 memory) {
        return uq112x112(uint224(x) << RESOLUTION);
    }

    // encodes a uint144 as a UQ144x112
    function encode144(uint144 x) internal pure returns (uq144x112 memory) {
        return uq144x112(uint256(x) << RESOLUTION);
    }

    // divide a UQ112x112 by a uint112, returning a UQ112x112
    function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
        require(x != 0, 'FixedPoint: DIV_BY_ZERO');
        return uq112x112(self._x / uint224(x));
    }

    // multiply a UQ112x112 by a uint, returning a UQ144x112
    // reverts on overflow
    function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
        uint z;
        require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
        return uq144x112(z);
    }

    // returns a UQ112x112 which represents the ratio of the numerator to the denominator
    // equivalent to encode(numerator).div(denominator)
    function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
        require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
        return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
    }

    // decode a UQ112x112 into a uint112 by truncating after the radix point
    function decode(uq112x112 memory self) internal pure returns (uint112) {
        return uint112(self._x >> RESOLUTION);
    }

    // decode a UQ144x112 into a uint144 by truncating after the radix point
    function decode144(uq144x112 memory self) internal pure returns (uint144) {
        return uint144(self._x >> RESOLUTION);
    }
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IWETH.sol



pragma solidity >=0.5.0;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}

// File: @uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol



pragma solidity >=0.5.0;

import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';

// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
    using FixedPoint for *;

    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
    function currentBlockTimestamp() internal view returns (uint32) {
        return uint32(block.timestamp % 2 ** 32);
    }

    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
    function currentCumulativePrices(
        address pair
    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
        blockTimestamp = currentBlockTimestamp();
        price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
        price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();

        // if time has elapsed since the last update on the pair, mock the accumulated price values
        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
        if (blockTimestampLast != blockTimestamp) {
            // subtraction overflow is desired
            uint32 timeElapsed = blockTimestamp - blockTimestampLast;
            // addition overflow is desired
            // counterfactual
            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
            // counterfactual
            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
        }
    }
}

// File: contracts/interfaces/IJusDeFi.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

interface IJusDeFi is IERC20 {
  function consult (uint amount) external view returns (uint);
  function burn (uint amount) external;
  function burnAndTransfer (address account, uint amount) external;
  function _feePool () external view returns (address payable);
}

// File: contracts/FeePool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/math/Math.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';

import './interfaces/IJusDeFi.sol';
import './interfaces/IStakingPool.sol';

contract FeePool {
  address private immutable _jusdefi;

  address private immutable _uniswapRouter;
  address private immutable _uniswapPair;

  address public immutable _jdfiStakingPool;
  address public immutable _univ2StakingPool;

  // fee specified in basis points
  uint public _fee; // initialized at 0; not set until #liquidityEventClose
  uint private constant FEE_BASE = 1000;
  uint private constant BP_DIVISOR = 10000;

  // allow slippage of 0.6%
  uint private constant BUYBACK_SLIPPAGE = 60;

  uint private constant UNIV2_STAKING_MULTIPLIER = 3;

  uint private immutable _initialUniTotalSupply;

  uint public _votesIncrease;
  uint public _votesDecrease;

  uint private _lastBuybackAt;
  uint private _lastRebaseAt;

  constructor (
    address jdfiStakingPool,
    address univ2StakingPool,
    address uniswapRouter,
    address uniswapPair
  ) {
    _jusdefi = msg.sender;
    _jdfiStakingPool = jdfiStakingPool;
    _univ2StakingPool = univ2StakingPool;
    _uniswapRouter = uniswapRouter;
    _uniswapPair = uniswapPair;

    // approve router to handle UNI-V2 for buybacks
    IUniswapV2Pair(uniswapPair).approve(uniswapRouter, type(uint).max);

    _initialUniTotalSupply = IUniswapV2Pair(uniswapPair).mint(address(this)) + IUniswapV2Pair(uniswapPair).MINIMUM_LIQUIDITY();
    _fee = FEE_BASE;
  }

  receive () external payable {
    require(msg.sender == _uniswapRouter || msg.sender == _jdfiStakingPool, 'JusDeFi: invalid ETH deposit');
  }

  /**
   * @notice calculate quantity of JDFI to withhold (burned and as rewards) on unstake
   * @param amount quantity untsaked
   * @return unt quantity withheld
   */
  function calculateWithholding (uint amount) external view returns (uint) {
    return amount * _fee / BP_DIVISOR;
  }

  /**
   * @notice vote for weekly fee changes by sending ETH
   * @param increase whether vote is to increase or decrease the fee
   */
  function vote (bool increase) external payable {
    if (increase) {
      _votesIncrease += msg.value;
    } else {
      _votesDecrease += msg.value;
    }
  }

  /**
   * @notice withdraw Uniswap liquidity in excess of initial amount, purchase and burn JDFI
   */
  function buyback () external {
    require(block.timestamp / (1 days) % 7 == 1, 'JusDeFi: buyback must take place on Friday (UTC)');
    require(block.timestamp - _lastBuybackAt > 1 days, 'JusDeFi: buyback already called this week');
    _lastBuybackAt = block.timestamp;

    address[] memory path = new address[](2);
    path[0] = IUniswapV2Router02(_uniswapRouter).WETH();
    path[1] = _jusdefi;

    // check output to fail fast if price has changed beyond allowed limits

    uint[] memory outputs = IUniswapV2Router02(_uniswapRouter).getAmountsOut(
      1e9,
      path
    );

    uint requiredOutput = IJusDeFi(_jusdefi).consult(1e9);

    require(outputs[1] * (BP_DIVISOR + BUYBACK_SLIPPAGE) / BP_DIVISOR  >= requiredOutput, 'JusDeFi: buyback price slippage too high');

    uint initialBalance = IJusDeFi(_jusdefi).balanceOf(address(this));

    // remove liquidity in excess of original amount

    uint initialUniTotalSupply = _initialUniTotalSupply;
    uint uniTotalSupply = IUniswapV2Pair(_uniswapPair).totalSupply();

    if (uniTotalSupply > initialUniTotalSupply) {
      uint delta = Math.min(
        IUniswapV2Pair(_uniswapPair).balanceOf(address(this)),
        uniTotalSupply - initialUniTotalSupply
      );

      if (delta > 0) {
        // minimum output not relevant due to earlier check
        IUniswapV2Router02(_uniswapRouter).removeLiquidityETH(
          _jusdefi,
          delta,
          0,
          0,
          address(this),
          block.timestamp
        );
      }
    }

    // buyback JDFI using ETH from withdrawn liquidity and fee votes

    if (address(this).balance > 0) {
      // minimum output not relevant due to earlier check
      IUniswapV2Router02(_uniswapRouter).swapExactETHForTokens{
        value: address(this).balance
      }(
        0,
        path,
        address(this),
        block.timestamp
      );
    }

    IJusDeFi(_jusdefi).burn(IJusDeFi(_jusdefi).balanceOf(address(this)) - initialBalance);
  }

  /**
   * @notice distribute collected fees to staking pools
   */
  function rebase () external {
    require(block.timestamp / (1 days) % 7 == 3, 'JusDeFi: rebase must take place on Sunday (UTC)');
    require(block.timestamp - _lastRebaseAt > 1 days, 'JusDeFi: rebase already called this week');
    _lastRebaseAt = block.timestamp;

    // skim to prevent manipulation of JDFI reserve
    IUniswapV2Pair(_uniswapPair).skim(address(this));
    uint rewards = IJusDeFi(_jusdefi).balanceOf(address(this));

    uint jdfiStakingPoolStaked = IERC20(_jdfiStakingPool).totalSupply();
    uint univ2StakingPoolStaked = IJusDeFi(_jusdefi).balanceOf(_uniswapPair) * IERC20(_univ2StakingPool).totalSupply() / IUniswapV2Pair(_uniswapPair).totalSupply();

    uint weight = jdfiStakingPoolStaked + univ2StakingPoolStaked * UNIV2_STAKING_MULTIPLIER;

    // if weight is zero, staked amounts are also zero, avoiding zero-division error

    if (jdfiStakingPoolStaked > 0) {
      IStakingPool(_jdfiStakingPool).distributeRewards(
        rewards * jdfiStakingPoolStaked / weight
      );
    }

    if (univ2StakingPoolStaked > 0) {
      IStakingPool(_univ2StakingPool).distributeRewards(
        rewards * univ2StakingPoolStaked * UNIV2_STAKING_MULTIPLIER / weight
      );
    }

    // set fee for the next week

    uint increase = _votesIncrease;
    uint decrease = _votesDecrease;

    if (increase > decrease) {
      _fee = FEE_BASE + _sigmoid(increase - decrease);
    } else if (increase < decrease) {
      _fee = FEE_BASE - _sigmoid(decrease - increase);
    } else {
      _fee = FEE_BASE;
    }

    _votesIncrease = 0;
    _votesDecrease = 0;
  }

  /**
   * @notice calculate fee offset based on net votes
   * @dev input is a uint, therefore sigmoid is only implemented for positive values
   * @return uint fee offset from FEE_BASE
   */
  function _sigmoid (uint net) private pure returns (uint) {
    return FEE_BASE * net / (3 ether + net);
  }
}

// File: contracts/DevStakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import './StakingPool.sol';

contract DevStakingPool is StakingPool {
  address private immutable _weth;

  constructor (address weth) ERC20('JDFI ETH Fund', 'JDFI/E') {
    _weth = weth;
    _ignoreWhitelist();
    _mint(msg.sender, 10000 ether);
  }

  /**
   * @notice withdraw earned WETH rewards
   */
  function withdraw () external {
    IERC20(_weth).transfer(msg.sender, rewardsOf(msg.sender));
    _clearRewards(msg.sender);
  }

  /**
   * @notice distribute rewards to stakers
   * @param amount quantity to distribute
   */
  function distributeRewards (uint amount) override external {
    IERC20(_weth).transferFrom(msg.sender, address(this), amount);
    _distributeRewards(amount);
  }
}

// File: contracts/JDFIStakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IWETH.sol';

import './interfaces/IJusDeFi.sol';
import './interfaces/IJDFIStakingPool.sol';
import './StakingPool.sol';

contract JDFIStakingPool is IJDFIStakingPool, StakingPool {
  using Address for address payable;

  address private immutable _jusdefi;
  // _airdropToken cannot be immutable because it is referenced in _beforeTokenTransfer
  address private _airdropToken;
  address private immutable _weth;
  address private immutable _devStakingPool;

  mapping (address => uint) private _lockedBalances;

  uint private constant JDFI_PER_ETH = 4;

  constructor (
    address airdropToken,
    uint initialSupply,
    address weth,
    address devStakingPool
  ) ERC20('Staked JDFI', 'JDFI/S') {
    _jusdefi = msg.sender;
    _airdropToken = airdropToken;
    _weth = weth;
    _devStakingPool = devStakingPool;

    _addToWhitelist(airdropToken);
    _addToWhitelist(msg.sender);

    // initialSupply is minted before receipt of JDFI; see JusDeFi constructor
    _mint(msg.sender, initialSupply);

    // approve devStakingPool to spend WETH
    IERC20(weth).approve(devStakingPool, type(uint).max);
  }

  /**
   * @notice query locked balance of an address
   * @param account address to query
   * @return uint locked balance of account
   */
  function lockedBalanceOf (address account) public view returns (uint) {
    return _lockedBalances[account];
  }

  /**
   * @notice stake earned rewards without incurring burns
   */
  function compound () external {
    uint amount = rewardsOf(msg.sender);
    _clearRewards(msg.sender);
    _mint(msg.sender, amount);
  }

  /**
   * @notice deposit and stake JDFI
   * @param amount quantity of JDFI to stake
   */
  function stake (uint amount) override external {
    IJusDeFi(_jusdefi).transferFrom(msg.sender, address(this), amount);
    _mint(msg.sender, amount);
  }

  /**
   * @notice unstake and withdraw JDFI
   * @param amount quantity of tokens to unstake
   */
  function unstake (uint amount) override external {
    _burn(msg.sender, amount);
    IJusDeFi(_jusdefi).burnAndTransfer(msg.sender, amount);
  }

  /**
   * @notice withdraw earned JDFI rewards
   */
  function withdraw () external {
    IJusDeFi(_jusdefi).burnAndTransfer(msg.sender, rewardsOf(msg.sender));
    _clearRewards(msg.sender);
  }

  /**
   * @notice deposit ETH to free locked token balance, at a rate of 1:4
   */
  function unlock () external payable {
    // fee pool address not available at deployment time, so fetch dynamically
    address payable feePool = IJusDeFi(_jusdefi)._feePool();
    require(feePool != address(0), 'JusDeFi: liquidity event still in progress');

    uint amount = msg.value * JDFI_PER_ETH;
    require(_lockedBalances[msg.sender] >= amount, 'JusDeFi: insufficient locked balance');
    _lockedBalances[msg.sender] -= amount;

    uint dev = msg.value / 2;

    // staking pool contract designed to work with ERC20, so convert to WETH
    IWETH(_weth).deposit{ value: dev }();
    IStakingPool(_devStakingPool).distributeRewards(dev);

    feePool.sendValue(address(this).balance);
  }

  /**
   * @notice distribute rewards to stakers
   * @param amount quantity to distribute
   */
  function distributeRewards (uint amount) override external {
    IJusDeFi(_jusdefi).transferFrom(msg.sender, address(this), amount);
    _distributeRewards(amount);
  }

  /**
   * @notice OpenZeppelin ERC20 hook: prevent transfer of locked tokens
   * @param from sender
   * @param to recipient
   * @param amount quantity transferred
   */
  function _beforeTokenTransfer (address from, address to, uint amount) override internal {
    super._beforeTokenTransfer(from, to, amount);

    uint locked = lockedBalanceOf(from);

    require(
      locked == 0 || balanceOf(from) - locked >= amount,
      'JusDeFi: amount exceeds unlocked balance'
    );

    if (from == _airdropToken) {
      _lockedBalances[to] += amount;
    }
  }
}

// File: contracts/UNIV2StakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';

import './interfaces/IJusDeFi.sol';
import './StakingPool.sol';

contract UNIV2StakingPool is StakingPool {
  using Address for address payable;

  address private immutable _jusdefi;
  address private immutable _uniswapPair;
  address private immutable _uniswapRouter;

  constructor (
    address uniswapPair,
    address uniswapRouter
  )
    ERC20('Staked JDFI/WETH UNI-V2', 'JDFI-WETH-UNI-V2/S')
  {
    _jusdefi = msg.sender;
    _uniswapPair = uniswapPair;
    _uniswapRouter = uniswapRouter;

    IERC20(uniswapPair).approve(uniswapRouter, type(uint).max);

    _addToWhitelist(msg.sender);
  }

  receive () external payable {
    require(msg.sender == _uniswapRouter, 'JusDeFi: invalid ETH deposit');
  }

  /**
   * @notice deposit earned JDFI and sent ETH to Uniswap and stake without incurring burns
   * @param amountETHMin minimum quantity of ETH to stake, despite price depreciation
   */
  function compound (uint amountETHMin) external payable {
    uint rewards = rewardsOf(msg.sender);
    _clearRewards(msg.sender);

    (
      ,
      uint amountETH,
      uint liquidity
    ) = IUniswapV2Router02(_uniswapRouter).addLiquidityETH{
      value: msg.value
    }(
      _jusdefi,
      rewards,
      rewards,
      amountETHMin,
      address(this),
      block.timestamp
    );

    // return remaining ETH to sender
    msg.sender.sendValue(msg.value - amountETH);

    _mint(msg.sender, liquidity);
  }

  /**
   * @notice deposit and stake preexisting Uniswap liquidity tokens
   * @param amount quantity of Uniswap liquidity tokens to stake
   */
  function stake (uint amount) external {
    IERC20(_uniswapPair).transferFrom(msg.sender, address(this), amount);
    _mint(msg.sender, amount);
  }

  /**
   * @notice deposit JDFI and ETH to Uniswap and stake
   * @dev params passed directly to IUniswapV2Router02#addLiquidityETH
   * @param amountJDFIDesired quantity of JDFI to stake if price depreciates
   * @param amountJDFIMin minimum quantity of JDFI to stake, despite price appreciation
   * @param amountETHMin minimum quantity of ETH to stake, despite price depreciation
   */
  function stake (
    uint amountJDFIDesired,
    uint amountJDFIMin,
    uint amountETHMin
  ) external payable {
    IERC20(_jusdefi).transferFrom(msg.sender, address(this), amountJDFIDesired);

    // prevent possible theft of rounding error
    require(amountJDFIDesired >= amountJDFIMin, 'JusDeFi: minimum JDFI must not exceed desired JDFI');
    require(msg.value >= amountETHMin, 'JusDeFi: minimum ETH must not exceed message value');

    (
      uint amountJDFI,
      uint amountETH,
      uint liquidity
    ) = IUniswapV2Router02(_uniswapRouter).addLiquidityETH{
      value: msg.value
    }(
      _jusdefi,
      amountJDFIDesired,
      amountJDFIMin,
      amountETHMin,
      address(this),
      block.timestamp
    );

    // return remaining JDFI and ETH to sender
    IERC20(_jusdefi).transfer(msg.sender, amountJDFIDesired - amountJDFI);
    msg.sender.sendValue(msg.value - amountETH);

    _mint(msg.sender, liquidity);
  }

  /**
   * @notice remove Uniswap liquidity and withdraw and unstake underlying JDFI and ETH
   * @param amount quantity of tokens to unstake
   * @param amountJDFIMin minimum quantity of JDFI to unstake, despite price appreciate
   * @param amountETHMin minimum quantity of ETH to unstake, despite price depreciation
   */
  function unstake (
    uint amount,
    uint amountJDFIMin,
    uint amountETHMin
  ) external {
    _burn(msg.sender, amount);

    (
      uint amountJDFI,
      uint amountETH
    ) = IUniswapV2Router02(_uniswapRouter).removeLiquidityETH(
      _jusdefi,
      amount,
      amountJDFIMin,
      amountETHMin,
      address(this),
      block.timestamp
    );

    IJusDeFi(_jusdefi).burnAndTransfer(msg.sender, amountJDFI);
    msg.sender.sendValue(amountETH);
  }

  /**
   * @notice withdraw earned JDFI rewards
   */
  function withdraw () external {
    IJusDeFi(_jusdefi).burnAndTransfer(msg.sender, rewardsOf(msg.sender));
    _clearRewards(msg.sender);
  }

  /**
   * @notice distribute rewards to stakers
   * @param amount quantity to distribute
   */
  function distributeRewards (uint amount) override external {
    IJusDeFi(_jusdefi).transferFrom(msg.sender, address(this), amount);
    _distributeRewards(amount);
  }
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

// File: @openzeppelin/contracts/math/Math.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

// File: contracts/StakingPool.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

import './interfaces/IStakingPool.sol';

abstract contract StakingPool is IStakingPool, ERC20 {
  uint private constant REWARD_SCALAR = 1e18;

  // values scaled by REWARD_SCALAR
  uint private _cumulativeRewardPerToken;
  mapping (address => uint) private _rewardsExcluded;
  mapping (address => uint) private _rewardsReserved;

  mapping (address => bool) private _transferWhitelist;
  bool private _skipWhitelist;

  /**
   * @notice get rewards of given account available for withdrawal
   * @param account owner of rewards
   * @return uint quantity of rewards available
   */
  function rewardsOf (address account) public view returns (uint) {
    return (
      balanceOf(account) * _cumulativeRewardPerToken
      + _rewardsReserved[account]
      - _rewardsExcluded[account]
    ) / REWARD_SCALAR;
  }

  /**
   * @notice distribute rewards proportionally to stake holders
   * @param amount quantity of rewards to distribute
   */
  function _distributeRewards (uint amount) internal {
    uint supply = totalSupply();
    require(supply > 0, 'StakingPool: supply must be greater than zero');
    _cumulativeRewardPerToken += amount * REWARD_SCALAR / supply;
  }

  /**
   * @notice remove pending rewards associated with account
   * @param account owner of rewards
   */
  function _clearRewards (address account) internal {
    _rewardsExcluded[account] = balanceOf(account) * _cumulativeRewardPerToken;
    delete _rewardsReserved[account];
  }

  /**
   * @notice add address to transfer whitelist to allow it to execute transfers
   * @param account address to add to whitelist
   */
  function _addToWhitelist (address account) internal {
    _transferWhitelist[account] = true;
  }

  /**
   * @notice disregard transfer whitelist
   */
  function _ignoreWhitelist () internal {
    _skipWhitelist = true;
  }

  /**
   * @notice OpenZeppelin ERC20 hook: prevent manual transfers, maintain reward distribution when tokens are transferred
   * @param from sender
   * @param to recipient
   * @param amount quantity transferred
   */
  function _beforeTokenTransfer (address from, address to, uint amount) virtual override internal {
    super._beforeTokenTransfer(from, to, amount);

    if (from != address(0) && to != address(0)) {
      require(_transferWhitelist[msg.sender] || _skipWhitelist, 'JusDeFi: staked tokens are non-transferrable');
    }

    uint delta = amount * _cumulativeRewardPerToken;

    if (from != address(0)) {
      uint excluded = balanceOf(from) * _cumulativeRewardPerToken;
      _rewardsReserved[from] += excluded - _rewardsExcluded[from];
      _rewardsExcluded[from] = excluded - delta;
    }

    if (to != address(0)) {
      _rewardsExcluded[to] += delta;
    }
  }
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: contracts/test/JusDeFiMock.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '../JusDeFi.sol';
import '../interfaces/IStakingPool.sol';

contract JusDeFiMock is JusDeFi {
  constructor (address airdropToken, address uniswapRouter) JusDeFi(airdropToken, uniswapRouter) {}

  function mint (address account, uint amount) external {
    _mint(account, amount);
  }

  function distributeJDFIStakingPoolRewards (uint amount) external {
    _mint(address(this), amount);
    IStakingPool(_jdfiStakingPool).distributeRewards(amount);
  }

  function distributeUNIV2StakingPoolRewards (uint amount) external {
    _mint(address(this), amount);
    IStakingPool(_univ2StakingPool).distributeRewards(amount);
  }
}

// File: contracts/test/StakingPoolMock.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.7.4;

import '../StakingPool.sol';

contract StakingPoolMock is StakingPool {
  constructor () ERC20('', '') {}

  function mint (address account, uint amount) external {
    _mint(account, amount);
  }

  // override needed for IStakingPool interface
  function distributeRewards (uint amount) override external {
    _distributeRewards(amount);
  }

  function clearRewards (address account) external {
    _clearRewards(account);
  }

  function addToWhitelist (address account) external {
    _addToWhitelist(account);
  }

  function ignoreWhitelist () external {
    _ignoreWhitelist();
  }
}