Contract Address Details

0x0b921FC8B84656157F5B7Ddbf385205d1873a72C

Contract Name
ElkV2FarmFactory
Creator
0x56bbca–3262ff at 0x85f4b0–3af127
Balance
0 VLX
Tokens
Fetching tokens...
Transactions
1 Transactions
Transfers
0 Transfers
Gas Used
44,650
Last Balance Update
69088070
Contract name:
ElkV2FarmFactory




Optimization enabled
true
Compiler version
v0.8.19+commit.7dd6d404




Optimization runs
300
EVM Version
default




Verified at
2023-10-05T09:16:48.684928Z

Constructor Arguments

0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000100000000000000000000000062dfb99c4d0ac8764b75a132ce0c4c433af46cf4

Arg [0] (address[]) : [0x62dfb99c4d0ac8764b75a132ce0c4c433af46cf4]

              

Contract source code

// SPDX-License-Identifier: BUSL-1.1
//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol


// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// File: contracts/interfaces/IElkPair.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.5.0;

interface IElkPair {
    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: contracts/interfaces/IElkDexOracle.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;

interface IElkDexOracle {
    struct Observation {
        uint timestamp;
        uint price0Cumulative;
        uint price1Cumulative;
    }

    function weth() external view returns (address);

    function factory() external view returns (address);

    function windowSize() external view returns (uint);

    function granularity() external view returns (uint8);

    function periodSize() external view returns (uint);

    function pairObservations(address _pair) external view returns (Observation[] memory);

    function observationIndexOf(uint _timestamp) external view returns (uint);

    function update(address _tokenA, address _tokenB) external;

    function updateWeth(address _token) external;

    function consult(address _tokenIn, uint _amountIn, address _tokenOut) external view returns (uint);

    function consultWeth(address _tokenIn, uint _amountIn) external view returns (uint);
}

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


// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @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
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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");

