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



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, 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/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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

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

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

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

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

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

// File: @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: @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: @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: contracts/interfaces/IAccessControl.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface IAccessControl {
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
    function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
    function hasRole(bytes32 role, address account) external view returns (bool);
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);
    function getRoleAdmin(bytes32 role) external view returns (bytes32);
    function grantRole(bytes32 role, address account) external;
    function revokeRole(bytes32 role, address account) external;
    function renounceRole(bytes32 role, address account) external;
}

// File: contracts/interfaces/IAddressRegistry.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface IAddressRegistry {
    event AvalancheUpdated(address indexed newAddress);
    event LGEUpdated(address indexed newAddress);
    event LodgeUpdated(address indexed newAddress);
    event LoyaltyUpdated(address indexed newAddress);
    event PwdrUpdated(address indexed newAddress);
    event PwdrPoolUpdated(address indexed newAddress);
    event SlopesUpdated(address indexed newAddress);
    event SnowPatrolUpdated(address indexed newAddress);
    event TreasuryUpdated(address indexed newAddress);
    event UniswapRouterUpdated(address indexed newAddress);
    event VaultUpdated(address indexed newAddress);
    event WethUpdated(address indexed newAddress);
    
    function getAvalanche() external view returns (address);
    function setAvalanche(address _address) external;

    function getLGE() external view returns (address);
    function setLGE(address _address) external;

    function getLodge() external view returns (address);
    function setLodge(address _address) external;

    function getLoyalty() external view returns (address);
    function setLoyalty(address _address) external;

    function getPwdr() external view returns (address);
    function setPwdr(address _address) external;

    function getPwdrPool() external view returns (address);
    function setPwdrPool(address _address) external;

    function getSlopes() external view returns (address);
    function setSlopes(address _address) external;

    function getSnowPatrol() external view returns (address);
    function setSnowPatrol(address _address) external;

    function getTreasury() external view returns (address payable);
    function setTreasury(address _address) external;

    function getUniswapRouter() external view returns (address);
    function setUniswapRouter(address _address) external;

    function getVault() external view returns (address);
    function setVault(address _address) external;

    function getWeth() external view returns (address);
    function setWeth(address _address) external;
}
// File: contracts/interfaces/IAvalanche.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface IAvalanche {
    event Activated(address indexed user);
    event Claim(address indexed user, uint256 pwdrAmount);    
    event Deposit(address indexed user, uint256 amount);
    event Withdraw(address indexed user, uint256 amount);
    event PwdrRewardAdded(address indexed user, uint256 pwdrReward);
    event EthRewardAdded(address indexed user, uint256 ethReward);

    function active() external view returns (bool);
    function activate() external;

    function addPwdrReward(address _from, uint256 _amount) external;
    // function addEthReward() external virtual payable;
    function deposit(uint256 _amount) external;
    function depositFor(address _from, address _user, uint256 _amount) external;
    function claim() external;
    function claimFor(address _user) external;
    function withdraw(uint256 _amount) external;

    function payoutNumber() external view returns (uint256);
    function timeUntilNextPayout() external view returns (uint256); 
    function rewardAtPayout(uint256 _payoutNumber) external view returns (uint256);
}
// File: contracts/interfaces/IPWDR.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface IPWDR {
    event EpochUpdated(address _address, uint256 _epoch, uint256 _phase);

    function MAX_SUPPLY() external view returns (uint256);
    function maxSupplyHit() external view returns (bool);
    function transferFee() external view returns (uint256);
    function currentEpoch() external view returns (uint256);
    function currentPhase() external view returns (uint256);
    function epochMaxSupply(uint _epoch) external view returns (uint256);
    function epochBaseRate(uint _epoch) external view returns (uint256);

    function accumulating() external view returns (bool);
    function currentMaxSupply() external view returns (uint256);
    function currentBaseRate() external view returns (uint256);
    // function incrementEpoch() external;
    // function incrementPhase() external;
    
    function updateEpoch(uint256 _epoch, uint256 _phase) external;
    function mint(address _to, uint256 _amount) external;
    function setTransferFee(uint256 _transferFee) external;
    function addToTransferWhitelist(bool _addToSenderWhitelist, address _address) external;
    function removeFromTransferWhitelist(bool _removeFromSenderWhitelist, address _address) external;
}

// File: contracts/interfaces/ISnowPatrol.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { AltitudeBase } from "../utils/AltitudeBase.sol";

