// 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/introspection/IERC165.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @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/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "../../introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "../../introspection/IERC165.sol";

/**
 * _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {

    /**
        @dev Handles the receipt of a single ERC1155 token type. This function is
        called at the end of a `safeTransferFrom` after the balance has been updated.
        To accept the transfer, this must return
        `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
        (i.e. 0xf23a6e61, or its own function selector).
        @param operator The address which initiated the transfer (i.e. msg.sender)
        @param from The address which previously owned the token
        @param id The ID of the token being transferred
        @param value The amount of tokens being transferred
        @param data Additional data with no specified format
        @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
    */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    )
        external
        returns(bytes4);

    /**
        @dev Handles the receipt of a multiple ERC1155 token types. This function
        is called at the end of a `safeBatchTransferFrom` after the balances have
        been updated. To accept the transfer(s), this must return
        `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
        (i.e. 0xbc197c81, or its own function selector).
        @param operator The address which initiated the batch transfer (i.e. msg.sender)
        @param from The address which previously owned the token
        @param ids An array containing ids of each token being transferred (order and length must match values array)
        @param values An array containing amounts of each token being transferred (order and length must match ids array)
        @param data Additional data with no specified format
        @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
    */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    )
        external
        returns(bytes4);
}

// 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: 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/ILodge.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface ILodge {
    event TokenCreated(address user, uint256 id, uint256 supply);

    function items(uint256 _token) external view returns(uint256);
    function boost(uint256 _id) external view returns (uint256);

    function setURI(string memory _newuri) external;
    function mint(address _account, uint256 _id, uint256 _amount, uint256 _boost) external;
}

// File: contracts/interfaces/ILoyalty.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface ILoyalty {
    event TrancheUpdated(uint256 _tranche, uint256 _points);
    event LoyaltyUpdated(address indexed _user, uint256 _tranche, uint256 _points);
    event BaseFeeUpdated(address indexed _user, uint256 _baseFee);
    event ProtocolFeeUpdated(address indexed _user, uint256 _protocolFee);
    event DiscountMultiplierUpdated(address indexed _user, uint256 _multiplier);
    event Deposit(address indexed _user, uint256 _id, uint256 _amount);
    event Withdraw(address indexed _user, uint256 _id, uint256 _amount);
    
    function staked(uint256 _id, address _address) external view returns (uint256);
    function whitelistedTokens(uint256 _id) external view returns (bool);

    function getTotalShares(address _user, uint256 _amount) external view returns (uint256);
    function getTotalFee(address _user, uint256 _amount) external view returns (uint256);
    function getProtocolFee(uint256 _amount) external view returns (uint256);
    function getBoost(address _user) external view returns (uint256);
    function deposit(uint256 _id, uint256 _amount) external;
    function withdraw(uint256 _id, uint256 _amount) external;
    function whitelistToken(uint256 _id) external;
    function blacklistToken(uint256 _id) external;
    function updatePoints(address _user) external;
}
// File: contracts/interfaces/ISlopes.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