        (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 functionCallWithValue(target, data, 0, "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");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // 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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: @openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol


// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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


// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

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


// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;


/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: contracts/interfaces/IStaking.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;


interface IStaking {
    /* ========== STATE VARIABLES ========== */
    function stakingToken() external returns (IERC20);

    function totalSupply() external returns (uint256);

    function balances(address _account) external returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */
    function stake(uint256 _amount) external;

    function withdraw(uint256 _amount) external;

    function exit() external;

    function recoverERC20(address _tokenAddress, address _recipient, uint256 _amount) external;

    /* ========== EVENTS ========== */

    // Emitted on staking
    event Staked(address indexed account, uint256 amount);

    // Emitted on withdrawal (including exit)
    event Withdrawn(address indexed account, uint256 amount);

    // Emitted on token recovery
    event Recovered(address indexed token, address indexed recipient, uint256 amount);
}

// File: contracts/interfaces/IStakingFee.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;


interface IStakingFee is IStaking {
    /* ========== STATE VARIABLES ========== */
    function feesUnit() external returns (uint256);

    function maxFee() external returns (uint256);

    function withdrawalFeeSchedule(uint256) external returns (uint256);

    function withdrawalFeesBps(uint256) external returns (uint256);

    function depositFeeBps() external returns (uint256);

    function collectedFees() external returns (uint256);

    function userLastStakedTime(address _user) external view returns (uint32);

    /* ========== VIEWS ========== */

    function depositFee(uint256 _depositAmount) external view returns (uint256);

    function withdrawalFee(address _account, uint256 _withdrawalAmount) external view returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function recoverFees(address _recipient) external;

    /* ========== EVENTS ========== */

    // Emitted when fees are (re)configured
    event FeesSet(uint16 _depositFeeBps, uint16[] _withdrawalFeesBps, uint32[] _feeSchedule);

    // Emitted when a deposit fee is collected
    event DepositFeesCollected(address indexed _user, uint256 _amount);

    // Emitted when a withdrawal fee is collected
    event WithdrawalFeesCollected(address indexed _user, uint256 _amount);

    // Emitted when fees are recovered by governance
    event FeesRecovered(uint256 _amount);
}

// File: contracts/interfaces/IStakingRewards.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;


interface IStakingRewards is IStakingFee {
    /* ========== STATE VARIABLES ========== */

    function rewardTokens(uint256) external view returns (IERC20);

    function rewardTokenAddresses(address _rewardAddress) external view returns (bool);

    function periodFinish() external view returns (uint256);

    function rewardsDuration() external view returns (uint256);

    function lastUpdateTime() external view returns (uint256);

    function rewardRates(address _rewardAddress) external view returns (uint256);

    function rewardPerTokenStored(address _rewardAddress) external view returns (uint256);

    // wallet address => token address => amount
    function userRewardPerTokenPaid(address _walletAddress, address _tokenAddress) external view returns (uint256);

    function rewards(address _walletAddress, address _tokenAddress) external view returns (uint256);

    /* ========== VIEWS ========== */

    function lastTimeRewardApplicable() external view returns (uint256);

    function rewardPerToken(address _tokenAddress) external view returns (uint256);

    function earned(address _tokenAddress, address _account) external view returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function getReward(address _tokenAddress, address _recipient) external;

    function getRewards(address _recipient) external;

    // Must send reward before calling this!
    function startEmission(uint256[] memory _rewards, uint256 _duration) external;

    function stopEmission(address _refundAddress) external;

    function recoverLeftoverReward(address _tokenAddress, address _recipient) external;

    function addRewardToken(address _tokenAddress) external;

    function rewardTokenIndex(address _tokenAddress) external view returns (int8);

    /* ========== EVENTS ========== */

    // Emitted when a reward is paid to an account
    event RewardPaid(address indexed _token, address indexed _account, uint256 _reward);

    // Emitted when a leftover reward is recovered
    event LeftoverRewardRecovered(address indexed _recipient, uint256 _amount);

    // Emitted when rewards emission is started
    event RewardsEmissionStarted(uint256[] _rewards, uint256 _duration);

    // Emitted when rewards emission ends
    event RewardsEmissionEnded();
}

// File: contracts/interfaces/IElkV2FarmingRewards.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;




interface IElkV2FarmingRewards is IStakingRewards {
    /// @notice Represents a snapshot of an LP position at a given timestamp
    struct Position {
        uint112 amount0;
        uint112 amount1;
        uint32 blockTimestamp;
    }

    /* ========== STATE VARIABLES ========== */

    function oracle() external returns (IElkDexOracle);

    function lpToken() external returns (IElkPair);

    function coverageTokenAddress() external returns (address);

    function coverageAmount() external returns (uint256);

    function coverageVestingDuration() external returns (uint256);

    function coverageRate() external returns (uint256);

    function coveragePerTokenStored() external returns (uint256);

    function userCoveragePerTokenPaid(address _tokenPaid) external returns (uint256);

    function coverage(address _token) external returns (uint256);

    function lastStakedPosition(
        address _user
    ) external returns (uint112 amount0, uint112 amount1, uint32 blockTimeStamp);

    /* ========== VIEWS ========== */

    function coveragePerToken() external view returns (uint256);

    function coverageEarned(address _account) external view returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function getCoverage(address _recipient) external;

    function startEmission(uint256[] memory _rewards, uint256 _coverage, uint256 _duration) external;

    function recoverLeftoverCoverage(address _recipient) external;

    /* ========== EVENTS ========== */

    // Emitted when the coverage is paid to an account
    event CoveragePaid(address indexed account, uint256 coverage);

    // Emitted when the leftover coverage is recovered
    event LeftoverCoverageRecovered(address indexed recipient, uint256 amount);
}

// File: contracts/interfaces/IElkV2FarmingRewardsPermissioned.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;


interface IElkV2FarmingRewardsPermissioned is IElkV2FarmingRewards {
    function setAddressPermission(address _walletAddress, bool _permission) external;
}

// File: contracts/interfaces/IElkV2FarmFactory.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>

pragma solidity >=0.8.0;


interface IElkV2FarmFactory {
    event ContractCreated(address _newContract);
    event ManagerSet(address _farmManager);
    event FeeSet(uint256 _newFee);
    event FeesRecovered(uint256 _balanceRecovered);

    function getFarm(address _creator, address _lpTokenAddress) external view returns (address);

    function getPermissionedFarm(address _creator, address _lpTokenAddress) external view returns (address);

    function isFarm(address _farmAddress) external view returns (bool);

    function isPermissionedFarm(address _farmAddress) external view returns (bool);

    function allFarms(uint _index) external view returns (address);

    function allFarmsLength() external view returns (uint256);

    function farmManager() external view returns (address);

    function getCreator(address _farmAddress) external view returns (address);

    function feeToken() external view returns (IERC20);

    function fee() external view returns (uint256);

    function maxFee() external view returns (uint256);

    function createNewRewards(
        address _oracleAddress,
        address _lpTokenAddress,
        address _coverageTokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) external;

    function createNewPermissonedRewards(
        address _oracleAddress,
        address _lpTokenAddress,
        address _coverageTokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) external;

    function setManager(address _managerAddress) external;

    function setFee(uint256 _newFee) external;

    function withdrawFees() external;

    function overrideOwnership(address _farmAddress) external;
}

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


// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;




/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

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


// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

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


// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;




/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

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

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

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

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

// File: @openzeppelin/contracts/access/Ownable.sol


// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;


/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: contracts/Staking.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>
// - Real-Hansolo <[email protected]>

pragma solidity >=0.8.0;







/**
 * Base contract implementing simple ERC20 token staking functionality (no staking rewards).
 */
contract Staking is ReentrancyGuard, Ownable, IStaking {
    using SafeERC20 for IERC20;

    /* ========== STATE VARIABLES ========== */

    /// @notice Staking token interface
    IERC20 public immutable stakingToken;

    /// @notice Total supply of the staking token
    uint256 public totalSupply;

    /// @notice Account balances
    mapping(address account => uint256 balance) public balances;

    // Scaling factor: supply is always stored as wei (10**18) regardless of the token's decimals
    uint256 private supplyScalingFactor;

    /* ========== CONSTRUCTOR ========== */

    /// @param _stakingTokenAddress address of the token used for staking (must be ERC20)
    constructor(address _stakingTokenAddress) {
        require(_stakingTokenAddress != address(0), "E1");
        stakingToken = IERC20(_stakingTokenAddress);
        supplyScalingFactor = 1e18 / 10 ** ERC20(_stakingTokenAddress).decimals();
    }

    /**
     * @dev Stake tokens.
     * Note: the contract must have sufficient allowance for the staking token.
     * @param _amount amount to stake
     */
    function stake(uint256 _amount) public nonReentrant {
        uint256 originalAmount = _amount;
        _amount = _beforeStake(msg.sender, _amount);
        require(_amount > 0 && originalAmount > 0, "E2"); // Check after the hook
        totalSupply += _amount * supplyScalingFactor;
        balances[msg.sender] += _amount;
        stakingToken.safeTransferFrom(msg.sender, address(this), originalAmount);
        emit Staked(msg.sender, _amount);
    }

    /**
     * @dev Withdraw previously staked tokens.
     * @param _amount amount to withdraw
     */
    function withdraw(uint256 _amount) public nonReentrant {
        uint256 originalAmount = _amount;
        _amount = _beforeWithdraw(msg.sender, _amount);
        // Check after the hook
        require(_amount > 0 && _amount <= balances[msg.sender] && originalAmount <= balances[msg.sender], "E3");
        totalSupply -= originalAmount * supplyScalingFactor;
        balances[msg.sender] -= originalAmount;
        stakingToken.safeTransfer(msg.sender, _amount);
        emit Withdrawn(msg.sender, _amount);
    }

    /**
     * @dev Exit the farm, i.e., withdraw the entire token balance of the calling account
     */
    function exit() external {
        _beforeExit(msg.sender);
        withdraw(balances[msg.sender]);
    }

    /* ========== RESTRICTED FUNCTIONS ========== */

    /**
     * @dev Recover ERC20 tokens held in the contract.
     * Note: privileged governance function to recover tokens mistakenly sent to this contract address.
     * This function cannot be used to withdraw staking tokens.
     * @param _tokenAddress address of the token to recover
     * @param _recipient recovery address
     * @param _amount amount to withdraw
     * @ return withdrawn amount (may differ from input amount due to e.g., fees)
     */
    function recoverERC20(address _tokenAddress, address _recipient, uint256 _amount) external nonReentrant onlyOwner {
        require(_tokenAddress != address(stakingToken), "E4");
        _beforeRecoverERC20(_tokenAddress, _recipient, _amount);
        IERC20 token = IERC20(_tokenAddress);
        token.safeTransfer(_recipient, _amount);
        emit Recovered(_tokenAddress, _recipient, _amount);
    }

    /* ========== HOOKS ========== */

    /**
     * @dev Internal hook called before staking (in the stake() function).
     * @ param _account staker address
     * @param _amount amount being staken
     * @return amount to stake (may be changed by the hook)
     */
    function _beforeStake(address /*_account*/, uint256 _amount) internal virtual returns (uint256) {
        return _amount;
    }

    /**
     * @dev Internal hook called before withdrawing (in the withdraw() function).
     * @ param _account withdrawer address
     * @param _amount amount being withdrawn
     * @return amount to withdraw (may be changed by the hook)
     */
    function _beforeWithdraw(address /*_account*/, uint256 _amount) internal virtual returns (uint256) {
        return _amount;
    }

    /**
     * @dev Internal hook called before exiting (in the exit() function).
     * Note: since exit() calls withdraw() internally, the _beforeWithdraw() hook fill fire too.
     * @param _account address exiting
     */
    function _beforeExit(address _account) internal virtual {}

    /**
     * @dev Internal hook called before recovering tokens (in the recoverERC20() function).
     * @param _tokenAddress address of the token being recovered
     * @param _recipient recovery address
     * @param _amount amount being withdrawn
     */
    function _beforeRecoverERC20(address _tokenAddress, address _recipient, uint256 _amount) internal virtual {}
}

// File: contracts/StakingFee.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;



/**
 * Contract implementing simple ERC20 token staking functionality and supporting deposit/withdrawal fees (no staking rewards).
 */
contract StakingFee is Staking, IStakingFee {
    using SafeERC20 for IERC20;

    /* ========== STATE VARIABLES ========== */

    /// @notice Constant Fee Unit (1e4)
    uint256 public constant feesUnit = 10000;

    /// @notice Maximum fee (20%)
    uint256 public constant maxFee = 2000;

    /// @notice Schedule of withdrawal fees represented as a sorted array of durations
    /// @dev example: 10% after 1 hour, 1% after a day, 0% after a week => [3600, 86400]
    uint256[] public withdrawalFeeSchedule;

    /// @notice Withdrawal fees described in basis points (fee unit) represented as an array of the same length as withdrawalFeeSchedule
    /// @dev example: 10% after 1 hour, 1% after a day, 0% after a week => [1000, 100]
    uint256[] public withdrawalFeesBps;

    /// @notice Deposit (staking) fee in basis points (fee unit)
    uint256 public depositFeeBps;

    /// @notice Counter of collected fees
    uint256 public collectedFees;

    /// @notice Last staking time for each user
    mapping(address => uint32) public userLastStakedTime;

    /* ========== CONSTRUCTOR ========== */

    /**
     * @param _stakingTokenAddress address of the token used for staking (must be ERC20)
     * @param _depositFeeBps deposit fee in basis points
     * @param _withdrawalFeesBps aligned to fee schedule
     * @param _withdrawalFeeSchedule assumes a sorted array
     */
    constructor(
        address _stakingTokenAddress,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) Staking(_stakingTokenAddress) {
        _setFees(_depositFeeBps, _withdrawalFeesBps, _withdrawalFeeSchedule);
    }

    /* ========== VIEWS ========== */

    /**
     * @dev Calculate the deposit fee for a given amount.
     * @param _depositAmount amount to stake
     * @return fee paid upon deposit
     */
    function depositFee(uint256 _depositAmount) public view returns (uint256) {
        return depositFeeBps > 0 ? (_depositAmount * depositFeeBps) / feesUnit : 0;
    }

    /**
     * @dev Calculate the withdrawal fee for a given amount.
     * @param _account user wallet address
     * @param _withdrawalAmount amount to withdraw
     * @return fee paid upon withdrawal
     */
    function withdrawalFee(address _account, uint256 _withdrawalAmount) public view returns (uint256) {
        uint256 userLastStakedTimestampDiff = block.timestamp - userLastStakedTime[_account];
        uint256 withdrawalFeeAmount;
        for (uint i = 0; i < withdrawalFeeSchedule.length; ++i) {
            if (userLastStakedTimestampDiff < withdrawalFeeSchedule[i]) {
                withdrawalFeeAmount = (_withdrawalAmount * withdrawalFeesBps[i]) / feesUnit;
                break;
            }
        }
        return withdrawalFeeAmount;
    }

    /* ========== RESTRICTED FUNCTIONS ========== */

    /**
     * @dev Recover collected fees held in the contract.
     * Note: privileged function for governance
     * @param _recipient fee recovery address
     */
    function recoverFees(address _recipient) external onlyOwner nonReentrant {
        _beforeRecoverFees(_recipient);
        uint256 previousFees = collectedFees;
        collectedFees = 0;
        emit FeesRecovered(previousFees);
        stakingToken.safeTransfer(_recipient, previousFees);
    }

    /* ========== PRIVATE FUNCTIONS ========== */

    /**
     * @dev Configure the fees for this contract.
     * @param _depositFeeBps deposit fee in basis points
     * @param _withdrawalFeesBps withdrawal fees in basis points
     * @param _withdrawalFeeSchedule withdrawal fees schedule
     */
    function _setFees(
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) private {
        require(
            _withdrawalFeeSchedule.length == _withdrawalFeesBps.length &&
                _withdrawalFeeSchedule.length <= 10 &&
                _depositFeeBps <= maxFee,
            "E5"
        );

        uint32 lastFeeSchedule = 0;
        uint256 lastWithdrawalFee = maxFee + 1;

        for (uint i = 0; i < _withdrawalFeeSchedule.length; ++i) {
            require(_withdrawalFeeSchedule[i] > lastFeeSchedule, "E7");
            require(_withdrawalFeesBps[i] < lastWithdrawalFee, "E8");
            lastFeeSchedule = _withdrawalFeeSchedule[i];
            lastWithdrawalFee = _withdrawalFeesBps[i];
        }

        withdrawalFeeSchedule = _withdrawalFeeSchedule;
        withdrawalFeesBps = _withdrawalFeesBps;
        depositFeeBps = _depositFeeBps;

        emit FeesSet(_depositFeeBps, _withdrawalFeesBps, _withdrawalFeeSchedule);
    }

    /* ========== HOOKS ========== */

    /**
     * @dev Override _beforeStake() hook to collect the deposit fee and update associated state
     */
    function _beforeStake(address _account, uint256 _amount) internal virtual override returns (uint256) {
        uint256 fee = depositFee(_amount);
        userLastStakedTime[_account] = uint32(block.timestamp);
        if (fee > 0) {
            collectedFees += fee;
            emit DepositFeesCollected(_account, fee);
        }
        return super._beforeStake(_account, _amount - fee);
    }

    /**
     * @dev Override _beforeWithdrawl() hook to collect the withdrawal fee and update associated state
     */
    function _beforeWithdraw(address _account, uint256 _amount) internal virtual override returns (uint256) {
        uint256 fee = withdrawalFee(_account, _amount);
        if (fee > 0) {
            collectedFees += fee;
            emit WithdrawalFeesCollected(_account, fee);
        }
        return super._beforeWithdraw(_account, _amount - fee);
    }

    /**
     * @dev Internal hook called before recovering fees (in the recoverFees() function).
     * @param _recipient recovery address
     */
    function _beforeRecoverFees(address _recipient) internal virtual {}
}

// File: contracts/StakingRewards.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>
// - Real-Hansolo <[email protected]>

pragma solidity >=0.8.0;






/**
 * Contract implementing simple ERC20 token staking functionality with staking rewards and deposit/withdrawal fees.
 */
contract StakingRewards is StakingFee, IStakingRewards {
    using SafeERC20 for IERC20;

    /* ========== STATE VARIABLES ========== */

    /// @notice List of reward token interfaces
    IERC20[] public rewardTokens;

    /// @notice Reward token addresses (maps every reward token address to true, others to false)
    mapping(address tokenAddress => bool isRewardToken) public rewardTokenAddresses;

    /// @notice Timestamp when rewards stop emitting
    uint256 public periodFinish;

    /// @notice Duration for reward emission
    uint256 public rewardsDuration;

    /// @notice Last time the rewards were updated
    uint256 public lastUpdateTime;

    /// @notice Reward token rates (maps every reward token to an emission rate,
    //i.e., how many tokens emitted per second)
    mapping(address token => uint256 emissionRate) public rewardRates;

    /// @notice How many tokens are emitted per staked token
    mapping(address token => uint256 emissionRate) public rewardPerTokenStored;

    /// @notice How many reward tokens were paid per user (token address => wallet address => amount)
    mapping(address token => mapping(address walletAddress => uint256 amount)) public userRewardPerTokenPaid;

    /// @notice Accumulator of reward tokens per user (token address => wallet address => amount)
    mapping(address token => mapping(address walletAddress => uint256 amount)) public rewards;

    /* ========== CONSTRUCTOR ========== */

    /**
     * @param _stakingTokenAddress address of the token used for staking (must be ERC20)
     * @param _rewardTokenAddresses addresses the reward tokens (must be ERC20)
     * @param _rewardsDuration reward emission duration
     * @param _depositFeeBps deposit fee in basis points
     * @param _withdrawalFeesBps aligned to fee schedule
     * @param _withdrawalFeeSchedule assumes a sorted array
     */
    constructor(
        address _stakingTokenAddress,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) StakingFee(_stakingTokenAddress, _depositFeeBps, _withdrawalFeesBps, _withdrawalFeeSchedule) {
        require(_rewardTokenAddresses.length > 0, "E9");
        // update reward data structures
        for (uint i = 0; i < _rewardTokenAddresses.length; ++i) {
            address tokenAddress = _rewardTokenAddresses[i];
            _addRewardToken(tokenAddress);
        }
        rewardsDuration = _rewardsDuration;
    }

    /* ========== VIEWS ========== */

    /**
     * @notice Return the last time rewards are applicable (the lowest of the
       current timestamp and the rewards expiry timestamp).
     * @return timestamp
     */
    function lastTimeRewardApplicable() public view returns (uint256) {
        return block.timestamp < periodFinish ? block.timestamp : periodFinish;
    }

    /**
     * @notice Return the reward per staked token for a given reward token address.
     * @param _tokenAddress reward token address
     * @return amount of reward per staked token
     */
    function rewardPerToken(address _tokenAddress) public view returns (uint256) {
        if (totalSupply == 0) {
            return rewardPerTokenStored[_tokenAddress];
        }
        return
            rewardPerTokenStored[_tokenAddress] +
            ((lastTimeRewardApplicable() - lastUpdateTime) *
                rewardRates[_tokenAddress] *
                10 ** ERC20(_tokenAddress).decimals()) /
            totalSupply;
    }

    /**
     * @notice Return the total reward earned by a user for a given reward token address.
     * @param _tokenAddress reward token address
     * @param _account user wallet address
     * @return amount earned
     */
    function earned(address _tokenAddress, address _account) public view returns (uint256) {
        return
            (balances[_account] * (rewardPerToken(_tokenAddress) - userRewardPerTokenPaid[_tokenAddress][_account])) /
            10 ** ERC20(_tokenAddress).decimals() +
            rewards[_tokenAddress][_account];
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    /**
     * @dev claim the specified token reward for a staker
     * @param _tokenAddress the address of the reward token
     * @param _recipient the address of the staker that should receive the reward
     * @ return amount of reward received
     */
    function getReward(address _tokenAddress, address _recipient) public nonReentrant updateRewards(_recipient) {
        return _getReward(_tokenAddress, _recipient);
    }

    /**
     * @dev claim rewards for all the reward tokens for the staker
     * @param _recipient address of the recipient to receive the rewards
     */
    function getRewards(address _recipient) public nonReentrant updateRewards(_recipient) {
        for (uint i = 0; i < rewardTokens.length; ++i) {
            _getReward(address(rewardTokens[i]), _recipient);
        }
    }

    /**
     * @dev Start the emission of rewards to stakers. The owner must send reward
       tokens to the contract before calling this function.
     * Note: Can only be called by owner when the contract is not emitting
       rewards.
     * @param _rewards array of rewards amounts for each reward token
     * @param _duration duration in seconds for which rewards will be emitted
     */
    function startEmission(
        uint256[] memory _rewards,
        uint256 _duration
    ) public virtual nonReentrant onlyOwner whenNotEmitting updateRewards(address(0)) {
        require(_duration > 0, "E10");
        require(_rewards.length == rewardTokens.length, "E11");

        _beforeStartEmission(_rewards, _duration);

        rewardsDuration = _duration;

        for (uint i = 0; i < rewardTokens.length; ++i) {
            IERC20 token = rewardTokens[i];
            address tokenAddress = address(token);
            rewardRates[tokenAddress] = _rewards[i] / rewardsDuration;

            // Ensure the provided reward amount is not more than the balance in the contract.
            // This keeps the reward rate in the right range, preventing overflows due to
            // very high values of rewardRate in the earned and rewardsPerToken functions;
            // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
            uint256 balance = rewardTokens[i].balanceOf(address(this));
            if (tokenAddress != address(stakingToken)) {
                require(rewardRates[tokenAddress] <= balance / rewardsDuration, "E3");
            } else {
                // Handle carefully where rewardsToken is the same as stakingToken (need to subtract total supply)
                require(rewardRates[tokenAddress] <= (balance - totalSupply) / rewardsDuration, "E3");
            }
        }

        lastUpdateTime = block.timestamp;
        periodFinish = block.timestamp + rewardsDuration;

        emit RewardsEmissionStarted(_rewards, _duration);
    }

    /**
     * @dev stop the reward emission process and transfer the remaining reward tokens to a specified address
     * Note: can only be called by owner when the contract is currently emitting rewards
     * @param _refundAddress the address to receive the remaining reward tokens
     */
    function stopEmission(address _refundAddress) external nonReentrant onlyOwner whenEmitting {
        _beforeStopEmission(_refundAddress);
        uint256 remaining = 0;
        if (periodFinish > block.timestamp) {
            remaining = periodFinish - block.timestamp;
        }

        periodFinish = block.timestamp;

        for (uint i = 0; i < rewardTokens.length; ++i) {
            IERC20 token = rewardTokens[i];
            address tokenAddress = address(token);
            uint256 refund = rewardRates[tokenAddress] * remaining;
            if (refund > 0) {
                token.safeTransfer(_refundAddress, refund);
            }
        }

        emit RewardsEmissionEnded();
    }

    /**
     * @dev recover leftover reward tokens and transfer them to a specified recipient
     * Note: can only be called by owner when the contract is not emitting rewards
     * @param _tokenAddress address of the reward token to be recovered
     * @param _recipient address to receive the recovered reward tokens
     */
    function recoverLeftoverReward(address _tokenAddress, address _recipient) external onlyOwner whenNotEmitting {
        require(totalSupply == 0, "E12");
        if (rewardTokenAddresses[_tokenAddress]) {
            _beforeRecoverLeftoverReward(_tokenAddress, _recipient);
            IERC20 token = IERC20(_tokenAddress);
            uint256 amount = token.balanceOf(address(this));
            if (amount > 0) {
                token.safeTransfer(_recipient, amount);
            }
            emit LeftoverRewardRecovered(_recipient, amount);
        }
    }

    /**
     * @dev add a reward token to the contract
     * Note: can only be called by owner when the contract is not emitting rewards
     * @param _tokenAddress address of the new reward token
     */
    function addRewardToken(address _tokenAddress) external onlyOwner whenNotEmitting {
        _addRewardToken(_tokenAddress);
    }

    /**
     * @dev Return the array index of the provided token address (if applicable)
     * @param _tokenAddress address of the LP token
     * @return the array index for _tokenAddress or -1 if it is not a reward token
     */
    function rewardTokenIndex(address _tokenAddress) public view returns (int8) {
        if (rewardTokenAddresses[_tokenAddress]) {
            for (uint i = 0; i < rewardTokens.length; ++i) {
                if (address(rewardTokens[i]) == _tokenAddress) {
                    return int8(int256(i));
                }
            }
        }
        return -1;
    }

    /* ========== PRIVATE FUNCTIONS ========== */

    /**
     * @dev Get the reward amount of a token for a specific recipient
     * @param _tokenAddress address of the token
     * @param _recipient address of the recipient
     */
    function _getReward(address _tokenAddress, address _recipient) private {
        require(msg.sender == owner() || msg.sender == _recipient, "E14");
        require(rewardTokenAddresses[_tokenAddress], "E13");
        uint256 reward = rewards[_tokenAddress][_recipient];
        if (reward > 0) {
            rewards[_tokenAddress][_recipient] = 0;
            IERC20(_tokenAddress).safeTransfer(_recipient, reward);
            emit RewardPaid(_tokenAddress, _recipient, reward);
        }
    }

    /**
     * @dev Add a token as a reward token
     * @param _tokenAddress address of the token to be added as a reward token
     */
    function _addRewardToken(address _tokenAddress) private {
        require(rewardTokens.length <= 15, "E15");
        require(_tokenAddress != address(0), "E1");
        if (!rewardTokenAddresses[_tokenAddress]) {
            rewardTokens.push(IERC20(_tokenAddress));
            rewardTokenAddresses[_tokenAddress] = true;
        }
    }

    /* ========== HOOKS ========== */

    /**
     * @dev Override _beforeStake() hook to ensure staking is only possible when
       rewards are emitting and update the rewards
     */
    function _beforeStake(
        address _account,
        uint256 _amount
    ) internal virtual override whenEmitting updateRewards(_account) returns (uint256) {
        return super._beforeStake(_account, _amount);
    }

    /**
     * @dev Override _beforeExit() hook to claim all rewards for the account exiting
     */
    function _beforeExit(address _account) internal virtual override {
        // getRewards calls updateRewards so we don't need to call it explicitly again here
        getRewards(_account);
        super._beforeExit(_account);
    }

    /**
     * @dev Override _beforeRecoverERC20() hook to prevent recovery of a reward token
     */
    function _beforeRecoverERC20(address _tokenAddress, address _recipient, uint256 _amount) internal virtual override {
        require(!rewardTokenAddresses[_tokenAddress], "E16");
        super._beforeRecoverERC20(_tokenAddress, _recipient, _amount);
    }

    /**
     * @dev Internal hook called before starting the emission process (in the
       startEmission() function).
     * @param _rewards array of rewards per token.
     * @param _duration emission duration.
     */
    function _beforeStartEmission(uint256[] memory _rewards, uint256 _duration) internal virtual {}

    /**
     * @dev Internal hook called before stopping the emission process (in the
       stopEmission() function).
     * @param _refundAddress address to refund the remaining reward to
     */
    function _beforeStopEmission(address _refundAddress) internal virtual {}

    /**
     * @dev Internal hook called before recovering leftover rewards (in the
       recoverLeftoverRewards() function).
     * @param _tokenAddress address of the token to recover
     * @param _recipient address to recover the leftover rewards to
     */
    function _beforeRecoverLeftoverReward(address _tokenAddress, address _recipient) internal virtual {}

    /* ========== MODIFIERS ========== */

    /**
     * @dev Modifier to update rewards of a given account.
     * @param _account account to update rewards for
     */
    modifier updateRewards(address _account) {
        for (uint i = 0; i < rewardTokens.length; ++i) {
            address tokenAddress = address(rewardTokens[i]);
            rewardPerTokenStored[tokenAddress] = rewardPerToken(tokenAddress);
        }
        lastUpdateTime = lastTimeRewardApplicable();
        if (_account != address(0)) {
            for (uint i = 0; i < rewardTokens.length; ++i) {
                address tokenAddress = address(rewardTokens[i]);
                rewards[tokenAddress][_account] = earned(tokenAddress, _account);
                userRewardPerTokenPaid[tokenAddress][_account] = rewardPerTokenStored[tokenAddress];
            }
        }
        _;
    }

    /**
     * @dev Modifier to check if rewards are emitting.
     */
    modifier whenEmitting() {
        require(block.timestamp <= periodFinish, "E18");
        _;
    }

    /**
     * @dev Modifier to check if rewards are not emitting.
     */
    modifier whenNotEmitting() {
        require(block.timestamp > periodFinish, "E17");
        _;
    }
}

// File: contracts/ElkV2FarmingRewards.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;





/**
 * Contract implementing simple ERC20 token staking functionality with staking rewards, impermanent loss coverage, and deposit/withdrawal fees.
 */
contract ElkV2FarmingRewards is StakingRewards, IElkV2FarmingRewards {
    using SafeERC20 for IERC20;

    /* ========== STATE VARIABLES ========== */

    /// @notice Interface to the ElkDex pricing oracle on this blockchain
    IElkDexOracle public immutable oracle;

    /// @notice Interface to the LP token that is staked in this farm
    IElkPair public immutable lpToken;

    /// @notice Address of the coverage token
    address public coverageTokenAddress;

    /// @notice Total amount of coverage available (worst case max amount)
    uint256 public coverageAmount;

    /// @notice Time until a farmed position is fully covered against impermanent loss (100%)
    uint256 public coverageVestingDuration;

    /// @notice Rate of coverage vesting
    uint256 public coverageRate;

    /// @notice Coverage amount per token staked in the farm
    uint256 public coveragePerTokenStored;

    /// @notice How much coverage was paid per user (wallet address => amount)
    mapping(address => uint256) public userCoveragePerTokenPaid;

    /// @notice Accumulator of coverage tokens per user (wallet address => amount)
    mapping(address => uint256) public coverage;

    /// @notice Last farming position for a given user (wallet address => position)
    mapping(address => Position) public lastStakedPosition;

    /* ========== CONSTRUCTOR ========== */

    /**
     * @param _oracleAddress address of the price oracle
     * @param _lpTokenAddress address of the staking LP token (must be an ElkDex LP)
     * @param _coverageTokenAddress address of the token that the coverage is paid in
     * @param _coverageAmount total amount of coverage
     * @param _coverageVestingDuration time it takes to vest 100% of the coverage (min. 1 day)
     * @param _rewardTokenAddresses addresses the reward tokens (must be ERC20)
     * @param _rewardsDuration reward emission duration
     * @param _depositFeeBps deposit fee in basis points
     * @param _withdrawalFeesBps aligned to fee schedule
     * @param _withdrawalFeeSchedule assumes a sorted array
     */
    constructor(
        address _oracleAddress,
        address _lpTokenAddress,
        address _coverageTokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    )
        StakingRewards(
            _lpTokenAddress,
            _rewardTokenAddresses,
            _rewardsDuration,
            _depositFeeBps,
            _withdrawalFeesBps,
            _withdrawalFeeSchedule
        )
    {
        oracle = IElkDexOracle(_oracleAddress);
        lpToken = IElkPair(_lpTokenAddress);

        if (_coverageTokenAddress != address(0)) {
            require(lpToken.token0() == _coverageTokenAddress || lpToken.token1() == _coverageTokenAddress, "E19");
            require(_coverageVestingDuration >= 24 * 3600 && _coverageVestingDuration <= rewardsDuration, "E21");
        }

        require(lpToken.factory() == oracle.factory(), "E20");

        coverageTokenAddress = _coverageTokenAddress;
        coverageAmount = _coverageAmount;
        coverageVestingDuration = _coverageVestingDuration;
    }

    // Optimized version below
    /*function coveragePerToken() public view returns (uint256) {
        if (totalSupply == 0) {
            return coveragePerTokenStored;
        }
        return
            // does this work for non 18 dec tokens?  rate = _coverage / rewardsDuration, here rate is converted back to 18 dec
            coveragePerTokenStored +
            ((lastTimeRewardApplicable() - lastUpdateTime) *
                coverageRate *
                10**ERC20(coverageTokenAddress).decimals()) /
            totalSupply;
    }*/

    /**
     * @dev Return the coverage per staked token (in coverage token amounts)
     * @return amount of coverage per staked token
     */
    function coveragePerToken() public view returns (uint256) {
        return
            totalSupply == 0
                ? coveragePerTokenStored
                : coveragePerTokenStored +
                    (((lastTimeRewardApplicable() - lastUpdateTime) *
                        coverageRate *
                        10 ** ERC20(coverageTokenAddress).decimals()) / totalSupply);
    }

    // Code below optimizes this version of the function
    /*function coverageEarned(address _account) public view returns(uint256) {
        if (coverageTokenAddress == address(0)) {
            return 0;
        }
        uint256 hodlValue = lpValueWeth(lastStakedPosition[_account]);
        if (hodlValue == 0) {
            // prevent division by zero below // equivalent check would be lastStakedPosition[_account].blockTimestamp > 0
            return coverage[_account];
        }
        uint256 outValue = lpValueWeth(position(balances[_account]));
        uint256 cappedCoverage = (balances[_account] *
            (coveragePerToken() - userCoveragePerTokenPaid[_account])) / 1e18;
        uint256 vested = vestedCoverage(
            hodlValue,
            outValue,
            lastStakedPosition[_account].blockTimestamp
        );
        if (vested > cappedCoverage) {
            vested = cappedCoverage;
        }
        // amount * (hodl value - out value) / hodl value = amount * (1 - (out value / hodl value))
        return (vested - (vested * outValue) / hodlValue) + coverage[_account];
    }*/

    /**
     * @dev Return the total coverage earned by a user.
     * @param _account user wallet address
     * @return coverage amount earned
     */
    function coverageEarned(address _account) public view returns (uint256) {
        if (coverageTokenAddress == address(0)) {
            return 0;
        }
        Position memory lastStake = lastStakedPosition[_account];
        uint256 hodlValue = lpValueWeth(lastStake);
        if (hodlValue == 0) {
            return coverage[_account];
        }
        uint256 outValue = lpValueWeth(position(balances[_account]));
        uint256 balance = balances[_account];
        uint256 cappedCoverage = (balance * (coveragePerToken() - userCoveragePerTokenPaid[_account])) / 1e18;
        uint256 vested = vestedCoverage(hodlValue, outValue, lastStake.blockTimestamp);
        return
            (vested > cappedCoverage ? cappedCoverage : vested) - (vested * outValue) / hodlValue + coverage[_account];
    }

    /* ========== MUTATIVE FUNCTIONS ========== */

    // Optimized version of this below
    /*
    function getCoverage(
        address _recipient
    ) public nonReentrant updateCoverage(_recipient) {
        require(
            msg.sender == owner() || msg.sender == _recipient,
            "E14"
        );
        require(coverageTokenAddress != address(0), "E23");
        uint256 cov = coverage[_recipient];
        if (cov > 0) {
            coverage[_recipient] = 0;
            IERC20(coverageTokenAddress).safeTransfer(_recipient, cov);
            emit CoveragePaid(_recipient, cov);
        }
    }
    */

    /**
     * @dev claim the coverage for a staker
     * @param _recipient the address of the staker that should receive the coverage
     * @ return the amount of reward received
     */
    function getCoverage(address _recipient) public nonReentrant updateCoverage(_recipient) {
        require(msg.sender == owner() || msg.sender == _recipient, "E14");
        require(coverageTokenAddress != address(0), "E23");

        uint256 cov = coverage[_recipient];
        if (cov == 0) return;

        coverage[_recipient] = 0;
        IERC20(coverageTokenAddress).safeTransfer(_recipient, cov);
        emit CoveragePaid(_recipient, cov);
    }

    /**
     * @dev Set the coverage parameters if none were set in the constructor. Gives the option for farm owners to change coverage tokens.
     * Note: Can't change coverage token if coverage is already accumulated
     * @param _tokenAddress address of token to be used for coverage emissions
     * @param _coverageAmount total amount of coverage token to emit
     * @param _coverageVestingDuration vesting period in seconds that users need to have staked to claim coverage
     */
    function setCoverage(
        address _tokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration
    ) external onlyOwner whenNotEmitting {
        require(coveragePerTokenStored == 0, "E24");
        require(
            (lpToken.token0() == _tokenAddress || lpToken.token1() == _tokenAddress) &&
                (_coverageVestingDuration >= 24 * 3600) &&
                (_coverageVestingDuration <= rewardsDuration),
            "E19"
        );
        coverageTokenAddress = _tokenAddress;
        coverageAmount = _coverageAmount;
        coverageVestingDuration = _coverageVestingDuration;
    }

    // Override startEmission() so it calls the expanded function that includes the coverage amount
    /**
     * @dev Start the emission of rewards to stakers with no coverage. The owner must send reward tokens to the contract before calling this function.
     * Note: Can only be called by owner when the contract is not emitting rewards.
     * @param _rewards array of rewards amounts for each reward token
     * @param _duration duration in seconds for which rewards will be emitted
     */
    function startEmission(
        uint256[] memory _rewards,
        uint256 _duration
    ) public override(StakingRewards, IStakingRewards) onlyOwner {
        return startEmission(_rewards, 0, _duration);
    }

    /**
     * @dev Start the emission of rewards to stakers. The owner must send reward and coverage tokens to the contract before calling this function.
     * Note: Can only be called by owner when the contract is not emitting rewards.
     * @param _rewards array of rewards amounts for each reward token
     * @param _coverage total amount of coverage provided to users (worst case max)
     * @param _duration duration in seconds for which rewards will be emitted (and coverage will be active)
     */
    function startEmission(
        uint256[] memory _rewards,
        uint256 _coverage,
        uint256 _duration
    ) public onlyOwner updateCoverage(address(0)) {
        super.startEmission(_rewards, _duration);
        require(coverageVestingDuration <= rewardsDuration, "E22"); // must check again

        coverageRate = _coverage / rewardsDuration; // rewardsDuration, not coverageVestingDuration which can be shorter!

        if (coverageTokenAddress != address(0) && _coverage > 0) {
            // Ensure the provided coverage amount is not more than the balance in the contract
            uint256 balance = IERC20(coverageTokenAddress).balanceOf(address(this));
            int8 tokenIndex = rewardTokenIndex(coverageTokenAddress);
            if (tokenIndex >= 0) {
                balance -= _rewards[uint256(int256(tokenIndex))];
            }
            require(coverageRate <= balance / rewardsDuration, "E3");
        }
    }

    /**
     * @dev recover leftover coverage tokens and transfer them to a specified recipient
     * Note: can only be called by owner when the contract is not emitting rewards
     * @param _recipient address to receive the recovered coverage tokens
     */
    function recoverLeftoverCoverage(address _recipient) public onlyOwner whenNotEmitting {
        require(totalSupply == 0 && coverageTokenAddress != address(0), "E12/E23");
        _beforeRecoverLeftoverCoverage(_recipient);
        IERC20 token = IERC20(coverageTokenAddress);
        uint256 amount = token.balanceOf(address(this));
        if (amount > 0) {
            token.safeTransfer(_recipient, amount);
            emit LeftoverCoverageRecovered(_recipient, amount);
        }
    }

    /* ========== PRIVATE FUNCTIONS ========== */

    /**
     * @dev Return the LP position for a given amount of LP token.
     * @param _amount the amount of LP token
     * @return the corresponding LP position (amount0, amount1, timestamp)
     */
    function position(uint256 _amount) private view returns (Position memory) {
        (uint112 reserve0, uint112 reserve1, uint32 timestamp) = lpToken.getReserves();
        uint256 totalAmount = lpToken.totalSupply();
        return
            Position(
                uint112((_amount * reserve0) / totalAmount),
                uint112((_amount * reserve1) / totalAmount),
                timestamp
            );
    }

    /**
     * @dev Return the value in WETH of the given LP position.
     * @param _position LP position
     * @return the value in WETH
     */
    function lpValueWeth(Position memory _position) private view returns (uint256) {
        return
            oracle.consultWeth(lpToken.token0(), _position.amount0) +
            oracle.consultWeth(lpToken.token1(), _position.amount1);
    }

    /**
     * @dev Return the vested coverage in coverage token amount for the given HODL and OUT values since the provided timestamp.
     * @param _hodlValue the value (in WETH) if the tokens making up the LP were kept unpaired
     * @param _outValue the value (in WETH) of the LP token position
     * @param _lastTimestamp the start timestamp (when the LP token position was created)
     * @return vested coverage in coverage token amount
     */
    function vestedCoverage(
        uint256 _hodlValue,
        uint256 _outValue,
        uint32 _lastTimestamp
    ) private view returns (uint256) {
        uint256 timeElapsed = block.timestamp - _lastTimestamp;
        uint256 wethCov = _hodlValue > _outValue ? _hodlValue - _outValue : 0;
        uint256 tokenCoverage = wethCov == 0 ? 0 : oracle.consult(oracle.weth(), wethCov, coverageTokenAddress);
        if (timeElapsed >= coverageVestingDuration) {
            return tokenCoverage;
        }
        return (tokenCoverage * timeElapsed) / coverageVestingDuration;
    }

    /* ========== HOOKS ========== */

    /**
     * @dev Override _beforeStake() hook to ensure staking updates the coverage
     */
    function _beforeStake(
        address _account,
        uint256 _amount
    ) internal virtual override updateCoverage(_account) returns (uint256) {
        return super._beforeStake(_account, _amount);
    }

    /**
     * @dev Override _beforeWithdraw() hook to ensure withdrawing updates the coverage
     */
    function _beforeWithdraw(
        address _account,
        uint256 _amount
    ) internal virtual override updateCoverage(_account) returns (uint256) {
        return super._beforeWithdraw(_account, _amount);
    }

    /**
     * @dev Override _beforeExit() hook to claim all coverage for the account exiting
     */
    function _beforeExit(address _account) internal virtual override {
        if (coverageTokenAddress != address(0)) {
            getCoverage(_account);
        }
        super._beforeExit(_account);
    }

    /**
     * @dev Override _beforeRecoverERC20() hook to prevent recovery of a coverage token
     */
    function _beforeRecoverERC20(address _tokenAddress, address _recipient, uint256 _amount) internal virtual override {
        require(_tokenAddress != coverageTokenAddress, "E16");
        super._beforeRecoverERC20(_tokenAddress, _recipient, _amount);
    }

    // New hooks

    /**
     * @dev Internal hook called before recovering leftover coverage (in the recoverLeftoverCoverage() function).
     * @param _recipient address to recover the leftover coverage to
     */
    function _beforeRecoverLeftoverCoverage(address _recipient) internal virtual {}

    /* ========== MODIFIERS ========== */

    /**
     * @dev Modifier to update the coverage of a given account.
     * @param _account account to update coverage for
     */
    modifier updateCoverage(address _account) {
        if (coverageTokenAddress != address(0)) {
            coveragePerTokenStored = coveragePerToken();
            lastUpdateTime = lastTimeRewardApplicable(); // it seems fine to redo this here
            oracle.update(lpToken.token0(), oracle.weth()); // update oracle for first token
            oracle.update(lpToken.token1(), oracle.weth()); // ditto for the second token
            if (_account != address(0)) {
                coverage[_account] = coverageEarned(_account);
                userCoveragePerTokenPaid[_account] = coveragePerTokenStored;
                lastStakedPosition[_account] = position(balances[_account]); // don't forget to reset the last position info
            }
        }
        _;
    }
}

// File: contracts/ElkV2FarmingRewardsPermissoned.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;



/**
 * Contract enabling staking permissions for FarmingRewards.
 */
contract ElkV2FarmingRewardsPermissioned is ElkV2FarmingRewards, IElkV2FarmingRewardsPermissioned {
    mapping(address => bool) public permittedAddresses;

    /* ========== CONSTRUCTOR ========== */

    /**
     * @param _oracleAddress address of the price oracle
     * @param _lpTokenAddress address of the staking LP token (must be an ElkDex LP)
     * @param _coverageTokenAddress address of the token that the coverage is paid in
     * @param _coverageAmount total amount of coverage
     * @param _coverageVestingDuration time it takes to vest 100% of the coverage (min. 1 day)
     * @param _rewardTokenAddresses addresses the reward tokens (must be ERC20)
     * @param _rewardsDuration reward emission duration
     * @param _depositFeeBps deposit fee in basis points
     * @param _withdrawalFeesBps aligned to fee schedule
     * @param _withdrawalFeeSchedule assumes a sorted array
     */
    constructor(
        address _oracleAddress, // address of the price oracle
        address _lpTokenAddress, // address of the staking LP token (must be an ElkDex LP)
        address _coverageTokenAddress, // address of the token that the coverage is paid in
        uint256 _coverageAmount, // total amount of coverage
        uint32 _coverageVestingDuration, // time it takes to vest 100% of the coverage (min. 1 day)
        address[] memory _rewardTokenAddresses, // addresses the reward tokens (must be ERC20)
        uint256 _rewardsDuration, // reward emission duration
        uint16 _depositFeeBps, // deposit fee in basis points
        uint16[] memory _withdrawalFeesBps, // aligned to fee schedule
        uint32[] memory _withdrawalFeeSchedule // assumes a sorted array
    )
        ElkV2FarmingRewards(
            _oracleAddress,
            _lpTokenAddress,
            _coverageTokenAddress,
            _coverageAmount,
            _coverageVestingDuration,
            _rewardTokenAddresses,
            _rewardsDuration,
            _depositFeeBps,
            _withdrawalFeesBps,
            _withdrawalFeeSchedule
        )
    {}

    /**
     * @notice set permission for an address
     * @param _walletAddress wallet address to set permission for
     * @param _permission permission to set
     */
    function setAddressPermission(address _walletAddress, bool _permission) external onlyOwner {
        permittedAddresses[_walletAddress] = _permission;
    }

    /**
     * @dev Override _beforeStake() hook to ensure address is permitted to stake
     */
    function _beforeStake(address _account, uint256 _amount) internal virtual override returns (uint256) {
        require(permittedAddresses[_account], "E25");
        return super._beforeStake(_account, _amount);
    }
}

// File: contracts/ElkV2FactoryHelperPermissioned.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;


/**
 * @title Library containing a helper function that creates new FarmingRewards contracts in the ElkFarmFactory. It was separated out due to contract size limitations.  Farm manager address must be passed in so that the ownership is always transfered to the FarmManager contract.
 */
library ElkV2FactoryHelperPermissioned {
    /**
     * @notice generates a permissioned FarmingRewards contract and transfers ownership to the provided farm manager
     * @param _abi the abi of the FarmingRewards contract
     * @param _salt the salt used to create the contract
     * @param _farmManager the address of the farm manager
     */
    function createFarmContract(
        bytes memory _abi,
        bytes32 _salt,
        address _farmManager
    ) external returns (address addr) {
        bytes memory bytecode = abi.encodePacked(type(ElkV2FarmingRewardsPermissioned).creationCode, _abi);

        assembly {
            addr := create2(0, add(bytecode, 0x20), mload(bytecode), _salt)
            if iszero(extcodesize(addr)) {
                revert(0, 0)
            }
        }

        ElkV2FarmingRewardsPermissioned(addr).transferOwnership(_farmManager);
    }
}

// File: contracts/ElkV2FactoryHelper.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;


/**
 * @title contains a helper function that creates new FarmingRewards contracts in the ElkFarmFactory
 * @notice this is a separate contract so that the FarmFactory contract is not too large
 */
library ElkV2FactoryHelper {
    /**
     * @notice creates a new FarmingRewards contract and transfers ownership to the provided farm manager
     * @param _abi the abi of the FarmingRewards contract
     * @param _salt the salt used to create the contract
     * @param _farmManager the address of the farm manager
     */
    function createFarmContract(
        bytes memory _abi,
        bytes32 _salt,
        address _farmManager
    ) external returns (address addr) {
        bytes memory bytecode = abi.encodePacked(type(ElkV2FarmingRewards).creationCode, _abi);

        assembly {
            addr := create2(0, add(bytecode, 0x20), mload(bytecode), _salt)
            if iszero(extcodesize(addr)) {
                revert(0, 0)
            }
        }

        ElkV2FarmingRewards(addr).transferOwnership(_farmManager);
    }
}

// File: contracts/ElkV2FarmFactory.sol


//
// Copyright (c) 2023 ElkLabs
// License terms: https://github.com/elkfinance/faas/blob/main/LICENSE
//
// Authors:
// - Seth <[email protected]>
// - Baal <[email protected]>
// - Elijah <[email protected]>
// - Snake <[email protected]>

pragma solidity >=0.8.0;









/**
 * Contract that is used by users to create FarmingRewards contracts.
 * It stores each farm as it's created, as well as the current owner of each farm.
 * It also contains various uitlity functions for use by Elk.
 */
contract ElkV2FarmFactory is IElkV2FarmFactory, Ownable {
    using SafeERC20 for IERC20;

    /* ========== STATE VARIABLES ========== */

    /// @notice get list of farms associated with address
    mapping(address => mapping(address => address)) public getFarm;

    /// @notice get list of permissioned farms
    mapping(address => mapping(address => address)) public getPermissionedFarm;

    /// @notice check if given address is a farm
    mapping(address => bool) public isFarm;

    /// @notice check if given address is a permissioned farm
    mapping(address => bool) public isPermissionedFarm;

    /// @notice all farms associated with contract;
    address[] public allFarms;

    /// @notice address of farm manager
    address public farmManager;

    /// @notice get address of farm creator
    mapping(address => address) public getCreator;

    /// @notice ELK token
    IERC20 public feeToken = IERC20(0xeEeEEb57642040bE42185f49C52F7E9B38f8eeeE);

    /// @notice fee in feeToken.
    uint256 public fee = 1000 ether;

    /// @notice maximum allowed fee.
    uint256 public maxFee = 100000 ether;

    /// @notice oracle address
    mapping(address => bool) public whitelistedOracles;

    constructor(address[] memory _oracleAddresses) {
        for (uint i = 0; i < _oracleAddresses.length; ++i) {
            require(_oracleAddresses[i] != address(0), "NO");
            whitelistedOracles[_oracleAddresses[i]] = true;
        }
    }

    /**
     * @notice Main function in the contract. Creates a new FarmingRewards contract, stores the farm address by creator and the given LP token, and also stores the creator of the contract by the new farm address.  This is where the fee is taken from the user.
     * @dev each user is only able to create one FarmingRewards contract per LP token.
     * @param _lpTokenAddress The address of the LP token contract.
     * @param _coverageTokenAddress The address of the ILP coverage token contract.
     * @param _coverageAmount The amount of ILP coverage tokens to be distributed.
     * @param _coverageVestingDuration The duration of the vesting period for the ILP coverage tokens.
     * @param _rewardTokenAddresses The addresses of the reward tokens to be distributed.
     * @param _rewardsDuration The duration of the rewards period.
     * @param _depositFeeBps The deposit fee in basis points.
     * @param _withdrawalFeesBps The withdrawal fees in basis points.
     * @param _withdrawalFeeSchedule The schedule for the withdrawal fees.
     */
    function createNewRewards(
        address _oracleAddress,
        address _lpTokenAddress,
        address _coverageTokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) public {
        require(whitelistedOracles[_oracleAddress], "NW");
        require(getFarm[msg.sender][_lpTokenAddress] == address(0), "FE"); // single check is sufficient

        bytes memory abiCode = abi.encode(
            _oracleAddress,
            _lpTokenAddress,
            _coverageTokenAddress,
            _coverageAmount,
            _coverageVestingDuration,
            _rewardTokenAddresses,
            _rewardsDuration,
            _depositFeeBps,
            _withdrawalFeesBps,
            _withdrawalFeeSchedule
        );
        bytes32 salt = keccak256(abi.encodePacked(_lpTokenAddress, msg.sender));

        _takeFee();

        address addr = ElkV2FactoryHelper.createFarmContract(abiCode, salt, farmManager);

        isFarm[addr] = true;
        getFarm[msg.sender][_lpTokenAddress] = addr;
        getCreator[addr] = msg.sender;
        allFarms.push(addr);

        emit ContractCreated(addr);
    }

    /**
     * @notice Creates a new PermissionedFarmingRewards contract, stores the farm address by creator and the given LP token, and also stores the creator of the contract by the new farm address.  This is where the fee is taken from the user.
     * @dev each user is only able to create one FarmingRewards contract per LP token.
     * @param _lpTokenAddress The address of the LP token contract.
     * @param _coverageTokenAddress The address of the ILP coverage token contract.
     * @param _coverageAmount The amount of ILP coverage tokens to be distributed.
     * @param _coverageVestingDuration The duration of the vesting period for the ILP coverage tokens.
     * @param _rewardTokenAddresses The addresses of the reward tokens to be distributed.
     * @param _rewardsDuration The duration of the rewards period.
     * @param _depositFeeBps The deposit fee in basis points.
     * @param _withdrawalFeesBps The withdrawal fees in basis points.
     * @param _withdrawalFeeSchedule The schedule for the withdrawal fees.
     */
    function createNewPermissonedRewards(
        address _oracleAddress,
        address _lpTokenAddress,
        address _coverageTokenAddress,
        uint256 _coverageAmount,
        uint32 _coverageVestingDuration,
        address[] memory _rewardTokenAddresses,
        uint256 _rewardsDuration,
        uint16 _depositFeeBps,
        uint16[] memory _withdrawalFeesBps,
        uint32[] memory _withdrawalFeeSchedule
    ) public {
        require(whitelistedOracles[_oracleAddress], "NW");
        require(getPermissionedFarm[msg.sender][_lpTokenAddress] == address(0), "PE"); // single check is sufficient

        bytes memory abiCode = abi.encode(
            _oracleAddress,
            _lpTokenAddress,
            _coverageTokenAddress,
            _coverageAmount,
            _coverageVestingDuration,
            _rewardTokenAddresses,
            _rewardsDuration,
            _depositFeeBps,
            _withdrawalFeesBps,
            _withdrawalFeeSchedule
        );
        bytes32 salt = keccak256(abi.encodePacked(_lpTokenAddress, msg.sender));

        _takeFee();

        address addr = ElkV2FactoryHelperPermissioned.createFarmContract(abiCode, salt, farmManager);

        isPermissionedFarm[addr] = true;
        getPermissionedFarm[msg.sender][_lpTokenAddress] = addr;
        getCreator[addr] = msg.sender;
        allFarms.push(addr);

        emit ContractCreated(addr);
    }

    /**
     * @return the number of farms created
     */
    function allFarmsLength() external view override returns (uint) {
        return allFarms.length;
    }

    /**
     * @notice Utility function to be used by Elk.  Changes which manager contract will be assigned ownership of each farm on creation. This is available in case any updates are made to the FarmManager contract.  Ownership is not changed retroactively, so any created farms will always have the same manager contract.
     * @param _managerAddress The address of the new manager contract.
     * @notice emits a ManagerSet event with the new manager address.
     */
    function setManager(address _managerAddress) external override onlyOwner {
        require(_managerAddress != address(0), "NM");
        farmManager = _managerAddress;
        emit ManagerSet(_managerAddress);
    }

    /**
     * @notice Takes fee for contract creation. Factory must be approved to spend the feeToken before creating a new farm.
     */
    function _takeFee() private {
        require(feeToken.balanceOf(msg.sender) >= fee, "NB");
        feeToken.safeTransferFrom(msg.sender, address(this), fee);
    }

    /**
     * @notice Utility function used by Elk to change the fee amount charged on contract creation.  Can never be more than the maxFee set stored in the contract.
     * @param _newFee The new fee amount.
     * @notice emits a FeeSet event with the new fee amount.
     */
    function setFee(uint256 _newFee) external onlyOwner {
        require(_newFee < maxFee, "IF");
        fee = _newFee;
        emit FeeSet(_newFee);
    }

    /**
     * @notice Utility function used by Elk to recover the fees gathered by the factory.
     * @notice emits a FeesRecovered event with the amount recovered.
     */
    function withdrawFees() external onlyOwner {
        uint256 balance = feeToken.balanceOf(address(this));
        feeToken.safeTransfer(msg.sender, balance);
        emit FeesRecovered(balance);
    }

    /**
     * @notice Override ownership of a farm, only used by Elk.
     * @param _farmAddress The address of the farm to be changed.
     */
    function overrideOwnership(address _farmAddress) external onlyOwner {
        _transferFarmOwnership(_farmAddress, msg.sender);
    }

    /**
     * @notice Transfer ownership of a farm (only possible from current owner).
     * @param _farmAddress The address of the farm to be changed.
     * @param _newOwner The address of the new farm owner.
     */
    function transferFarmOwnership(address _farmAddress, address _newOwner) external {
        require(msg.sender == getCreator[_farmAddress], "NF1");
        _transferFarmOwnership(_farmAddress, _newOwner);
    }

    /**
     * @notice Private function that performs a transfer of ownership for a farm.
     */
    function _transferFarmOwnership(address _farmAddress, address _newOwner) private {
        require(isFarm[_farmAddress] || isPermissionedFarm[_farmAddress], "NF2");

        address creatorAddress = getCreator[_farmAddress];

        require(creatorAddress != address(0), "NF3");

        IElkV2FarmingRewards rewardsContract = IElkV2FarmingRewards(_farmAddress);
        address lpTokenAddress = address(rewardsContract.stakingToken());

        if (isFarm[_farmAddress]) {
            getFarm[creatorAddress][lpTokenAddress] = address(0);
            getFarm[_newOwner][lpTokenAddress] = _farmAddress;
            getCreator[_farmAddress] = _newOwner;
        } else {
            getPermissionedFarm[creatorAddress][lpTokenAddress] = address(0);
            getPermissionedFarm[_newOwner][lpTokenAddress] = _farmAddress;
            getCreator[_farmAddress] = _newOwner;
        }
    }
}
        

Contract ABI

[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address[]","name":"_oracleAddresses","internalType":"address[]"}]},{"type":"event","name":"ContractCreated","inputs":[{"type":"address","name":"_newContract","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"FeeSet","inputs":[{"type":"uint256","name":"_newFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"FeesRecovered","inputs":[{"type":"uint256","name":"_balanceRecovered","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ManagerSet","inputs":[{"type":"address","name":"_farmManager","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"allFarms","inputs":[{"type":"uint256","name":"","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"allFarmsLength","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"createNewPermissonedRewards","inputs":[{"type":"address","name":"_oracleAddress","internalType":"address"},{"type":"address","name":"_lpTokenAddress","internalType":"address"},{"type":"address","name":"_coverageTokenAddress","internalType":"address"},{"type":"uint256","name":"_coverageAmount","internalType":"uint256"},{"type":"uint32","name":"_coverageVestingDuration","internalType":"uint32"},{"type":"address[]","name":"_rewardTokenAddresses","internalType":"address[]"},{"type":"uint256","name":"_rewardsDuration","internalType":"uint256"},{"type":"uint16","name":"_depositFeeBps","internalType":"uint16"},{"type":"uint16[]","name":"_withdrawalFeesBps","internalType":"uint16[]"},{"type":"uint32[]","name":"_withdrawalFeeSchedule","internalType":"uint32[]"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"createNewRewards","inputs":[{"type":"address","name":"_oracleAddress","internalType":"address"},{"type":"address","name":"_lpTokenAddress","internalType":"address"},{"type":"address","name":"_coverageTokenAddress","internalType":"address"},{"type":"uint256","name":"_coverageAmount","internalType":"uint256"},{"type":"uint32","name":"_coverageVestingDuration","internalType":"uint32"},{"type":"address[]","name":"_rewardTokenAddresses","internalType":"address[]"},{"type":"uint256","name":"_rewardsDuration","internalType":"uint256"},{"type":"uint16","name":"_depositFeeBps","internalType":"uint16"},{"type":"uint16[]","name":"_withdrawalFeesBps","internalType":"uint16[]"},{"type":"uint32[]","name":"_withdrawalFeeSchedule","internalType":"uint32[]"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"farmManager","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"fee","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC20"}],"name":"feeToken","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getCreator","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getFarm","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getPermissionedFarm","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isFarm","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isPermissionedFarm","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"maxFee","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"overrideOwnership","inputs":[{"type":"address","name":"_farmAddress","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setFee","inputs":[{"type":"uint256","name":"_newFee","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setManager","inputs":[{"type":"address","name":"_managerAddress","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferFarmOwnership","inputs":[{"type":"address","name":"_farmAddress","internalType":"address"},{"type":"address","name":"_newOwner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"whitelistedOracles","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"withdrawFees","inputs":[]}]
            

Contract Creation Code

0x6080604052600880546001600160a01b03191673eeeeeb57642040be42185f49c52f7e9b38f8eeee179055683635c9adc5dea0000060095569152d02c7e14af6800000600a553480156200005257600080fd5b5060405162001c7b38038062001c7b8339810160408190526200007591620001e0565b62000080336200015d565b60005b8151811015620001555760006001600160a01b0316828281518110620000ad57620000ad620002b2565b60200260200101516001600160a01b031603620000f55760405162461bcd60e51b81526020600482015260026024820152614e4f60f01b604482015260640160405180910390fd5b6001600b6000848481518110620001105762000110620002b2565b6020908102919091018101516001600160a01b03168252810191909152604001600020805460ff19169115159190911790556200014d81620002c8565b905062000083565b5050620002f0565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b634e487b7160e01b600052604160045260246000fd5b80516001600160a01b0381168114620001db57600080fd5b919050565b60006020808385031215620001f457600080fd5b82516001600160401b03808211156200020c57600080fd5b818501915085601f8301126200022157600080fd5b815181811115620002365762000236620001ad565b8060051b604051601f19603f830116810181811085821117156200025e576200025e620001ad565b6040529182528482019250838101850191888311156200027d57600080fd5b938501935b82851015620002a6576200029685620001c3565b8452938501939285019262000282565b98975050505050505050565b634e487b7160e01b600052603260045260246000fd5b600060018201620002e957634e487b7160e01b600052601160045260246000fd5b5060010190565b61197b80620003006000396000f3fe608060405234801561001057600080fd5b50600436106101625760003560e01c8063715018a6116100c8578063a1d953f71161008c578063ddca3f4311610066578063ddca3f4314610368578063e9290a6c14610371578063f2fde38b1461038457600080fd5b8063a1d953f7146102fe578063ba7174df14610332578063d0ebdbe71461035557600080fd5b8063715018a6146102a15780637bc6d443146102a95780637fdf1b04146102b15780638da5cb5b146102c4578063a0210309146102d557600080fd5b8063476343ee1161012a578063647846a511610104578063647846a51461024757806369fe0e2d1461025a5780636e5a296a1461026d57600080fd5b8063476343ee146102095780634b2d07cf14610211578063637012c71461022457600080fd5b806301f59d161461016757806320925787146101835780633ae21bb11461019857806343acb9a9146101ab57806343da3ff6146101d6575b600080fd5b610170600a5481565b6040519081526020015b60405180910390f35b6101966101913660046113d0565b610397565b005b6101966101a6366004611409565b6103f9565b6101be6101b936600461142d565b61040e565b6040516001600160a01b03909116815260200161017a565b6101f96101e4366004611409565b600b6020526000908152604090205460ff1681565b604051901515815260200161017a565b610196610438565b6006546101be906001600160a01b031681565b6101f9610232366004611409565b60036020526000908152604090205460ff1681565b6008546101be906001600160a01b031681565b61019661026836600461142d565b6104fe565b6101be61027b3660046113d0565b60026020908152600092835260408084209091529082529020546001600160a01b031681565b610196610571565b600554610170565b6101966102bf36600461160f565b610585565b6000546001600160a01b03166101be565b6101be6102e3366004611409565b6007602052600090815260409020546001600160a01b031681565b6101be61030c3660046113d0565b60016020908152600092835260408084209091529082529020546001600160a01b031681565b6101f9610340366004611409565b60046020526000908152604090205460ff1681565b610196610363366004611409565b6108cc565b61017060095481565b61019661037f36600461160f565b61095d565b610196610392366004611409565b610c8d565b6001600160a01b038281166000908152600760205260409020541633146103eb5760405162461bcd60e51b81526020600482015260036024820152624e463160e81b60448201526064015b60405180910390fd5b6103f58282610d03565b5050565b610401610f38565b61040b8133610d03565b50565b6005818154811061041e57600080fd5b6000918252602090912001546001600160a01b0316905081565b610440610f38565b6008546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015610489573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ad9190611700565b6008549091506104c7906001600160a01b03163383610f92565b6040518181527f6857c770f3cb43e9c19050a37dd914ec876241c1f4b487d26a1d4f5d3054f49b906020015b60405180910390a150565b610506610f38565b600a54811061053c5760405162461bcd60e51b815260206004820152600260248201526124a360f11b60448201526064016103e2565b60098190556040518181527f20461e09b8e557b77e107939f9ce6544698123aad0fc964ac5cc59b7df2e608f906020016104f3565b610579610f38565b6105836000610ffa565b565b6001600160a01b038a166000908152600b602052604090205460ff166105d25760405162461bcd60e51b81526020600482015260026024820152614e5760f01b60448201526064016103e2565b3360009081526001602090815260408083206001600160a01b038d81168552925290912054161561062a5760405162461bcd60e51b8152602060048201526002602482015261464560f01b60448201526064016103e2565b60008a8a8a8a8a8a8a8a8a8a60405160200161064f9a9998979695949392919061178e565b60408051601f19818403018152908290526bffffffffffffffffffffffff1960608d811b8216602085015233901b16603483015291506000906048016040516020818303038152906040528051906020012090506106ab61104a565b60065460405163c82e8b9560e01b815260009173c3d712e6253e33ba3cf361d00ba5382da4d30fb69163c82e8b95916106f691879187916001600160a01b03909116906004016118a5565b602060405180830381865af4158015610713573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073791906118d7565b9050600160036000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff0219169083151502179055508060016000336001600160a01b03166001600160a01b0316815260200190815260200160002060008e6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055503360076000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055506005819080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507fcf78cf0d6f3d8371e1075c69c492ab4ec5d8cf23a1a239b6a51a1d00be7ca312816040516108b591906001600160a01b0391909116815260200190565b60405180910390a150505050505050505050505050565b6108d4610f38565b6001600160a01b03811661090f5760405162461bcd60e51b81526020600482015260026024820152614e4d60f01b60448201526064016103e2565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f60a0f5b9f9e81e98216071b85826681c796256fe3d1354ecb675580fba64fa69906020016104f3565b6001600160a01b038a166000908152600b602052604090205460ff166109aa5760405162461bcd60e51b81526020600482015260026024820152614e5760f01b60448201526064016103e2565b3360009081526002602090815260408083206001600160a01b038d811685529252909120541615610a025760405162461bcd60e51b8152602060048201526002602482015261504560f01b60448201526064016103e2565b60008a8a8a8a8a8a8a8a8a8a604051602001610a279a9998979695949392919061178e565b60408051601f19818403018152908290526bffffffffffffffffffffffff1960608d811b8216602085015233901b1660348301529150600090604801604051602081830303815290604052805190602001209050610a8361104a565b60065460405163c82e8b9560e01b81526000917328462f0898120db3138e5dbbe83f2f62066247229163c82e8b9591610ace91879187916001600160a01b03909116906004016118a5565b602060405180830381865af4158015610aeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b0f91906118d7565b9050600160046000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff0219169083151502179055508060026000336001600160a01b03166001600160a01b0316815260200190815260200160002060008e6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055503360076000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055506005819080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507fcf78cf0d6f3d8371e1075c69c492ab4ec5d8cf23a1a239b6a51a1d00be7ca312816040516108b591906001600160a01b0391909116815260200190565b610c95610f38565b6001600160a01b038116610cfa5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016103e2565b61040b81610ffa565b6001600160a01b03821660009081526003602052604090205460ff1680610d4257506001600160a01b03821660009081526004602052604090205460ff165b610d745760405162461bcd60e51b815260206004820152600360248201526227231960e91b60448201526064016103e2565b6001600160a01b038083166000908152600760205260409020541680610dc25760405162461bcd60e51b81526020600482015260036024820152624e463360e81b60448201526064016103e2565b60008390506000816001600160a01b03166372f702f36040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610e09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2d91906118d7565b6001600160a01b03861660009081526003602052604090205490915060ff1615610ec3576001600160a01b03808416600090815260016020818152604080842086861680865290835281852080546001600160a01b03199081169091558a87168087529484528286209186529083528185208054968c169682168717905594845260079091529091208054909216179055610f31565b6001600160a01b03808416600090815260026020818152604080842086861680865290835281852080546001600160a01b03199081169091558a87168087529484528286209186529083528185208054968c1696821687179055948452600790915290912080549092161790555b5050505050565b6000546001600160a01b031633146105835760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016103e2565b6040516001600160a01b038316602482015260448101829052610ff590849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261110b565b505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6009546008546040516370a0823160e01b81523360048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015611095573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b99190611700565b10156110ec5760405162461bcd60e51b8152602060048201526002602482015261272160f11b60448201526064016103e2565b600954600854610583916001600160a01b0390911690339030906111dd565b6000611160826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661121b9092919063ffffffff16565b805190915015610ff5578080602001905181019061117e91906118f4565b610ff55760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016103e2565b6040516001600160a01b03808516602483015283166044820152606481018290526112159085906323b872dd60e01b90608401610fbe565b50505050565b606061122a8484600085611232565b949350505050565b6060824710156112935760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016103e2565b600080866001600160a01b031685876040516112af9190611916565b60006040518083038185875af1925050503d80600081146112ec576040519150601f19603f3d011682016040523d82523d6000602084013e6112f1565b606091505b50915091506113028783838761130d565b979650505050505050565b6060831561137c578251600003611375576001600160a01b0385163b6113755760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016103e2565b508161122a565b61122a83838151156113915781518083602001fd5b8060405162461bcd60e51b81526004016103e29190611932565b6001600160a01b038116811461040b57600080fd5b80356113cb816113ab565b919050565b600080604083850312156113e357600080fd5b82356113ee816113ab565b915060208301356113fe816113ab565b809150509250929050565b60006020828403121561141b57600080fd5b8135611426816113ab565b9392505050565b60006020828403121561143f57600080fd5b5035919050565b803563ffffffff811681146113cb57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156114995761149961145a565b604052919050565b600067ffffffffffffffff8211156114bb576114bb61145a565b5060051b60200190565b600082601f8301126114d657600080fd5b813560206114eb6114e6836114a1565b611470565b82815260059290921b8401810191818101908684111561150a57600080fd5b8286015b8481101561152e578035611521816113ab565b835291830191830161150e565b509695505050505050565b803561ffff811681146113cb57600080fd5b600082601f83011261155c57600080fd5b8135602061156c6114e6836114a1565b82815260059290921b8401810191818101908684111561158b57600080fd5b8286015b8481101561152e576115a081611539565b835291830191830161158f565b600082601f8301126115be57600080fd5b813560206115ce6114e6836114a1565b82815260059290921b840181019181810190868411156115ed57600080fd5b8286015b8481101561152e5761160281611446565b83529183019183016115f1565b6000806000806000806000806000806101408b8d03121561162f57600080fd5b6116388b6113c0565b995061164660208c016113c0565b985061165460408c016113c0565b975060608b0135965061166960808c01611446565b955060a08b013567ffffffffffffffff8082111561168657600080fd5b6116928e838f016114c5565b965060c08d013595506116a760e08e01611539565b94506101008d01359150808211156116be57600080fd5b6116ca8e838f0161154b565b93506101208d01359150808211156116e157600080fd5b506116ee8d828e016115ad565b9150509295989b9194979a5092959850565b60006020828403121561171257600080fd5b5051919050565b600081518084526020808501945080840160005b8381101561174d57815161ffff168752958201959082019060010161172d565b509495945050505050565b600081518084526020808501945080840160005b8381101561174d57815163ffffffff168752958201959082019060010161176c565b60006101408083016001600160a01b03808f1685526020818f1681870152818e1660408701528c606087015263ffffffff8c1660808701528360a08701528293508a5180845261016087019450818c01935060005b818110156118015784518416865294820194938201936001016117e3565b50505050508660c084015261181c60e084018761ffff169052565b82810361010084015261182f8186611719565b90508281036101208401526118448185611758565b9d9c50505050505050505050505050565b60005b83811015611870578181015183820152602001611858565b50506000910152565b60008151808452611891816020860160208601611855565b601f01601f19169290920160200192915050565b6060815260006118b86060830186611879565b90508360208301526001600160a01b0383166040830152949350505050565b6000602082840312156118e957600080fd5b8151611426816113ab565b60006020828403121561190657600080fd5b8151801515811461142657600080fd5b60008251611928818460208701611855565b9190910192915050565b602081526000611426602083018461187956fea26469706673582212206a7782b806310c93995162b6135ebfe48881d55a1f95c2f63abe53706032619f64736f6c634300081300330000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000100000000000000000000000062dfb99c4d0ac8764b75a132ce0c4c433af46cf4

Deployed ByteCode

0x608060405234801561001057600080fd5b50600436106101625760003560e01c8063715018a6116100c8578063a1d953f71161008c578063ddca3f4311610066578063ddca3f4314610368578063e9290a6c14610371578063f2fde38b1461038457600080fd5b8063a1d953f7146102fe578063ba7174df14610332578063d0ebdbe71461035557600080fd5b8063715018a6146102a15780637bc6d443146102a95780637fdf1b04146102b15780638da5cb5b146102c4578063a0210309146102d557600080fd5b8063476343ee1161012a578063647846a511610104578063647846a51461024757806369fe0e2d1461025a5780636e5a296a1461026d57600080fd5b8063476343ee146102095780634b2d07cf14610211578063637012c71461022457600080fd5b806301f59d161461016757806320925787146101835780633ae21bb11461019857806343acb9a9146101ab57806343da3ff6146101d6575b600080fd5b610170600a5481565b6040519081526020015b60405180910390f35b6101966101913660046113d0565b610397565b005b6101966101a6366004611409565b6103f9565b6101be6101b936600461142d565b61040e565b6040516001600160a01b03909116815260200161017a565b6101f96101e4366004611409565b600b6020526000908152604090205460ff1681565b604051901515815260200161017a565b610196610438565b6006546101be906001600160a01b031681565b6101f9610232366004611409565b60036020526000908152604090205460ff1681565b6008546101be906001600160a01b031681565b61019661026836600461142d565b6104fe565b6101be61027b3660046113d0565b60026020908152600092835260408084209091529082529020546001600160a01b031681565b610196610571565b600554610170565b6101966102bf36600461160f565b610585565b6000546001600160a01b03166101be565b6101be6102e3366004611409565b6007602052600090815260409020546001600160a01b031681565b6101be61030c3660046113d0565b60016020908152600092835260408084209091529082529020546001600160a01b031681565b6101f9610340366004611409565b60046020526000908152604090205460ff1681565b610196610363366004611409565b6108cc565b61017060095481565b61019661037f36600461160f565b61095d565b610196610392366004611409565b610c8d565b6001600160a01b038281166000908152600760205260409020541633146103eb5760405162461bcd60e51b81526020600482015260036024820152624e463160e81b60448201526064015b60405180910390fd5b6103f58282610d03565b5050565b610401610f38565b61040b8133610d03565b50565b6005818154811061041e57600080fd5b6000918252602090912001546001600160a01b0316905081565b610440610f38565b6008546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015610489573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ad9190611700565b6008549091506104c7906001600160a01b03163383610f92565b6040518181527f6857c770f3cb43e9c19050a37dd914ec876241c1f4b487d26a1d4f5d3054f49b906020015b60405180910390a150565b610506610f38565b600a54811061053c5760405162461bcd60e51b815260206004820152600260248201526124a360f11b60448201526064016103e2565b60098190556040518181527f20461e09b8e557b77e107939f9ce6544698123aad0fc964ac5cc59b7df2e608f906020016104f3565b610579610f38565b6105836000610ffa565b565b6001600160a01b038a166000908152600b602052604090205460ff166105d25760405162461bcd60e51b81526020600482015260026024820152614e5760f01b60448201526064016103e2565b3360009081526001602090815260408083206001600160a01b038d81168552925290912054161561062a5760405162461bcd60e51b8152602060048201526002602482015261464560f01b60448201526064016103e2565b60008a8a8a8a8a8a8a8a8a8a60405160200161064f9a9998979695949392919061178e565b60408051601f19818403018152908290526bffffffffffffffffffffffff1960608d811b8216602085015233901b16603483015291506000906048016040516020818303038152906040528051906020012090506106ab61104a565b60065460405163c82e8b9560e01b815260009173c3d712e6253e33ba3cf361d00ba5382da4d30fb69163c82e8b95916106f691879187916001600160a01b03909116906004016118a5565b602060405180830381865af4158015610713573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073791906118d7565b9050600160036000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff0219169083151502179055508060016000336001600160a01b03166001600160a01b0316815260200190815260200160002060008e6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055503360076000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055506005819080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507fcf78cf0d6f3d8371e1075c69c492ab4ec5d8cf23a1a239b6a51a1d00be7ca312816040516108b591906001600160a01b0391909116815260200190565b60405180910390a150505050505050505050505050565b6108d4610f38565b6001600160a01b03811661090f5760405162461bcd60e51b81526020600482015260026024820152614e4d60f01b60448201526064016103e2565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f60a0f5b9f9e81e98216071b85826681c796256fe3d1354ecb675580fba64fa69906020016104f3565b6001600160a01b038a166000908152600b602052604090205460ff166109aa5760405162461bcd60e51b81526020600482015260026024820152614e5760f01b60448201526064016103e2565b3360009081526002602090815260408083206001600160a01b038d811685529252909120541615610a025760405162461bcd60e51b8152602060048201526002602482015261504560f01b60448201526064016103e2565b60008a8a8a8a8a8a8a8a8a8a604051602001610a279a9998979695949392919061178e565b60408051601f19818403018152908290526bffffffffffffffffffffffff1960608d811b8216602085015233901b1660348301529150600090604801604051602081830303815290604052805190602001209050610a8361104a565b60065460405163c82e8b9560e01b81526000917328462f0898120db3138e5dbbe83f2f62066247229163c82e8b9591610ace91879187916001600160a01b03909116906004016118a5565b602060405180830381865af4158015610aeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b0f91906118d7565b9050600160046000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff0219169083151502179055508060026000336001600160a01b03166001600160a01b0316815260200190815260200160002060008e6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055503360076000836001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055506005819080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507fcf78cf0d6f3d8371e1075c69c492ab4ec5d8cf23a1a239b6a51a1d00be7ca312816040516108b591906001600160a01b0391909116815260200190565b610c95610f38565b6001600160a01b038116610cfa5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016103e2565b61040b81610ffa565b6001600160a01b03821660009081526003602052604090205460ff1680610d4257506001600160a01b03821660009081526004602052604090205460ff165b610d745760405162461bcd60e51b815260206004820152600360248201526227231960e91b60448201526064016103e2565b6001600160a01b038083166000908152600760205260409020541680610dc25760405162461bcd60e51b81526020600482015260036024820152624e463360e81b60448201526064016103e2565b60008390506000816001600160a01b03166372f702f36040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610e09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2d91906118d7565b6001600160a01b03861660009081526003602052604090205490915060ff1615610ec3576001600160a01b03808416600090815260016020818152604080842086861680865290835281852080546001600160a01b03199081169091558a87168087529484528286209186529083528185208054968c169682168717905594845260079091529091208054909216179055610f31565b6001600160a01b03808416600090815260026020818152604080842086861680865290835281852080546001600160a01b03199081169091558a87168087529484528286209186529083528185208054968c1696821687179055948452600790915290912080549092161790555b5050505050565b6000546001600160a01b031633146105835760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016103e2565b6040516001600160a01b038316602482015260448101829052610ff590849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261110b565b505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6009546008546040516370a0823160e01b81523360048201526001600160a01b03909116906370a0823190602401602060405180830381865afa158015611095573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b99190611700565b10156110ec5760405162461bcd60e51b8152602060048201526002602482015261272160f11b60448201526064016103e2565b600954600854610583916001600160a01b0390911690339030906111dd565b6000611160826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661121b9092919063ffffffff16565b805190915015610ff5578080602001905181019061117e91906118f4565b610ff55760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016103e2565b6040516001600160a01b03808516602483015283166044820152606481018290526112159085906323b872dd60e01b90608401610fbe565b50505050565b606061122a8484600085611232565b949350505050565b6060824710156112935760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016103e2565b600080866001600160a01b031685876040516112af9190611916565b60006040518083038185875af1925050503d80600081146112ec576040519150601f19603f3d011682016040523d82523d6000602084013e6112f1565b606091505b50915091506113028783838761130d565b979650505050505050565b6060831561137c578251600003611375576001600160a01b0385163b6113755760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016103e2565b508161122a565b61122a83838151156113915781518083602001fd5b8060405162461bcd60e51b81526004016103e29190611932565b6001600160a01b038116811461040b57600080fd5b80356113cb816113ab565b919050565b600080604083850312156113e357600080fd5b82356113ee816113ab565b915060208301356113fe816113ab565b809150509250929050565b60006020828403121561141b57600080fd5b8135611426816113ab565b9392505050565b60006020828403121561143f57600080fd5b5035919050565b803563ffffffff811681146113cb57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156114995761149961145a565b604052919050565b600067ffffffffffffffff8211156114bb576114bb61145a565b5060051b60200190565b600082601f8301126114d657600080fd5b813560206114eb6114e6836114a1565b611470565b82815260059290921b8401810191818101908684111561150a57600080fd5b8286015b8481101561152e578035611521816113ab565b835291830191830161150e565b509695505050505050565b803561ffff811681146113cb57600080fd5b600082601f83011261155c57600080fd5b8135602061156c6114e6836114a1565b82815260059290921b8401810191818101908684111561158b57600080fd5b8286015b8481101561152e576115a081611539565b835291830191830161158f565b600082601f8301126115be57600080fd5b813560206115ce6114e6836114a1565b82815260059290921b840181019181810190868411156115ed57600080fd5b8286015b8481101561152e5761160281611446565b83529183019183016115f1565b6000806000806000806000806000806101408b8d03121561162f57600080fd5b6116388b6113c0565b995061164660208c016113c0565b985061165460408c016113c0565b975060608b0135965061166960808c01611446565b955060a08b013567ffffffffffffffff8082111561168657600080fd5b6116928e838f016114c5565b965060c08d013595506116a760e08e01611539565b94506101008d01359150808211156116be57600080fd5b6116ca8e838f0161154b565b93506101208d01359150808211156116e157600080fd5b506116ee8d828e016115ad565b9150509295989b9194979a5092959850565b60006020828403121561171257600080fd5b5051919050565b600081518084526020808501945080840160005b8381101561174d57815161ffff168752958201959082019060010161172d565b509495945050505050565b600081518084526020808501945080840160005b8381101561174d57815163ffffffff168752958201959082019060010161176c565b60006101408083016001600160a01b03808f1685526020818f1681870152818e1660408701528c606087015263ffffffff8c1660808701528360a08701528293508a5180845261016087019450818c01935060005b818110156118015784518416865294820194938201936001016117e3565b50505050508660c084015261181c60e084018761ffff169052565b82810361010084015261182f8186611719565b90508281036101208401526118448185611758565b9d9c50505050505050505050505050565b60005b83811015611870578181015183820152602001611858565b50506000910152565b60008151808452611891816020860160208601611855565b601f01601f19169290920160200192915050565b6060815260006118b86060830186611879565b90508360208301526001600160a01b0383166040830152949350505050565b6000602082840312156118e957600080fd5b8151611426816113ab565b60006020828403121561190657600080fd5b8151801515811461142657600080fd5b60008251611928818460208701611855565b9190910192915050565b602081526000611426602083018461187956fea26469706673582212206a7782b806310c93995162b6135ebfe48881d55a1f95c2f63abe53706032619f64736f6c63430008130033

External libraries

ElkV2FactoryHelper : 0xc3D712E6253E33Ba3CF361d00Ba5382Da4d30fb6  
ElkV2FactoryHelperPermissioned : 0x28462F0898120Db3138e5dbbE83f2f6206624722