Contract Source Code:
File 1 of 1 : Presale
// SPDX-License-Identifier: UNLICENSED
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
/**
* @dev Required interface of an ERC-721 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 ERC-721 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 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* 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 address zero.
*
* 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: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
/**
* @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) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts (last updated v4.9.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;
}
/**
* @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: nftPreSale.sol
pragma solidity ^0.8.30;
interface INFT is IERC721 {
enum RarityType { Bronze, Silver, Gold, Legendary }
function getRarityType(uint256 tokenId) external view returns (RarityType);
function walletOfOwner(address owner) external view returns (uint256[] memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract Presale is Ownable(msg.sender), ReentrancyGuard {
IERC20 public token;
INFT public nft;
uint256 public tokenPrice; // Price per 1 whole token (10^tokenDecimals units) in wei
uint256 public tokenDecimals;
uint256 public totalTokensForSale;
uint256 public tokensSold = 0;
bool public saleActive = false;
bool public saleFinalized = false;
bool public redeemable = false;
struct WhitelistInfo {
bool isWhitelisted;
uint256 amount;
}
mapping(uint256 => uint256) public rarityToMaxTokens;
mapping(address => WhitelistInfo) public whitelist;
mapping(address => uint256) public tokensPurchased; // Tracks purchased tokens only
mapping(uint256 => uint256) public nftRemainingAllowance; // Tracks remaining allowance per tokenId
mapping(uint256 => bool) public nftInitialized;
event TokensPurchased(address indexed buyer, uint256 amount, uint256[] nftIds);
event RarityMaxTokensUpdated(uint256 rarity, uint256 maxTokens);
event SaleStarted(address token, uint256 totalTokens);
event SaleEnded();
event SaleRedeemable();
event TokensRedeemed(address indexed user, uint256 amount);
event WhitelistUpdated(address indexed user, bool status, uint256 amount);
struct PresaleData {
bool saleActive;
bool saleFinalized;
bool redeemable;
uint256 tokenPrice;
uint256 totalTokensForSale;
uint256 tokensSold;
bool canBuy;
uint256 availableTokens;
bool canRedeem;
uint256 redeemableAmount;
uint256[] tokenIds;
uint256[] allowances;
string[] tokenURIs;
uint256 whitelistAvailable;
bool isWhitelisted;
}
constructor(address _nft, address _token, uint256 _tokenPrice, uint256 _tokenDecimals) {
require(_token != address(0), "Invalid token address");
require(_tokenDecimals > 0, "Invalid decimals");
nft = INFT(_nft);
tokenPrice = _tokenPrice;
token = IERC20(_token);
tokenDecimals = _tokenDecimals;
rarityToMaxTokens[0] = 850_000 * 10**_tokenDecimals; // Bronze
rarityToMaxTokens[1] = 1_700_000 * 10**_tokenDecimals; // Silver
rarityToMaxTokens[2] = 3_400_000 * 10**_tokenDecimals; // Gold
rarityToMaxTokens[3] = 6_800_000 * 10**_tokenDecimals; // Legendary
}
function startSale(uint256 _totalTokensForSale) external onlyOwner {
require(!saleActive, "Sale already active");
require(!saleFinalized, "Sale already finalized");
require(_totalTokensForSale > 0, "Invalid token amount");
totalTokensForSale = _totalTokensForSale;
require(token.transferFrom(msg.sender, address(this), _totalTokensForSale), "Token transfer failed");
saleActive = true;
emit SaleStarted(address(token), _totalTokensForSale);
}
function endSale() external onlyOwner {
require(saleActive, "Sale not active");
saleFinalized = true;
saleActive = false;
emit SaleEnded();
}
function setRedeemable() external onlyOwner {
require(!saleActive, "Sale not active");
require(saleFinalized, "Sale not finalized");
redeemable = true;
emit SaleRedeemable();
}
function updateWhitelist(address[] calldata _users, bool[] calldata _statuses, uint256[] calldata _amounts) external onlyOwner {
require(_users.length == _statuses.length && _users.length == _amounts.length, "Input arrays must have equal length");
for (uint256 i = 0; i < _users.length; i++) {
whitelist[_users[i]] = WhitelistInfo(_statuses[i], _amounts[i]);
emit WhitelistUpdated(_users[i], _statuses[i], _amounts[i]);
}
}
function getPurchaseEligibility(address _user) public view returns (uint256 availableTokens) {
WhitelistInfo memory userInfo = whitelist[_user];
uint256 totalAvailable = 0;
if (userInfo.isWhitelisted) {
totalAvailable += userInfo.amount;
}
uint256[] memory ownedNFTs = nft.walletOfOwner(_user);
for (uint256 i = 0; i < ownedNFTs.length; i++) {
uint256 tokenId = ownedNFTs[i];
uint256 allowance = nftRemainingAllowance[tokenId];
if (!nftInitialized[tokenId]) {
uint256 rarity = uint256(nft.getRarityType(tokenId));
allowance = rarityToMaxTokens[rarity];
}
totalAvailable += allowance;
}
// Cap by remaining tokens in the sale
uint256 remainingTokens = totalTokensForSale - tokensSold;
return totalAvailable > remainingTokens ? remainingTokens : totalAvailable;
}
function buy(uint256 _tokenAmount, uint256[] memory _tokenIds) external payable nonReentrant {
require(saleActive, "Sale not active");
require(tokensSold + _tokenAmount <= totalTokensForSale, "Exceeds available tokens");
require(_tokenAmount > 0, "Amount must be greater than 0");
uint256 wholeTokens = _tokenAmount / 10**tokenDecimals;
uint256 totalCost = wholeTokens * tokenPrice;
require(msg.value >= totalCost, "Insufficient ETH sent");
uint256[] memory finalUsedNFTs = new uint256[](_tokenIds.length);
uint256 tokensToCover = _tokenAmount;
// Validate purchase amount
require(_tokenAmount <= getPurchaseEligibility(msg.sender), "Exceeds available purchase amount");
// Use whitelist amount first
WhitelistInfo memory userInfo = whitelist[msg.sender];
uint256 whitelistUsed = 0;
if (userInfo.isWhitelisted && tokensToCover > 0) {
if (userInfo.amount >= tokensToCover) {
whitelistUsed = tokensToCover;
whitelist[msg.sender].amount -= tokensToCover;
if (whitelist[msg.sender].amount == 0) {
whitelist[msg.sender].isWhitelisted = false;
}
tokensToCover = 0;
} else {
whitelistUsed = userInfo.amount;
tokensToCover -= userInfo.amount;
whitelist[msg.sender].amount = 0;
whitelist[msg.sender].isWhitelisted = false;
}
}
// Use NFT allowances if needed
if (tokensToCover > 0) {
for (uint256 i = 0; i < _tokenIds.length && tokensToCover > 0; i++) {
require(nft.ownerOf(_tokenIds[i]) == msg.sender, "You do not own this NFT");
finalUsedNFTs[i] = _tokenIds[i];
uint256 allowance = nftRemainingAllowance[_tokenIds[i]];
if (!nftInitialized[_tokenIds[i]]) {
uint256 rarity = uint256(nft.getRarityType(_tokenIds[i]));
allowance = rarityToMaxTokens[rarity];
nftRemainingAllowance[_tokenIds[i]] = allowance;
nftInitialized[_tokenIds[i]] = true;
}
if (allowance >= tokensToCover) {
nftRemainingAllowance[_tokenIds[i]] -= tokensToCover;
tokensToCover = 0;
} else {
tokensToCover -= allowance;
nftRemainingAllowance[_tokenIds[i]] = 0;
}
}
require(tokensToCover == 0, "Insufficient NFT allowance");
}
tokensPurchased[msg.sender] += _tokenAmount;
tokensSold += _tokenAmount;
if (msg.value > totalCost) {
payable(msg.sender).transfer(msg.value - totalCost);
}
emit TokensPurchased(msg.sender, _tokenAmount, finalUsedNFTs);
}
function redeemTokens() external nonReentrant {
require(saleFinalized, "Sale not finalized");
require(redeemable, "Sale not redeemable");
require(tokensPurchased[msg.sender] > 0, "No tokens to redeem");
uint256 amount = tokensPurchased[msg.sender];
tokensPurchased[msg.sender] = 0;
require(token.transfer(msg.sender, amount), "Token transfer failed");
emit TokensRedeemed(msg.sender, amount);
}
function getRedeemableTokens(address _user) public view returns (bool canRedeem, uint256 redeemableAmount) {
canRedeem = saleFinalized && redeemable && tokensPurchased[_user] > 0;
redeemableAmount = tokensPurchased[_user];
return (canRedeem, redeemableAmount);
}
function getPresaleData(address _user) external view returns (PresaleData memory) {
uint256[] memory ownedNFTs = nft.walletOfOwner(_user);
uint256[] memory tokenIds = new uint256[](ownedNFTs.length);
uint256[] memory allowances = new uint256[](ownedNFTs.length);
string[] memory tokenURIs = new string[](ownedNFTs.length);
WhitelistInfo memory userInfo = whitelist[_user];
uint256 whitelistAvailable = userInfo.isWhitelisted ? userInfo.amount : 0;
bool isWhiteListed = userInfo.isWhitelisted ? userInfo.isWhitelisted : false;
for (uint256 i = 0; i < ownedNFTs.length; i++) {
uint256 tokenId = ownedNFTs[i];
tokenIds[i] = tokenId;
uint256 allowance = nftRemainingAllowance[tokenId];
if (!nftInitialized[tokenId]) {
uint256 rarity = uint256(nft.getRarityType(tokenId));
allowance = rarityToMaxTokens[rarity];
}
allowances[i] = allowance;
tokenURIs[i] = nft.tokenURI(tokenId);
}
bool canRedeem = saleFinalized && redeemable && tokensPurchased[_user] > 0;
uint256 redeemableAmount = tokensPurchased[_user];
uint256 availableTokens = getPurchaseEligibility(_user);
return PresaleData({
saleActive: saleActive,
saleFinalized: saleFinalized,
redeemable: redeemable,
tokenPrice: tokenPrice,
totalTokensForSale: totalTokensForSale,
tokensSold: tokensSold,
canBuy: availableTokens > 0,
availableTokens: availableTokens,
canRedeem: canRedeem,
redeemableAmount: redeemableAmount,
tokenIds: tokenIds,
allowances: allowances,
tokenURIs: tokenURIs,
whitelistAvailable: whitelistAvailable,
isWhitelisted: isWhiteListed
});
}
function withdrawETH() external onlyOwner {
require(saleFinalized, "Sale not finalized");
payable(owner()).transfer(address(this).balance);
}
function withdrawTokens() external onlyOwner {
require(saleFinalized, "Sale not finalized");
uint256 remainingTokens = totalTokensForSale - tokensSold;
require(token.transfer(owner(), remainingTokens), "Token transfer failed");
}
}