interface ISnowPatrol {
    function ADMIN_ROLE() external pure returns (bytes32);
    function LGE_ROLE() external pure returns (bytes32);
    function PWDR_ROLE() external pure returns (bytes32);
    function SLOPES_ROLE() external pure returns (bytes32);
    function setCoreRoles() external;
}
// File: contracts/token/PWDR.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { IUniswapV2Factory } from '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import { IUniswapV2Router02 } from '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import { IPWDR } from "../interfaces/IPWDR.sol";
import { IAvalanche } from '../interfaces/IAvalanche.sol';
import { PWDRBase } from "./PWDRBase.sol";

contract PWDR is IPWDR, PWDRBase {
    event EpochUpdated(address _address, uint256 _epoch, uint256 _phase);

    uint256 public override constant MAX_SUPPLY = 21000000 * 1e18; // max supply 21M

    bool public override maxSupplyHit; // has max supply been reached
    uint256 public override transferFee; // PWDR transfer fee, 1 = 0.1%. Default 1.5%

    uint256 public override currentEpoch;
    uint256 public override currentPhase; // current phase; 0 = Accumulation ,1 = Distribution
    uint256[] public override epochMaxSupply; // max total supply for each epoch, running total
    uint256[] public override epochBaseRate; // base APR of Slope rewards
    
    // Mapping of whitelisted sender and recipient addresses that don't pay the transfer fee. 
    // Allows PWDR token holders to whitelist future contracts
    mapping(address => bool) public senderWhitelist;
    mapping(address => bool) public recipientWhitelist;

    modifier Accumulation {
        require(
            currentPhase == 0,
            "PWDR is not in Accumulation"
        );
        _;
    }
    
    modifier MaxSupplyNotReached {
        require(!maxSupplyHit, "Max PWDR Supply has been reached");
        _;
    }

    modifier OnlyAuthorized {
        require(
            msg.sender == avalancheAddress()
            || msg.sender == lgeAddress()
            || msg.sender == slopesAddress(),
            "Only LGE, Slopes, and Avalanche contracts can call this function"
        );
        _;
    }

    constructor(address addressRegistry) 
        public 
        PWDRBase(addressRegistry, "Altitude", "PWDR") 
    {
        transferFee = 15;
        _initializeEpochs();
    }

    function _initializeEpochs() 
        private 
    {
        _setupEpoch(5250000 * 1e18, 0); // 5.25M PWDR for LGE
        _setupEpoch(13250000 * 1e18, 800); // +8M PWDR, 800%
        _setupEpoch(17250000 * 1e18, 400); // +4M PWDR, 400%
        _setupEpoch(19250000 * 1e18, 200); // +2M PWDR, 200%
        _setupEpoch(20250000 * 1e18, 100); // +1M PWDR, 100%
        _setupEpoch(20750000 * 1e18, 50); // +500K PWDR, 50%
        _setupEpoch(21000000 * 1e18, 25); // +250K PWDR, 25%
    }

    function _setupEpoch(uint256 maxSupply, uint256 baseRate) 
        private 
    {
        epochMaxSupply.push(maxSupply);
        epochBaseRate.push(baseRate);
    }

    function currentMaxSupply() 
        external 
        view
        override 
        returns (uint256)
    {
        return epochMaxSupply[currentEpoch];
    }

    function currentBaseRate() 
        external 
        view 
        override
        returns (uint256)
    {
        return epochBaseRate[currentEpoch];
    }

    function accumulating()
        external
        view
        override
        returns (bool)
    {
        return currentEpoch > 0 && currentEpoch <= 6
            && currentPhase == 0;
    }

    function updateEpoch(uint256 _epoch, uint256 _phase)
        external
        override
        OnlyAuthorized
    {
        // require valid update calls
        if (currentPhase == 0) {
            require(
                _epoch == currentEpoch && _phase == 1,
                "Invalid Epoch Phase Update Call"
            );
        } else {
            // change this to _epoch == currentEpoch + 1 in prod
            require(
                _epoch > currentEpoch && _phase == 0,
                "Invalid Epoch Update Call"
            );
        }

        currentEpoch = _epoch;
        currentPhase = _phase;

        emit EpochUpdated(_msgSender(), _epoch, _phase);
    }

    // Creates `_amount` PWDR token to `_to`. 
    // Can only be called by the LGE, Slopes, and Avalanche contracts
    //  when epoch and max supply numbers allow
    function mint(address _to, uint256 _amount)
        external
        override
        Accumulation
        MaxSupplyNotReached
        OnlyAuthorized
    {
        uint256 supply = totalSupply();
        uint256 epochSupply = epochMaxSupply[currentEpoch];

        // update phase if epoch max supply is hit during this mint
        if (supply.add(_amount) >= epochSupply) {
            _amount = epochSupply.sub(supply);
            
            if (supply.add(_amount) >= MAX_SUPPLY) {
                maxSupplyHit = true;
            }

            // activate gets called at every accumulation end to reset rewards
            IAvalanche(avalancheAddress()).activate();            

            if (currentEpoch == 0) {
                currentEpoch += 1;
            } else {
                currentPhase += 1;
            }
            emit EpochUpdated(_msgSender(), currentEpoch, currentPhase);
        }

        if (_amount > 0) {
            _mint(_to, _amount);
        }
    }

    // Transfer override to support transfer fees that are sent to Avalanche
    function _transfer(
        address sender, 
        address recipient, 
        uint256 amount
    ) 
        internal
        override
    {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");
        uint256 transferFeeAmount;
        uint256 tokensToTransfer;
        if (amount > 0) {
            address avalancheAddress = avalancheAddress();

            // Send a fee to the Avalanche staking contract if this isn't a whitelisted transfer
            if (_isWhitelistedTransfer(sender, recipient) != true) {
                transferFeeAmount = amount.mul(transferFee).div(1000);
                _balances[avalancheAddress] = _balances[avalancheAddress].add(transferFeeAmount);
                IAvalanche(avalancheAddress).addPwdrReward(sender, transferFeeAmount);
                emit Transfer(sender, avalancheAddress, transferFeeAmount);
            }
            tokensToTransfer = amount.sub(transferFeeAmount);
            _balances[sender] = _balances[sender].sub(tokensToTransfer, "ERC20: transfer amount exceeds balance");

            if (tokensToTransfer > 0) {
                _balances[recipient] = _balances[recipient].add(tokensToTransfer);

                // If the Avalanche is the transfer recipient, add rewards to keep balances updated
                if (recipient == avalancheAddress) {
                    IAvalanche(avalancheAddress).addPwdrReward(sender, tokensToTransfer);
                }
            }

        }
        emit Transfer(sender, recipient, tokensToTransfer);
    }

    // Admin calls this at token deployment to setup PWDR-LP LGE transfers
    function calculateUniswapPoolAddress() 
        external
        view 
        HasPatrol("ADMIN")
        returns (address)
    {
        address uniswapRouter = uniswapRouterAddress();
        address wethAddress = wethAddress();

        // Calculate the address the PWDR-ETH Uniswap pool will exist at
        address factoryAddress = IUniswapV2Router02(uniswapRouter).factory();
        // return IUniswapV2Factory(factoryAddress).createPair(wethAddress, address(this));

        // token0 must be strictly less than token1 by sort order to determine the correct address
        (address token0, address token1) = address(this) < wethAddress 
            ? (address(this), wethAddress) 
            : (wethAddress, address(this));

        //uniswap address pre-calculation using create2
        return address(uint(keccak256(abi.encodePacked(
            hex'ff',
            factoryAddress,
            keccak256(abi.encodePacked(token0, token1)),
            hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
        ))));
    }

    // Sets the PWDR transfer fee that gets rewarded to Avalanche stakers. Can't be higher than 5%.
    function setTransferFee(uint256 _transferFee) 
        public
        override
        HasPatrol("ADMIN")
    {
        require(_transferFee <= 50, "over 5%");
        transferFee = _transferFee;
    }

    // Add an address to the sender or recipient transfer whitelist
    function addToTransferWhitelist(bool _addToSenderWhitelist, address _address) 
        public
        override 
        HasPatrol("ADMIN") 
    {
        if (_addToSenderWhitelist == true) {
            senderWhitelist[_address] = true;
        } else {
            recipientWhitelist[_address] = true;
        }
    }

    // Remove an address from the sender or recipient transfer whitelist
    function removeFromTransferWhitelist(bool _removeFromSenderWhitelist, address _address) 
        public
        override
        HasPatrol("ADMIN") 
    {
        if (_removeFromSenderWhitelist == true) {
            senderWhitelist[_address] = false;
        } else  {
            recipientWhitelist[_address] = false;
        }
    }

    // Internal function to determine if a PWDR transfer is being sent or received by a whitelisted address
    function _isWhitelistedTransfer(
        address _sender, 
        address _recipient
    ) 
        internal 
        view 
        returns (bool) 
    {
        // Ecosytem contracts should not pay transfer fees
        return _sender == avalancheAddress() || _recipient == avalancheAddress()
            || _sender == lgeAddress() || _recipient == lgeAddress()
            || _sender == slopesAddress() || _recipient == slopesAddress()
            || senderWhitelist[_sender] == true || recipientWhitelist[_recipient] == true;
    }
}