interface ISlopes {
    event Activated(address user);
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Claim(address indexed user, uint256 indexed pid, uint256 pwdrAmount, uint256 tokenAmount);
    event ClaimAll(address indexed user, uint256 pwdrAmount, uint256[] tokenAmounts);
    event Migrate(address indexed user, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    // event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event PwdrPurchase(address indexed user, uint256 ethSpentOnPwdr, uint256 pwdrBought);

    function active() external view returns (bool);
    function pwdrSentToAvalanche() external view returns (uint256);
    function stakingFee() external view returns (uint256);
    function roundRobinFee() external view returns (uint256);
    function protocolFee() external view returns (uint256);

    function activate() external;
    function massUpdatePools() external;
    function updatePool(uint256 _pid) external;
    // function addPwdrReward(address _from, uint256 _amount) external virtual;
    // function addEthReward() external virtual payable;
    function claim(uint256 _pid) external;
    function claimAll() external;
    function claimAllFor(address _user) external;
    function deposit(uint256 _pid, uint256 _amount) external;
    function withdraw(uint256 _pid, uint256 _amount) external;
    function migrate() external;
    function poolLength() external view returns (uint256);
    function addPool(address _token, address _lpToken, bool _lpStaked, uint256 _weight) external;
    function setWeight(uint256 _pid, uint256 _weight) external;
}

// interface ISlopes {
    

//     function activate() external;
//     function poolLength() external view returns (uint256);
//     function massUpdatePools() external;
//     function updatePool(uint256 _pid) external;
//     function deposit(uint256 _pid, uint256 _amount) 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/loyalty/Loyalty.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { ILoyalty } from "../interfaces/ILoyalty.sol";
import { ILodge } from "../interfaces/ILodge.sol";
import { ISlopes } from "../interfaces/ISlopes.sol";
import { IAvalanche } from "../interfaces/IAvalanche.sol";
import { LoyaltyBase } from "./LoyaltyBase.sol";

// contract to manage all bonuses
contract Loyalty is ILoyalty, IERC1155Receiver, LoyaltyBase {
    event TrancheUpdated(uint256 _tranche, uint256 _points);
    event LoyaltyUpdated(address indexed _user, uint256 _tranche, uint256 _points);
    event BaseFeeUpdated(address indexed _user, uint256 _baseFee);
    event ProtocolFeeUpdated(address indexed _user, uint256 _protocolFee);
    event DiscountMultiplierUpdated(address indexed _user, uint256 _multiplier);
    event Deposit(address indexed _user, uint256 _id, uint256 _amount);
    event Withdraw(address indexed _user, uint256 _id, uint256 _amount);

    struct LoyaltyInfo {
        uint256 points;
        uint256 tranche;
        uint256 boost; // current boosts, 1 = 0.1%
        uint256 staked; // id+1 of staked nft
    }

    uint256[] public tokenIds;
    uint256 public baseFee; // default 0.08% 
    uint256 public protocolFee; // default 20% of 0.8%
    uint256 public discountMultiplier; // 0.01%

    mapping(uint256 => mapping(address => uint256)) public override staked;
    mapping(uint256 => bool) public override whitelistedTokens;
    mapping (uint256 => uint256) public loyaltyTranches; // Tranche level to points required
    mapping (address => LoyaltyInfo) public userLoyalty; // Address to loyalty points accrued

    modifier Whitelisted(uint256 _id) {
        require(whitelistedTokens[_id], "This Lodge token cannot be staked");
        _;
    }

    modifier OnlyOneBoost(address _user) {
        require(
            userLoyalty[_user].boost == 0,
            "Max one boost per account"
        );
        _;
    }

    constructor(address _address) 
        public
        LoyaltyBase(_address)
    {
        tokenIds = new uint256[](0);
        baseFee = 80; // 0.08%
        protocolFee = 20000; // 20% of baseFee
        discountMultiplier = 10; // 0.01%

        _initializeWhitelist();
        _initializeLoyaltyTranches();
    }

    function _initializeWhitelist() internal {
        whitelistedTokens[0] = true;
        whitelistedTokens[1] = true;
        whitelistedTokens[2] = true;

        tokenIds.push(0);
        tokenIds.push(1);
        tokenIds.push(2);
    }

     // set the base loyalty tranches, performing more flash loans unlocks
     // greater discounts
    function _initializeLoyaltyTranches() internal {
        _setLoyaltyTranche(0, 0); // base loyalty, base fee
        _setLoyaltyTranche(1, 100); // level 1, 100 tx
        _setLoyaltyTranche(2, 500);  // level 2, 500 tx
        _setLoyaltyTranche(3, 1000); // level 3, 1k tx
        _setLoyaltyTranche(4, 5000); // level 4, 5k tx
        _setLoyaltyTranche(5, 10000); // level 5, 10k tx
        _setLoyaltyTranche(6, 50000); // level 6, 50k tx
        _setLoyaltyTranche(7, 100000); // level 7, 100k tx, initially 0.01% fee + boost
    }

    function deposit(uint256 _id, uint256 _amount)
        external
        override
    {
        _deposit(_msgSender(), _id, _amount);
    }

    function _deposit(address _address, uint256 _id, uint256 _amount) 
        internal
        Whitelisted(_id)
        NonZeroAmount(_amount)
        OnlyOneBoost(_address)
    {
        IERC1155(lodgeAddress()).safeTransferFrom(_address, address(this), _id, _amount, "");
        staked[_id][_address] += _amount;
        userLoyalty[_address].boost = ILodge(lodgeAddress()).boost(_id);
        userLoyalty[_address].staked = _id + 1;

        ISlopes(slopesAddress()).claimAllFor(_address);
        IAvalanche(avalancheAddress()).claimFor(_address);

        emit Deposit(_address, _id, _amount);
    }

    function withdraw(uint256 _id, uint256 _amount) 
        external
        override
    {
        _withdraw(_msgSender(), _id, _amount);
    }

    function _withdraw(address _address, uint256 _id, uint256 _amount) 
        internal 
    {
        require(
            staked[_id][_address] >= _amount,
            "Staked balance not high enough to withdraw this amount" 
        );
        
        IERC1155(lodgeAddress()).safeTransferFrom(address(this), _address, _id, _amount, "");
        staked[_id][_address] -= _amount;
        userLoyalty[_address].boost = 0;
        userLoyalty[_address].staked = 0;

        // claim all user rewards and update user pool shares to prevent abuse
        ISlopes(slopesAddress()).claimAllFor(_address);
        IAvalanche(avalancheAddress()).claimFor(_address);

        emit Withdraw(_address, _id, _amount);
    }

    function whitelistToken(uint256 _id)
        external
        override
        HasPatrol("ADMIN")
    {
        whitelistedTokens[_id] = true;
        tokenIds.push(_id);
    }

    function blacklistToken(uint256 _id)
        external
        override
        HasPatrol("ADMIN")
    {
        whitelistedTokens[_id] = false;
    }

    function getBoost(address _user)
        external
        override
        view
        returns (uint256)
    {
        return userLoyalty[_user].boost;
    }

    // get the total shares a user will receive when staking a given token amount
    function getTotalShares(address _user, uint256 _amount)
        external
        override
        view
        returns (uint256)
    {
        // 1 + [1 * (boost/1000)]
        return _amount.add(_amount.mul(userLoyalty[_user].boost).div(1000));
    }

    // get the total fee amount that an address will pay on a given flash loan amount
    // get base fee for user tranche, then flat discount based on boost
    function getTotalFee(address _user, uint256 _amount) 
        external 
        override
        view 
        returns (uint256)
    {
        uint256 feeMultiplier = baseFee.sub(discountMultiplier.mul(userLoyalty[_user].tranche));
        uint256 trancheFee = _amount.mul(feeMultiplier).div(100000);
        return trancheFee.sub(trancheFee.mul(userLoyalty[_user].boost).div(1000));
    }

    // protocol fee added for future use
    function getProtocolFee(uint256 _amount)
        external
        override
        view
        returns (uint256)
    {
        return _amount.mul(protocolFee).div(10000);
    }

    // update user points and tranche if needed
    function updatePoints(address _address) 
        external
        override
        OnlySlopes
    {
        userLoyalty[_address].points = userLoyalty[_address].points.add(1);
        if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche.add(1)]) {
            userLoyalty[_address].tranche = userLoyalty[_address].tranche.add(1);
        }
    }

    function updateTranche(address _address)
        public  
    {
        if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche + 1]) {
            userLoyalty[_address].tranche = userLoyalty[_address].tranche + 1;
        } else {
            if (userLoyalty[_address].tranche == 0) {
                return;
            }
            if (userLoyalty[_address].points < loyaltyTranches[userLoyalty[_address].tranche]) {
                userLoyalty[_address].tranche = userLoyalty[_address].tranche - 1;
            }
        }
    }

    function _getProtocolFee(uint256 _totalFee)
        internal
        view
        returns (uint256)
    {
        return _totalFee.mul(protocolFee).div(100000);
    }

    function setBaseFee(uint256 _newFee)
        external
        HasPatrol("ADMIN")
    {
        require(_newFee != baseFee, "No change");
        require(_newFee <= 90, "Base Fee must remain below 0.09%");

        baseFee = _newFee;
        emit BaseFeeUpdated(msg.sender, _newFee);
    }

    function setProtocolFee(
        uint256 _newFee
    )
        external
        HasPatrol("ADMIN")
    {
        require(_newFee != baseFee, "No change");

        protocolFee = _newFee;
        emit ProtocolFeeUpdated(msg.sender, _newFee);
    }

    function setLoyaltyTranche(
        uint256 _tranche, 
        uint256 _points
    )
        external
        HasPatrol("ADMIN")
    {
        _setLoyaltyTranche(_tranche, _points);
    }

    function _setLoyaltyTranche(
        uint256 _tranche, 
        uint256 _points
    )
        internal
    {
        loyaltyTranches[_tranche] = _points;
        emit TrancheUpdated(_tranche, _points);
    }

    function setDiscountMultiplier(uint256 _newMultiplier)
        external
        HasPatrol("ADMIN")
    {
        discountMultiplier = _newMultiplier;
        emit DiscountMultiplierUpdated(msg.sender, _newMultiplier);
    }

    function setLoyaltyPoints(
        address _address,
        uint256 _points
    )
        external
        HasPatrol("ADMIN")
    {
        userLoyalty[_address].points = _points;
        updateTranche(_address);
        emit LoyaltyUpdated(_address, userLoyalty[_address].tranche, _points);
    }

    function updateIds(uint256[] memory _ids) external HasPatrol("ADMIN") {
        tokenIds = _ids;
    }

    // https://eips.ethereum.org/EIPS/eip-1155#erc-1155-token-receiver
    function supportsInterface(bytes4 interfaceId) 
        external
        override
        view 
        returns (bool)
    {
        return interfaceId == 0x01ffc9a7 
            || interfaceId == 0x4e2312e0; 
    }

    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    )
        external
        override
        returns(bytes4)
    {
        return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
    }

    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    )
        external
        override
        returns(bytes4)
    {
        return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
    }

    function getLoyaltyStats(address _user)
        external
        view
        returns (
            bool _active, 
            bool _approved, 
            uint256[] memory _balances,
            uint256[] memory _stats
        )
    {
        _active = ISlopes(slopesAddress()).active();
        _approved = IERC1155(lodgeAddress()).isApprovedForAll(_user, address(this));
        
        address[] memory users = new address[](tokenIds.length);
        for (uint i = 0; i < tokenIds.length; i++) {
            users[i] = _user;
        }
        
        _balances = IERC1155(lodgeAddress()).balanceOfBatch(users, tokenIds);

        _stats = new uint256[](4);
        _stats[0] = userLoyalty[_user].points;
        _stats[1] = userLoyalty[_user].tranche;
        _stats[2] = userLoyalty[_user].staked;
        _stats[3] = userLoyalty[_user].boost;

    }
}
// File: contracts/loyalty/LoyaltyBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.12;

import "@openzeppelin/contracts/math/SafeMath.sol";
import { PatrolBase } from "../utils/PatrolBase.sol";

contract LoyaltyBase is PatrolBase {
    using SafeMath for uint256;

    constructor(address addressRegistry) 
        public
    {
        _setAddressRegistry(addressRegistry);
    }
}
// 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"
        );
        _;
    }
}