// File: src/PreSale.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./Vesting.sol";
import "openzeppelin/token/ERC20/extensions/IERC20Permit.sol";
import "openzeppelin/token/ERC20/IERC20.sol";
import "openzeppelin/access/Ownable.sol";
import "openzeppelin/security/ReentrancyGuard.sol";
import "chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "openzeppelin/security/Pausable.sol";

interface ERC20Interface is IERC20, IERC20Permit {}

contract PreSale is Ownable, Pausable, ReentrancyGuard {

    Vesting public vestingContract;
    ERC20Interface public erc20Token;
    AggregatorV3Interface public aggregator;
    bool public isSaleEnd;
    uint256 public tokenPrice;
    uint256 public maxTokensToSell;
    uint256 public remainingTokens;
    uint256 public duration;
    uint256 public vestingStartDate;
    uint256 public lockDuration;
    uint256 public usdPrice;
    address public treasuryAddress;
    uint256 public maxInt = 2**256 - 1;
    mapping(address => uint256) public usdcAmount;
    mapping(address => uint256) public ethAmount;

    mapping(address => uint256) public vestedAmount;
    mapping(address => bool) public whitelist;

    event TokensPurchased(address buyer, uint256 amount);
    event TokensClaimed(address beneficiary, uint256 amount);

    constructor(address _vestingContract, address _erc20TokenContract, address _aggregatorContract, uint256 _maxTokensToSell, uint256 _tokenPrice, uint256 _usdPrice, uint256 _vestingDuration, uint256 _vestingStartDate, uint256 _lockDuration, address _treasuryAddress) Ownable(msg.sender) {
        require(_treasuryAddress != address(0), "Treasury address cannot be Zero");
        vestingContract = Vesting(_vestingContract);
        tokenPrice = _tokenPrice; // This is the price of Adeno in ERC20 'token bits'
        duration = _vestingDuration;
        vestingStartDate = _vestingStartDate;
        lockDuration = _lockDuration;
        erc20Token = ERC20Interface(_erc20TokenContract);
        aggregator = AggregatorV3Interface(_aggregatorContract);
        maxTokensToSell = _maxTokensToSell;
        remainingTokens = _maxTokensToSell;
        usdPrice = _usdPrice; // This is the USD price for Eth purchases
        isSaleEnd = false;
        treasuryAddress = _treasuryAddress;
    }

    modifier onlySaleEnd() {
        require(isSaleEnd, "Sale has not ended");
        _;
    }

    modifier onlySaleNotEnd() {
        require(!isSaleEnd, "Sale is not running");
        _;
    }

    modifier onlyWhitelisted() {
        require(whitelist[msg.sender], "Sender is not whitelisted");
        _;
    }

    function purchaseTokensWithUSDC(uint256 _numberOfTokens)
        external
        onlySaleNotEnd
        onlyWhitelisted
        nonReentrant
    {
        uint256 _tokensToBuy = _numberOfTokens * 10**18;
        require(_numberOfTokens > 0, "Number of tokens must be greater than zero");
        require(remainingTokens >= _tokensToBuy, "Insufficient tokens available for sale");
        require(duration > 0, "Duration must be greater than zero");

        uint256 usdcValue = _numberOfTokens * tokenPrice;
        uint256 allowance = erc20Token.allowance(msg.sender, address(this));
        require(allowance >= usdcValue, "Check the token allowance");
        bool success = erc20Token.transferFrom(msg.sender, address(this), usdcValue);
        require(success, "Transaction was not successful");
        usdcAmount[msg.sender] = usdcAmount[msg.sender] + usdcValue;

        vestedAmount[msg.sender] = vestedAmount[msg.sender] + _tokensToBuy;

        vestingContract.createVestingSchedule(
            msg.sender,
            _tokensToBuy,
            duration, // Number of months for the release period
            vestingStartDate, // Start time of the vesting schedule
            lockDuration // Number of months before vesting period begins
        );

        remainingTokens = remainingTokens - _tokensToBuy;

        emit TokensPurchased(msg.sender, _tokensToBuy);
    }

    function permitAndPurchaseTokensWithUSDC(uint256 _numberOfTokens, uint8 v, bytes32 r, bytes32 s)
        external
        onlySaleNotEnd
        onlyWhitelisted
        nonReentrant
    {
        uint256 _tokensToBuy = _numberOfTokens * 10**18;
        require(_numberOfTokens > 0, "Number of tokens must be greater than zero");
        require(remainingTokens >= _tokensToBuy, "Insufficient tokens available for sale");
        require(duration > 0, "Duration must be greater than zero");

        uint256 usdcValue = _numberOfTokens * tokenPrice;
        erc20Token.permit(msg.sender, address(this), usdcValue, uint256(maxInt), v, r, s);
        bool success = erc20Token.transferFrom(msg.sender, address(this), usdcValue);
        require(success, "Transaction was not successful");
        usdcAmount[msg.sender] = usdcAmount[msg.sender] + usdcValue;

        vestedAmount[msg.sender] = vestedAmount[msg.sender] + _tokensToBuy;

        vestingContract.createVestingSchedule(
            msg.sender,
            _tokensToBuy,
            duration, // Number of months for the release period
            vestingStartDate, // Start time of the vesting schedule
            lockDuration // Number of months before vesting period begins
        );

        remainingTokens = remainingTokens - _tokensToBuy;

        emit TokensPurchased(msg.sender, _tokensToBuy);
    }

    function purchaseTokensWithEth(uint256 _numberOfTokens)
        external payable
        onlySaleNotEnd
        onlyWhitelisted
        nonReentrant
    {
        uint256 _tokensToBuy = _numberOfTokens * 10**18;
        (, int256 price, , , ) = aggregator.latestRoundData();
        require(price >= 0, "Price value must be positive");
        uint256 ethValue = (usdPrice * _tokensToBuy) / uint256(price);
        require(msg.value >= ethValue, "Insufficient Eth for purchase");
        require(_numberOfTokens > 0, "Number of tokens must be greater than zero");
        require(remainingTokens >= _tokensToBuy, "Insufficient tokens available for sale");
        require(duration > 0, "Duration must be greater than zero");
        uint256 excess = msg.value - ethValue;
        ethAmount[msg.sender] = ethAmount[msg.sender] + ethValue;

        vestedAmount[msg.sender] = vestedAmount[msg.sender] + _tokensToBuy;

        vestingContract.createVestingSchedule(
            msg.sender,
            _tokensToBuy,
            duration, // Number of months for the release period
            vestingStartDate, // Start time of the vesting schedule
            lockDuration // Number of months before vesting period begins
        );

        remainingTokens = remainingTokens - _tokensToBuy;
        if (excess > 0) {
            require(address(this).balance >= excess, "Not enough Eth to make the transfer");
            (bool success, ) = payable(msg.sender).call{value: excess}("");
            require(success, "ETH transfer failed");
        }
        emit TokensPurchased(msg.sender, _tokensToBuy);
    }

    function changeAggregatorInterface(address _address) external onlyOwner {
        aggregator = AggregatorV3Interface(_address);
    }

    function seeVestingSchedule() external view returns (uint256, uint256, uint256, uint256, uint256) {
        return vestingContract.vestingSchedules(address(this), msg.sender);
    }

    function seeClaimableTokens() external view returns (uint256 releasableTokens) {
        releasableTokens = vestingContract.getReleasableTokens(address(this), msg.sender);
    }

    function claimVestedTokens() external onlySaleEnd {
        require(vestedAmount[msg.sender] > 0, "No tokens available to claim");
        uint256 releasableTokens = vestingContract.getReleasableTokens(address(this), msg.sender);
        require(releasableTokens > 0, "No tokens available for release");
        vestingContract.releaseTokens(address(this), msg.sender);
        emit TokensClaimed(msg.sender, releasableTokens);
    }

    function refundPurchase(address _buyer) external onlySaleNotEnd nonReentrant onlyOwner {
        (uint256 totalTokens,,, uint256 releasedTokens,) = vestingContract.vestingSchedules(address(this), _buyer);
        require(totalTokens != 0, "Nothing to refund");
        require(releasedTokens == 0, "Tokens have already been claimed");
        bool refundEth;
        bool refundUSDC;
        uint256 ethToRefund = 0;
        uint256 usdcToRefund = 0;
        if(ethAmount[_buyer] > 0) {
            require(address(this).balance >= ethAmount[_buyer], "Not enough Eth to make the transfer");
            ethToRefund = ethAmount[_buyer];
            ethAmount[_buyer] = 0;
            refundEth = true;
        }
        if(usdcAmount[_buyer] > 0) {
            require(erc20Token.balanceOf(address(this)) >= usdcAmount[_buyer], "Not enough USDC to make the transfer");
            usdcToRefund = usdcAmount[_buyer];
            usdcAmount[_buyer] = 0;
            refundUSDC = true;
        }
        remainingTokens = remainingTokens + vestedAmount[_buyer];
        vestedAmount[_buyer] = 0;
        vestingContract.removeVestingSchedule(address(this), _buyer);
        if(refundEth) {
            (bool success, ) = payable(_buyer).call{value: ethToRefund}("");
            require(success, "ETH transfer failed");
        }
        if(refundUSDC) {
            require(erc20Token.transfer(_buyer, usdcToRefund), "USDC transfer failed");
        }
    }

    function addToWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = true;
        }
    }

    function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = false;
        }
    }

    function setSaleEnd() external onlyOwner {
        isSaleEnd = !isSaleEnd;
    }

    function transferRemaining() external onlySaleEnd onlyOwner {
        require(remainingTokens > 0, "No tokens remaining");
        uint256 vestingAmount = remainingTokens;
        remainingTokens = 0;
        vestingContract.createVestingSchedule(
            treasuryAddress,
            vestingAmount,
            1,
            vestingStartDate,
            0
        );
    }

    function updateTreasuryAddress(address treasuryAddr) external onlyOwner {
        require(treasuryAddr != address(0), "Treasury address cannot be Zero");
        treasuryAddress = treasuryAddr;
    }

    function updateVestingAddress(address vestingAddr) external onlyOwner {
        require(vestingAddr != address(0), "Vesting address cannot be Zero");
        vestingContract = Vesting(vestingAddr);
    }

    function updateUSDCAddress(address erc20Addr) external onlyOwner {
        require(erc20Addr != address(0), "ERC20 address cannot be Zero");
        erc20Token = ERC20Interface(erc20Addr);
    }

    function updateAggregatorAddress(address aggregatorAddr) external onlyOwner {
        require(aggregatorAddr != address(0), "Aggregator address cannot be Zero");
        aggregator = AggregatorV3Interface(aggregatorAddr);
    }

    function updateTokenPrice(uint256 _tokenPrice) external onlyOwner {
        tokenPrice = _tokenPrice; // This is the price of Adeno in ERC20 'token bits'
    }

    function updateEthPrice(uint256 _usdPrice) external onlyOwner {
        usdPrice = _usdPrice; // This is the USD price for Eth purchases
    }

    function withdrawUSDC() external onlySaleEnd nonReentrant onlyOwner {
        require(erc20Token.balanceOf(address(this)) > 0, "No USDC to withdraw");
        require(erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))));
    }

    function withdrawEth() external onlySaleEnd nonReentrant onlyOwner {
        require(address(this).balance > 0, "No Eth to withdraw");
        (bool sent,) = payable(msg.sender).call{value: address(this).balance}("");
        require(sent);
    }
}