// File: contracts/token/PWDRBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

// import { ERC20 } from "../utils/ERC20/ERC20.sol";

import { PWDRToken } from "./PWDRToken.sol";
import { PatrolBase } from "../utils/PatrolBase.sol";

abstract contract PWDRBase is PatrolBase, PWDRToken {
    constructor(
        address addressRegistry,
        string memory name_, 
        string memory symbol_
    ) 
        public
        PWDRToken(name_, symbol_)
    {
        _setAddressRegistry(addressRegistry);
    }
}
// File: contracts/token/PWDRToken.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

// import { ERC20 } from "../utils/ERC20/ERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import { Context } from "@openzeppelin/contracts/GSN/Context.sol";

// Standed ERC20 with internal _balances, virtual _transfer, and add'l helper funcs
// Modificiations made out of ecosystem necessity  
abstract contract PWDRToken is IERC20, Context {
    using SafeMath for uint256;

    mapping (address => uint256) internal _balances;
    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    constructor (string memory name_, string memory symbol_) public {
        _name = name_;
        _symbol = symbol_;
        _decimals = 18;
    }

    function name() public view returns (string memory) {
        return _name;
    }

    function symbol() public view returns (string memory) {
        return _symbol;
    }

    function decimals() public view returns (uint8) {
        return _decimals;
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, 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) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    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;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    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;
    }

    function _transfer(address sender, address recipient, uint256 amount) internal virtual;

    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);
    }

    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);
    }

    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 _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

