Skip to content
Verified contractPartialMIT

VestingTokenSale

Address0x49cd7276d8ea8f00375bfeccc69509adbb52d455
Balance

0 ETH

 

Transactions

7

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
No
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,590,795
Creation transaction
0x8356aacb30…b498b953d0

purchase.sol

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

/// @notice Minimal ERC-20 interface. Tokens are handled through SafeERC20 below,
/// including tokens that do not return a boolean value.
interface IERC20 {
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

library SafeERC20 {
    error ERC20CallFailed(address token, bytes data);

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

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

    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        (bool success, bytes memory returndata) = address(token).call(data);
        if (!success || (returndata.length != 0 && !abi.decode(returndata, (bool)))) {
            revert ERC20CallFailed(address(token), data);
        }
    }
}

/// @notice Full precision multiplication/division adapted from OpenZeppelin's Math.mulDiv.
library FullMath {
    error MathOverflowedMulDiv();

    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            uint256 prod0 = x * y;
            uint256 prod1;
            assembly ("memory-safe") {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }
            if (prod1 == 0) return prod0 / denominator;
            if (denominator <= prod1) revert MathOverflowedMulDiv();

            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(x, y, denominator)
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }
            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
                prod0 := div(prod0, twos)
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;
            uint256 inverse = (3 * denominator) ^ 2;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            inverse *= 2 - denominator * inverse;
            return prod0 * inverse;
        }
    }

    function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (mulmod(x, y, denominator) > 0) {
            if (result == type(uint256).max) revert MathOverflowedMulDiv();
            result++;
        }
        return result;
    }
}

