// File: Airdrop.sol



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

/*
                 .'cdO0000OO00KKNNNXKOkdc'.                 
              'cooolc;;lc',l:'':lloxO000KKOdc'              
           'ldoll;.'c..;; .:'  ':..::;cxKKxccddl'           
         ;ddlc'.:;                 ,..;c,cdxddk0Ox:.        
       ;ddc..:,                       ...,::xOo;;lkk;       
     .dx;.;;                             ''.,lk0xlodkd'     
    ;kl;c.                                 .c'.okc,,cO0:    
   ckc'..        .cxd,       'ldOd'          .c:c00ollokl   
  cO;'c.        .dWMMX:     ,0MMMM0'          .'.cko;;;xKl  
 ;Ol;,          ;KMMMMO.    oWMMMMWl           .c'cKkcccdO: 
.ko.,'          :NMMMMK,   .dMMMMMMd            .,;dx.   lk'
lk;:,           ,KMMMMO.    lWMMMMWo             ;,,OklllxKl
ko.'.           .oWMMNl     .OWMMM0'             .:;dO;...dO
0:;:             .ckk:.      .:okd'               ,.cO:...c0
0;'.     .;.                            ':c.      ;::0kllldK
O;c;     cXNOo'                      .cONNx.      ..;Oc   'O
0;..      lW0d,                      .;o0K,       ;::Ol...;0
0c;;      cNl                          .xK,       '.:0xlllkK
ko.,.     ;Xx.                         '0O.      .c;dk.   lO
lk::.     .xX:                         oNl       '.,0Oc::lOo
.ko.:'     'O0,                       cXx.      .::dkc::cOO'
 :Ol,'      'OKc.                   .oKx.      ':.:KkcccdO: 
  cO;,c.     .oKO;.               .cOKc.       ',cko;;:xKl  
   ckc.',      'd0Oo;..      ...:d0Ol.       .c,:00olldOl.  
    ;kl:;.       .;okOkkxddxkOOOko;.       .;.'oOl;;:k0:    
     .dx,'c'         .',::::;'..         ..':cxkdlok0x'     
       ;xd:.'c.                       ...c;;xXkc:cdx:       
        .;ddl:..c. .              .'..c,.:ddlcdKXk:.        
           'ldooc..:, .c. ';..':, 'c,,cokK0xdddl,           
              'cooolc;:l,.:c,,:cccldO0Okxkkdc'.             
                 .,lxO000OOO00KKNNNNX0Oxl,.                 
*/

// BETTER Airdrop

import "./Ownable.sol";
import "./IERC20.sol";
import "./IERC721.sol";