// File: src/Vesting.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "openzeppelin/token/ERC20/IERC20.sol";
import "openzeppelin/access/Ownable.sol";
import "openzeppelin/security/Pausable.sol";

contract Vesting is Ownable, Pausable {

    // Number of seconds in 365 days, divided by 12:
    uint256 public constant SECONDS_PER_MONTH = 2628000;

    // Mapping of plan id to start date. All beneficiaries of a specific plan would have the same start time
    mapping(uint256 => uint256) public startDates;
    struct VestingSchedule {
        uint256 totalTokens; // amount of tokens for a recipient
        uint256 releasePeriod; // Number of months for the release period
        uint256 startDate; // The plan number for the start time of the vesting schedule
        uint256 releasedTokens; // Number of tokens released so far
        uint256 lockDuration; // Number of months for the release period
    }
    uint256 public tokensVested;

    // privatesale addr => (user addr => schedule)
    mapping(address => mapping(address => VestingSchedule)) public vestingSchedules;

    // privatesale addr => bool
    mapping(address => bool) public vestingSchedulesActive;
    mapping(address => bool) public whitelist;

    IERC20 public token;

    event TokensReleased(address beneficiary, uint256 amount);
    event VestingScheduleCreated(address beneficiary, uint256 totalTokens, uint256 startDate, uint256 lockDuration);
    event VestingScheduleUpdated(address beneficiary, uint256 totalTokens);

    constructor(address _token) Ownable(msg.sender) {
        token = IERC20(_token);
    }

    function createVestingSchedule(address beneficiary, uint256 totalTokens, uint256 releasePeriod, uint256 startDate, uint256 lockDuration)
        external
        onlyWhitelisted
        whenNotPaused
    {
        require(totalTokens > 0, "Total tokens must be greater than zero");
        require(releasePeriod > 0, "Release period must be greater than zero");
        require((totalTokens + tokensVested) <= token.balanceOf(address(this)), "Not enough tokens for vesting");
        require(
            vestingSchedules[msg.sender][beneficiary].releasedTokens == 0,
            "Vesting schedule already in use, for the beneficiary"
        );
        VestingSchedule storage schedule = vestingSchedules[msg.sender][beneficiary];
        if(vestingSchedules[msg.sender][beneficiary].totalTokens == 0) {
            schedule.totalTokens = totalTokens;
            schedule.releasePeriod = releasePeriod;
            schedule.startDate = startDate;
            schedule.lockDuration = lockDuration;
            emit VestingScheduleCreated(beneficiary, schedule.totalTokens, startDates[schedule.startDate], schedule.lockDuration);
        } else {
            schedule.totalTokens = schedule.totalTokens + totalTokens;
            emit VestingScheduleUpdated(beneficiary, totalTokens);
        }
        tokensVested = tokensVested + totalTokens;
    }

    function removeVestingSchedule(address contractAddress, address beneficiary)
        external
        whenNotPaused
        onlyWhitelisted
    {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        uint256 tokensLeft = schedule.totalTokens - schedule.releasedTokens;
        tokensVested = tokensVested - tokensLeft;
        delete vestingSchedules[contractAddress][beneficiary];
    }

    function releaseTokens(address contractAddress, address beneficiary) external whenNotPaused onlyWhitelisted {
        require(vestingSchedulesActive[contractAddress] == true, "Vesting schedule not active");
        uint256 releasableTokens = getReleasableTokens(contractAddress, beneficiary);
        require(releasableTokens > 0, "No tokens available for release");
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        schedule.releasedTokens = schedule.releasedTokens + releasableTokens;
        tokensVested = tokensVested - releasableTokens;
        token.transfer(beneficiary, releasableTokens);
        emit TokensReleased(beneficiary, releasableTokens);
    }

    function getReleasableTokens(address contractAddress, address beneficiary) public view returns (uint256) {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        require(schedule.totalTokens > 0, "No vesting schedule found for the beneficiary");
        uint256 tokensToClaim;
        uint256 claimingStartTime = startDates[schedule.startDate] + (schedule.lockDuration * SECONDS_PER_MONTH);
        if(block.timestamp <= claimingStartTime) {
            tokensToClaim = 0;
        } else {
            uint256 elapsedTime = block.timestamp - claimingStartTime;
            uint256 totalReleasePeriods = schedule.releasePeriod;
            uint256 totalTokens = schedule.totalTokens;
            uint256 tokensPerPeriod = totalTokens / totalReleasePeriods;
            uint256 passedMonths = (elapsedTime / SECONDS_PER_MONTH) >= totalReleasePeriods
                ? totalReleasePeriods
                : elapsedTime / SECONDS_PER_MONTH;
            uint256 tokensToRelease = passedMonths * (tokensPerPeriod);

            if(passedMonths == 0) {
                tokensToClaim = 0;
            } else {
                tokensToClaim = passedMonths == totalReleasePeriods
                    ? totalTokens - schedule.releasedTokens
                    : tokensToRelease - schedule.releasedTokens;
            }
        }
        return tokensToClaim;
    }

    function getNextClaimableTime(address contractAddress, address beneficiary, uint256 dateID) external view returns (uint256) {
        VestingSchedule storage schedule = vestingSchedules[contractAddress][beneficiary];
        uint256 current_time = block.timestamp;
        uint256 timeRemaining;
        uint256 claimingStartTime = startDates[dateID] + (schedule.lockDuration * SECONDS_PER_MONTH);
        if(current_time > ((schedule.releasePeriod * SECONDS_PER_MONTH) + claimingStartTime)) {
            timeRemaining = 0;
        } else {
            if(current_time >= claimingStartTime) {
                uint256 diff = current_time - claimingStartTime;
                uint256 current_multiple = diff / SECONDS_PER_MONTH;
                uint256 timer_start = (current_multiple * SECONDS_PER_MONTH) + claimingStartTime;
                uint256 current_progress_in_month = current_time - timer_start;
                timeRemaining = SECONDS_PER_MONTH - current_progress_in_month;
            } else {
                timeRemaining = claimingStartTime - current_time;
            }
        }
        return timeRemaining;
    }

    modifier onlyWhitelisted() {
        require(whitelist[msg.sender], "Sender is not whitelisted");
        _;
    }

    function updateStartDate(uint256 dateId, uint256 startDate) external onlyOwner {
        startDates[dateId] = startDate;
    }

    function addToWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = true;
        }
    }

    function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
        for (uint256 i = 0; i < addresses.length; i++) {
            address addr = addresses[i];
            whitelist[addr] = false;
        }
    }

    function setVestingSchedulesActive(address contractAddress, bool active) external onlyOwner {
        vestingSchedulesActive[contractAddress] = active;
    }

    function updateTokenAddress(address tokenAddr) external onlyOwner {
        require(tokenAddr != address(0), "Token address cannot be Zero");
        token = IERC20(tokenAddr);
    }

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @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: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

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

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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: lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    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
        if (_status == _ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: lib/chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(
    uint80 _roundId
  ) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

  function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

// File: lib/openzeppelin-contracts/contracts/security/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: lib/openzeppelin-contracts/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.20;

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