/// @title VestingTokenSale - single-file token purchase and vesting contract
/// @notice Sells ERC-20 tokens held by this contract, accepting only Ethereum-mainnet USDC or USDT.
/// @dev This contract intentionally has no proxy, delegatecall, signature, or upgrade entry point.
contract VestingTokenSale {
    using SafeERC20 for IERC20;

    uint256 public constant CLIFF = 365 days;
    uint256 public constant VESTING_INTERVAL = 30 days;
    uint256 public constant VESTING_PERIODS = 10;
    // Official Ethereum mainnet token contracts. This contract is intentionally mainnet-specific.
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;

    address public admin;
    address public pendingAdmin;
    IERC20 public immutable saleToken;
    uint8 public immutable saleTokenDecimals;
    uint256 public immutable saleTokenUnit;
    uint256 public minPurchaseAmount;
    /// @notice Sale-token amount promised to buyers but not yet claimed.
    uint256 public totalOutstanding;
    bool public saleActive;
    uint256 private _entered;

    // Both supported payment tokens use 6 decimals on Ethereum mainnet.
    // pricePerSaleToken is in the payment token's smallest unit.
    struct PaymentOption {
        bool enabled;
        uint256 pricePerSaleToken;
    }

    struct Lock {
        uint128 amount;
        uint128 claimed;
        uint64 purchasedAt;
    }

    mapping(address paymentToken => PaymentOption) public paymentOptions;
    mapping(address buyer => Lock[]) private _locks;

    error Unauthorized();
    error ZeroAddress();
    error InvalidDecimals();
    error InvalidAmount();
    error InvalidPrice();
    error SaleNotActive();
    error PaymentNotSupported();
    error Reentrancy();
    error InvalidLock();
    error NothingToClaim();
    error InsufficientInventory(uint256 available, uint256 required);
    error AmountTooLarge();
    error SaleTokenCannotBePaymentToken();
    error IncorrectErc20Payment(uint256 expected, uint256 received);
    error PaymentExceedsMaximum(uint256 required, uint256 maximum);
    error UnsupportedPaymentToken(address token);

    event AdminTransferStarted(address indexed currentAdmin, address indexed pendingAdmin);
    event AdminTransferred(address indexed oldAdmin, address indexed newAdmin);
    event SaleStatusChanged(bool active);
    event MinPurchaseAmountChanged(uint256 oldAmount, uint256 newAmount);
    event PaymentOptionSet(address indexed paymentToken, bool enabled, uint256 pricePerSaleToken);
    event Purchased(address indexed buyer, address indexed paymentToken, uint256 saleAmount, uint256 paymentAmount, uint256 lockId);
    event Claimed(address indexed buyer, uint256 indexed lockId, uint256 amount);
    event InventoryWithdrawn(address indexed recipient, uint256 amount);
    event PaymentWithdrawn(address indexed paymentToken, address indexed recipient, uint256 amount);

    modifier onlyAdmin() {
        if (msg.sender != admin) revert Unauthorized();
        _;
    }

    modifier nonReentrant() {
        if (_entered == 1) revert Reentrancy();
        _entered = 1;
        _;
        _entered = 0;
    }

    constructor(address saleToken_, uint8 saleTokenDecimals_, uint256 minPurchaseAmount_, address initialAdmin) {
        if (saleToken_ == address(0) || initialAdmin == address(0)) revert ZeroAddress();
        if (saleTokenDecimals_ > 77) revert InvalidDecimals(); // 10**77 is the largest safe decimal power in uint256.
        if (minPurchaseAmount_ == 0) revert InvalidAmount();
        saleToken = IERC20(saleToken_);
        saleTokenDecimals = saleTokenDecimals_;
        saleTokenUnit = 10 ** saleTokenDecimals_;
        minPurchaseAmount = minPurchaseAmount_;
        admin = initialAdmin;
    }

    function transferAdmin(address newPendingAdmin) external onlyAdmin {
        if (newPendingAdmin == address(0)) revert ZeroAddress();
        pendingAdmin = newPendingAdmin;
        emit AdminTransferStarted(admin, newPendingAdmin);
    }

    function acceptAdmin() external {
        if (msg.sender != pendingAdmin) revert Unauthorized();
        address oldAdmin = admin;
        admin = msg.sender;
        pendingAdmin = address(0);
        emit AdminTransferred(oldAdmin, msg.sender);
    }

    function setSaleActive(bool active) external onlyAdmin {
        saleActive = active;
        emit SaleStatusChanged(active);
    }

    function setMinPurchaseAmount(uint256 amount) external onlyAdmin {
        if (amount == 0) revert InvalidAmount();
        emit MinPurchaseAmountChanged(minPurchaseAmount, amount);
        minPurchaseAmount = amount;
    }

    /// @param paymentToken Official Ethereum mainnet USDC or USDT address.
    /// @param pricePerSaleToken_ Payment smallest units required for exactly 1 whole sale token (10**saleTokenDecimals units).
    function setPaymentOption(address paymentToken, bool enabled, uint256 pricePerSaleToken_) external onlyAdmin {
        if (!_isSupportedPaymentToken(paymentToken)) revert UnsupportedPaymentToken(paymentToken);
        if (enabled && pricePerSaleToken_ == 0) revert InvalidPrice();
        paymentOptions[paymentToken] = PaymentOption(enabled, pricePerSaleToken_);
        emit PaymentOptionSet(paymentToken, enabled, pricePerSaleToken_);
    }

    function quote(address paymentToken, uint256 saleAmount) public view returns (uint256) {
        PaymentOption memory option = paymentOptions[paymentToken];
        if (!option.enabled) revert PaymentNotSupported();
        if (saleAmount == 0) revert InvalidAmount();
        // Round up: the buyer can never underpay due to integer division.
        return FullMath.mulDivUp(saleAmount, option.pricePerSaleToken, saleTokenUnit);
    }

    /// @notice Buy sale tokens. The tokens remain held by the contract until individually claimed under the vesting schedule.
    /// @param paymentToken Official Ethereum mainnet USDC or USDT address.
    /// @param saleAmount Amount of sale token in its smallest unit.
    /// @param maxPaymentAmount Highest payment amount the buyer accepts. Protects ERC-20 buyers from a price increase while their transaction is pending.
    function buy(address paymentToken, uint256 saleAmount, uint256 maxPaymentAmount) external nonReentrant returns (uint256 lockId) {
        if (!saleActive) revert SaleNotActive();
        if (saleAmount < minPurchaseAmount) revert InvalidAmount();
        if (saleAmount > type(uint128).max) revert AmountTooLarge();
        uint256 available = availableInventory();
        if (available < saleAmount) revert InsufficientInventory(available, saleAmount);

        uint256 paymentAmount = quote(paymentToken, saleAmount);
        if (paymentAmount > maxPaymentAmount) revert PaymentExceedsMaximum(paymentAmount, maxPaymentAmount);

        // Effects before interactions; a failed payment transfer reverts this new lock as well.
        lockId = _locks[msg.sender].length;
        _locks[msg.sender].push(Lock({amount: uint128(saleAmount), claimed: 0, purchasedAt: uint64(block.timestamp)}));
        totalOutstanding += saleAmount;

        uint256 balanceBefore = IERC20(paymentToken).balanceOf(address(this));
        IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), paymentAmount);
        uint256 received = IERC20(paymentToken).balanceOf(address(this)) - balanceBefore;
        if (received != paymentAmount) revert IncorrectErc20Payment(paymentAmount, received);
        emit Purchased(msg.sender, paymentToken, saleAmount, paymentAmount, lockId);
    }

    function lockCount(address buyer) external view returns (uint256) {
        return _locks[buyer].length;
    }

    function lockAt(address buyer, uint256 lockId) external view returns (Lock memory) {
        return _locks[buyer][lockId];
    }

    function claimable(address buyer, uint256 lockId) public view returns (uint256) {
        Lock memory lock = _locks[buyer][lockId];
        if (block.timestamp < uint256(lock.purchasedAt) + CLIFF) return 0;
        uint256 periods = (block.timestamp - uint256(lock.purchasedAt) - CLIFF) / VESTING_INTERVAL;
        if (periods > VESTING_PERIODS) periods = VESTING_PERIODS;
        uint256 vested = FullMath.mulDiv(uint256(lock.amount), periods, VESTING_PERIODS);
        return vested - uint256(lock.claimed);
    }

    /// @notice Claim one or more purchase locks. Supplying selected IDs avoids an unbounded loop over every historical purchase.
    function claim(uint256[] calldata lockIds) external nonReentrant returns (uint256 totalClaimed) {
        uint256 count = _locks[msg.sender].length;
        for (uint256 i; i < lockIds.length; ++i) {
            uint256 lockId = lockIds[i];
            if (lockId >= count) revert InvalidLock();
            uint256 amount = claimable(msg.sender, lockId);
            if (amount == 0) continue;
            _locks[msg.sender][lockId].claimed += uint128(amount);
            totalClaimed += amount;
            emit Claimed(msg.sender, lockId, amount);
        }
        if (totalClaimed == 0) revert NothingToClaim();
        totalOutstanding -= totalClaimed;
        saleToken.safeTransfer(msg.sender, totalClaimed);
    }

    function withdrawUnsoldInventory(address recipient, uint256 amount) external onlyAdmin nonReentrant {
        if (recipient == address(0)) revert ZeroAddress();
        uint256 available = availableInventory();
        if (amount > available) revert InsufficientInventory(available, amount);
        saleToken.safeTransfer(recipient, amount);
        emit InventoryWithdrawn(recipient, amount);
    }

    function withdrawPayments(address paymentToken, address recipient, uint256 amount) external onlyAdmin nonReentrant {
        if (recipient == address(0)) revert ZeroAddress();
        // Sale-token withdrawals are restricted to withdrawUnsoldInventory(), which reserves buyers' unclaimed allocations.
        if (paymentToken == address(saleToken)) revert SaleTokenCannotBePaymentToken();
        if (!_isSupportedPaymentToken(paymentToken)) revert UnsupportedPaymentToken(paymentToken);
        IERC20(paymentToken).safeTransfer(recipient, amount);
        emit PaymentWithdrawn(paymentToken, recipient, amount);
    }

    /// @notice Tokens that are not reserved for already purchased vesting allocations.
    function availableInventory() public view returns (uint256) {
        uint256 balance = saleToken.balanceOf(address(this));
        return balance > totalOutstanding ? balance - totalOutstanding : 0;
    }

    function _isSupportedPaymentToken(address token) private pure returns (bool) {
        return token == USDC || token == USDT;
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.