// File: contracts/utils/AddressBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { IAddressRegistry } from "../interfaces/IAddressRegistry.sol";
import { UtilitiesBase } from "./UtilitiesBase.sol";

abstract contract AddressBase is UtilitiesBase {
    address internal _addressRegistry;

    function _setAddressRegistry(address _address)
        internal
    {
        _addressRegistry = _address;
    }
}
// File: contracts/utils/AltitudeBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { IAddressRegistry } from "../interfaces/IAddressRegistry.sol";
import { ISnowPatrol } from "../interfaces/ISnowPatrol.sol";
import { AddressBase } from "./AddressBase.sol";

abstract contract AltitudeBase is AddressBase {
    modifier OnlyLGE {
        require(
            _msgSender() == lgeAddress(), 
            "Only the LGE contract can call this function"
        );
        _;
    }

    modifier OnlyLoyalty {
        require(
            _msgSender() == loyaltyAddress(), 
            "Only the Loyalty contract can call this function"
        );
        _;
    }

    modifier OnlyPWDR {
        require(
            _msgSender() == pwdrAddress(),
            "Only PWDR Contract can call this function"
        );
        _;
    }

    modifier OnlySlopes {
        require(
            _msgSender() == slopesAddress(), 
            "Only the Slopes contract can call this function"
        );
        _;
    }

    function avalancheAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getAvalanche();
    }

    function lgeAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getLGE();
    }

    function lodgeAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getLodge();
    }

    function loyaltyAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getLoyalty();
    }

    function pwdrAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getPwdr();
    }

    function pwdrPoolAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getPwdrPool();
    }

    function slopesAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getSlopes();
    }

    function snowPatrolAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getSnowPatrol();
    }

    function treasuryAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getTreasury();
    }

    function uniswapRouterAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getUniswapRouter();
    }

    function vaultAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getVault();
    }

    function wethAddress() internal view returns (address) {
        return IAddressRegistry(_addressRegistry).getWeth();
    }
}
// File: contracts/utils/PatrolBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { AltitudeBase } from "./AltitudeBase.sol";
import { IAddressRegistry } from "../interfaces/IAddressRegistry.sol";
import { IAccessControl } from "../interfaces/IAccessControl.sol";

contract PatrolBase is AltitudeBase {
    modifier HasPatrol(bytes memory _patrol) {
        require(
            IAccessControl(snowPatrolAddress()).hasRole(keccak256(_patrol), address(_msgSender())),
            "Account does not have sufficient role to call this function"
        );
        _;
    }

    function hasPatrol(bytes memory _patrol, address _address)
        internal
        view
        returns (bool)
    {
        return IAccessControl(snowPatrolAddress()).hasRole(keccak256(_patrol), _address);
    }
}
// File: contracts/utils/UtilitiesBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Context } from "@openzeppelin/contracts/GSN/Context.sol";

abstract contract UtilitiesBase is Context {
    modifier NonZeroAmount(uint256 _amount) {
        require(
            _amount > 0, 
            "Amount must be greater than zero"
        );
        _;
    }

    modifier NonZeroTokenBalance(address _address) {
        require(
            IERC20(_address).balanceOf(address(this)) > 0,
            "No tokens to transfer"
        );
        _;
    }

    modifier NonZeroETHBalance(address _address) {
        require(
            address(this).balance > 0,
            "No ETH to transfer"
        );
        _;
    }

    modifier OnlyOrigin {
        require(
            tx.origin == address(this), 
            "Only origin contract can call this function"
        );
        _;
    }
}