// File: interfaces.sol



// SPDX-License-Identifier: UNLICENSE

pragma solidity ^0.8.7;

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

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

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

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

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

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

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

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

// Reflection
interface IReflect {
    function tokenFromReflection(uint256 rAmount)
        external
        view
        returns (uint256);

    function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
        external
        view
        returns (uint256);

    function getRate() external view returns (uint256);
}

/// ChainLink ETH/USD oracle
interface IChainLink {
    // chainlink ETH/USD oracle
    // answer|int256 :  216182781556 - 8 decimals
    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

/// USDT is not ERC-20 compliant, not returning true on transfers
interface IUsdt {
    function transfer(address, uint256) external;

    function transferFrom(
        address,
        address,
        uint256
    ) external;
}

// Check ETH send to first presale
// Yes, there is a typo
interface IPresale1 {
    function blanceOf(address user) external view returns (uint256 amt);
}

// Check tokens bought in second presale
// There is bug in ETH deposits, we need handle it
// Also "tokensBoughtOf" calculation is broken, so we do all math
interface IPresale2 {
    function ethDepositOf(address user) external view returns (uint256 amt);

    function usdDepositOf(address user) external view returns (uint256 amt);
}

// Check final sale tokens bought
interface ISale {
    function tokensBoughtOf(address user) external view returns (uint256 amt);
}

interface IClaimSale {
    function addLock(
        address user,
        uint256 reflection,
        uint256 locktime
    ) external;
}

// File: owned.sol



// SPDX-License-Identifier: UNLICENSE

pragma solidity ^0.8.7;

contract Owned {
    address public owner;
    address public newOwner;

    event OwnershipChanged(address from, address to);

    constructor() {
        owner = msg.sender;
        emit OwnershipChanged(address(0), msg.sender);
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Only owner");
        _;
    }

    // owner can give super-rights to someone
    function giveOwnership(address user) external onlyOwner {
        require(user != address(0), "User renounceOwnership");
        newOwner = user;
    }

    // new owner need to accept
    function acceptOwnership() external {
        require(msg.sender == newOwner, "Only NewOwner");
        emit OwnershipChanged(owner, newOwner);
        owner = msg.sender;
        delete newOwner;
    }
}

// File: public-claim.sol



// SPDX-License-Identifier: UNLICENSE
// Rzucam 70mln worków w tłum w tłum .. kto łapie ten jara ... XD

/**
Apes Together Strong!

About BigShortBets DeFi project:

We are creating a social&trading p2p platform that guarantees encrypted interaction between investors.
Logging in is possible via a cryptocurrency wallet (e.g. Metamask).
The security level is one comparable to the Tor network.

https://bigsb.io/ - Our Tool
https://bigshortbets.com - Project&Team info

Video explainer:
https://youtu.be/wbhUo5IvKdk

Zaorski, You Son of a bitch I’m in …
*/

pragma solidity 0.8.7;
import "./owned.sol";
import "./reentryGuard.sol";
import "./interfaces.sol";

contract BigSBsaleClaim is Owned, Guarded {
    /**
        Claiming contract for BigSB public sale
        @param sale address of sale contract
        @param token address of BigSB token tontract
     */
    constructor(address sale, address token) {
        saleContract = sale;
        tokenContract = token;
        emergencyUnlock = block.timestamp + 720 days;
    }

    /// timestamp moving 2 years of last lock made
    uint256 public emergencyUnlock;

    address public immutable tokenContract;
    address public immutable saleContract;

    struct Lock {
        uint256 reflection;
        uint256 locktime;
    }

    /// Storage of user locks by address
    mapping(address => Lock[]) public userLocks;

    /**
        Add lock for user, can be called only by sale contract.
        Using contract reflection rate it can earn from transfer fees.
        @param user address of user
        @param reflection amount of reflection tokens
        @param locktime timestamp after which tokens can be released
     */
    function addLock(
        address user,
        uint256 reflection,
        uint256 locktime
    ) external {
        require(msg.sender == saleContract, "Only sale contract");
        userLocks[user].push(Lock(reflection, locktime));
        emergencyUnlock = block.timestamp + 720 days;
    }

    /// claim all tokens than can be claimed
    function claim() external guarded {
        uint256 len = userLocks[msg.sender].length;
        require(len > 0, "Nothing locked");
        uint256 i;
        uint256 timeNow = block.timestamp;
        uint256 amt;
        for (i; i < len; i++) {
            Lock memory l = userLocks[msg.sender][i];
            if (timeNow > l.locktime && l.reflection > 0) {
                amt += IReflect(tokenContract).tokenFromReflection(
                    l.reflection
                );
                // tokens taken
                userLocks[msg.sender][i].reflection = 0;
            }
        }
        require(amt > 0, "Nothing to claim");
        IERC20(tokenContract).transfer(msg.sender, amt);
    }

    /// return all user locks
    function getUserLocks(address user) external view returns (Lock[] memory) {
        return userLocks[user];
    }

    /// return balance of user from all locks
    function balanceOf(address user) external view returns (uint256 amt) {
        uint256 len = userLocks[user].length;
        if (len == 0) return amt;
        uint256 i;
        for (i; i < len; i++) {
            amt += IReflect(tokenContract).tokenFromReflection(
                userLocks[user][i].reflection
            );
        }
        return amt;
    }

    /// How many tokens user can claim now?
    function claimable(address user) external view returns (uint256 amt) {
        uint256 len = userLocks[user].length;
        if (len == 0) return amt;
        uint256 i;
        uint256 timeNow = block.timestamp;
        for (i; i < len; i++) {
            Lock memory l = userLocks[user][i];
            if (timeNow > l.locktime) {
                amt += IReflect(tokenContract).tokenFromReflection(
                    l.reflection
                );
            }
        }
        return amt;
    }

    //
    // Emergency functions
    //
    /**
        Take ETH from contract
    */
    function withdrawEth() external onlyOwner {
        payable(owner).transfer(address(this).balance);
    }

    /**
        Take any ERC20 from contract
        BigSB is possible after 2 years form last lock event
    */
    function withdrawErc20(address token) external onlyOwner {
        if (token == tokenContract) {
            require(block.timestamp > emergencyUnlock, "Too soon");
        }
        uint256 balance = IERC20(token).balanceOf(address(this));
        require(balance > 0, "Nothing to withdraw");
        // use broken IERC20
        IUsdt(token).transfer(owner, balance);
    }
}
//This is fine!

// File: reentryGuard.sol



// SPDX-License-Identifier: UNLICENSE

pragma solidity ^0.8.7;

contract Guarded {
    uint256 constant NOT_ENTERED = 1;
    uint256 constant ENTERED = 2;
    uint256 entryState = NOT_ENTERED;

    modifier guarded() {
        require(entryState == NOT_ENTERED, "Reentry");
        entryState = ENTERED;
        _;
        entryState = NOT_ENTERED;
    }
}