contract Airdrop is Ownable {
    address public signerAddress;
    IERC20 internal better;
    IERC20 internal holdingToken;
    uint256 public tokenMinHold;
    IERC721 internal holdingNFT;
    uint256 public nftMinHold;

    mapping(string => bool) public usedIP;
    mapping(address => bool) public usedAddresses;

    uint256 public totalDropLimit;
    uint256 public userDropLimit;
    uint256 public totalDropped;
    
    event AirDropped(
        address indexed userAddress,
        uint256 amount
    );

    event DropLimitUpdated( uint256 newLimit );
    event TokenHoldingLimitUpdated(uint256 newTokenLimit);
    event NFTHoldingLimitUpdated(uint256 newNFTLimit);
    event UserDropLimitUpdated(uint256 newLimit);

    constructor(address _signerAddress, address _tokenAddress, uint256 userdropLimit_, uint256  totalDropLimit_) {
        require(
            _signerAddress != address(0),
            "Signer Address could not be empty"
        );
        require(
            _tokenAddress != address(0),
            "Token Address could not be empty"
        );

        signerAddress = _signerAddress;
        better = IERC20(_tokenAddress);
        userDropLimit = userdropLimit_;
        totalDropLimit = totalDropLimit_;
    }

    /**
     * @dev public function to get Better token airdrop.
     * takes userIp address and verified signature value as input. 
     */
    function getAirdrop(
        string memory userIP_,
        bytes memory signature_
    ) public returns (bool) {
        require(totalDropped + userDropLimit <= totalDropLimit, "Airdrop max Limit reached");
        require(!usedIP[userIP_], "Ip already used");
        require(!usedAddresses[msg.sender], "Address already used");

        if (tokenMinHold > 0){
            require(holdingToken.balanceOf(msg.sender) >= tokenMinHold, "Not enough token holdings");
        }
        if (nftMinHold > 0){
            require(holdingNFT.balanceOf(msg.sender) >= nftMinHold, "Not enough NFT holdings");
        }

        address recoveredAddress = recoverSigner(
            keccak256(abi.encodePacked(msg.sender, userIP_, userDropLimit)),
            signature_
        );

        require(recoveredAddress == signerAddress, "Invalid signature");
        usedAddresses[msg.sender] = true;
        usedIP[userIP_] = true;
        totalDropped += userDropLimit;

        better.transfer(msg.sender, userDropLimit);
        
        emit AirDropped(msg.sender, userDropLimit);
        return true;
    }

//  ================= Admin functions ========================
    function updateTotalDropLimit(uint256 newLimit_)public onlyOwner returns(bool){
        require (newLimit_ > 0, "Limit can not be zero");
        totalDropLimit = newLimit_;
        emit DropLimitUpdated(newLimit_);
        return true;
    }

    function updateUserDropLimit(uint256 newLimit_)public onlyOwner returns(bool){
        require (newLimit_ > 0, "Limit can not be zero");
        userDropLimit = newLimit_;
        emit UserDropLimitUpdated(newLimit_);
        return true;
    }

//   admin functions to withdraw better tokens out of the contract.
    function adminWithdrawal(address userAddress, uint256 amount)public onlyOwner {
        require(userAddress != address(0), "User Address could not be empty");
        require(amount > 0, "Amount cannot be zero");

        better.transfer(userAddress, amount);
    }

// admin function to update the contract address of holding token
    function updateHoldingTokenAddress(address _tokenAddress) public onlyOwner {
        require(_tokenAddress != address(0), "Invalid token address");
        holdingToken = IERC20(_tokenAddress);
    }

    function updateHoldingTokenAmount(uint256 _amount) public onlyOwner {
        tokenMinHold = _amount;
        emit TokenHoldingLimitUpdated(tokenMinHold);
    }

// admin function to update the contract address of holding NFT token
    function updateHoldingNFTAddress(address _nftAddress) public onlyOwner {
        require(_nftAddress != address(0), "Invalid contract address");
        holdingNFT = IERC721(_nftAddress);
    }

    function updateHoldingNFTAmount(uint256 _amount) public onlyOwner {
        nftMinHold = _amount;
        emit NFTHoldingLimitUpdated(nftMinHold);
    }

// admin function to update the address of message signer.
    function updateSignerAddress(address _signerAddress) public onlyOwner {
        require(
            _signerAddress != address(0),
            "Signer Address could not be empty"
        );
        signerAddress = _signerAddress;
    }

    // ============= helper functions ======================

    function recoverSigner(bytes32 message, bytes memory sig)
        internal
        pure
        returns (address)
    {
        message = prefixed(message);
        uint8 v;
        bytes32 r;
        bytes32 s;

        (v, r, s) = splitSignature(sig);
        return ecrecover(message, v, r, s);
    }

    // Builds a prefixed hash to mimic the behavior of eth_sign.
    function prefixed(bytes32 hash) internal pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
            );
    }

    function splitSignature(bytes memory sig)
        internal
        pure
        returns (
            uint8,
            bytes32,
            bytes32
        )
    {
        require(sig.length == 65);
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            // first 32 bytes, after the length prefix
            r := mload(add(sig, 32))
            // second 32 bytes
            s := mload(add(sig, 64))
            // final byte (first byte of the next 32 bytes)
            v := byte(0, mload(add(sig, 96)))
        }

        return (v, r, s);
    }
}

// File: Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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: IERC165.sol



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

pragma solidity ^0.8.0;

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File: Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./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.
 *
 * 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 () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        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.
     */

    /**
     * @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");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}