Verified contractPartialMIT
Presale
Address0xaf24b07427be0e0d49f3cd117202bfe121cadaa5
- Balance
0 ETH
- Transactions
2,686
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,473,278
- Creation transaction
- 0xd9f2efc6bc…7f06ffde11
16 files
- src/Presale.solmain36.85 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.83 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.38 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/interfaces/IAggregatorV3.sol1.1 KB
src/Presale.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IAggregatorV3} from "./interfaces/IAggregatorV3.sol";
/// @title Presale
/// @author ConConAI
/// @notice Phased presale for the already-deployed $CON token. Buyers pay in USDC, USDT or ETH and
/// their $CON allocation is *booked* (no token transfer at purchase). After the presale the
/// admin opens claiming and buyers withdraw their allocation.
/// @dev Audit-clean by construction:
/// - Immutable config (token, stables, oracle, treasury); NO setters for them.
/// - Custom errors only, events on every state change, strict CEI, pull-pattern claim.
/// - `ReentrancyGuard` on all value-moving entry points, `SafeERC20` everywhere.
/// - One-way `presaleEnded` / `claimOpen` flags that the owner can never unset.
/// - The owner can never mutate `purchased`, reverse a claim, or touch buyers' $CON.
/// Buyers also earn one-time, stacking purchase bonuses (see {bonusTiers}); bonuses are pure
/// internal bookings (no external call) and, together with base sales, can never push
/// `totalSold` above {PRESALE_CAP}. A professional security audit is required before mainnet.
contract Presale is Ownable2Step, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////
TYPES
//////////////////////////////////////////////////////////////*/
/// @notice A single presale phase.
/// @param priceUsdE6 Price per 1 CON in USD, scaled by 1e6 (e.g. $0.005 == 5000).
/// @param cap Maximum amount of CON (18 decimals) sellable in this phase.
/// @param sold Amount of CON (18 decimals) already booked in this phase.
/// @param started Whether the admin has started this phase.
/// @param endsAt Unix timestamp after which buying in this phase is closed.
struct Phase {
uint256 priceUsdE6;
uint256 cap;
uint256 sold;
bool started;
uint64 endsAt;
}
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Number of presale phases.
uint8 public constant NUM_PHASES = 5;
/// @notice CON cap per phase: 10,000,000 CON (18 decimals).
uint256 public constant PHASE_CAP = 10_000_000 * 1e18;
/// @notice Hard global cap on total booked CON (base + stacking bonuses), 18 decimals.
/// @dev `totalSold` (base + bonus) can never exceed this; the deployer funds the presale with
/// exactly this amount so every booked allocation (including bonuses) is claimable.
uint256 public constant PRESALE_CAP = 50_000_000 * 1e18;
/// @notice Number of one-time, stacking purchase-bonus tiers.
uint8 public constant NUM_BONUS_TIERS = 3;
/// @notice Cumulative USD(1e6) a buyer must contribute to unlock bonus tier 1 / 2 / 3.
uint256 internal constant BONUS_TIER1_USD = 10_000 * 1e6;
uint256 internal constant BONUS_TIER2_USD = 25_000 * 1e6;
uint256 internal constant BONUS_TIER3_USD = 50_000 * 1e6;
/// @notice Extra CON(1e18) granted when a buyer first crosses bonus tier 1 / 2 / 3 (each once).
/// @dev Stacking: reaching $50k yields 50k + 150k + 400k = 600,000 CON in total bonuses.
uint256 internal constant BONUS_TIER1_CON = 50_000 * 1e18;
uint256 internal constant BONUS_TIER2_CON = 150_000 * 1e18;
uint256 internal constant BONUS_TIER3_CON = 400_000 * 1e18;
/// @notice CON has 18 decimals; used to scale conAmount math.
uint256 internal constant CON_SCALE = 1e18;
/// @notice Expected decimals of the Chainlink ETH/USD feed (standard USD feeds use 8).
uint8 internal constant FEED_DECIMALS = 8;
/// @notice Combined scale to convert `wei * answer(1e8)` into a USD(1e6) amount: 1e8 * 1e12.
uint256 internal constant ETH_USD_SCALE = 1e20;
/// @notice Maximum accepted age of an oracle answer (Chainlink ETH/USD mainnet heartbeat).
/// @dev Re-verify against the live feed's heartbeat before mainnet.
uint256 public constant MAX_ORACLE_AGE = 1 hours;
/*//////////////////////////////////////////////////////////////
IMMUTABLE CONFIG
//////////////////////////////////////////////////////////////*/
/// @notice The already-deployed $CON token this presale books and pays out.
IERC20 public immutable CON_TOKEN;
/// @notice USDC payment token (6 decimals, 1:1 USD).
IERC20 public immutable USDC;
/// @notice USDT payment token (6 decimals, 1:1 USD).
IERC20 public immutable USDT;
/// @notice Chainlink ETH/USD price feed.
IAggregatorV3 public immutable ETH_USD_FEED;
/// @notice Treasury that receives raised funds and swept/unsold $CON (equals the owner/admin).
address public immutable TREASURY;
/// @notice Unix timestamp at/after which buying is permanently closed (hard sale end).
/// @dev No purchase can execute once `block.timestamp >= SALE_HARD_END`, regardless of any phase
/// timer the owner may set.
uint256 public immutable SALE_HARD_END;
/// @notice Unix timestamp at/after which claiming is automatically available to every buyer.
/// @dev Claiming auto-opens at this time even if {enableClaim} was never called, so the owner can
/// never withhold buyers' allocations past this point. {enableClaim} can only open EARLIER.
uint256 public immutable CLAIM_START;
/*//////////////////////////////////////////////////////////////
STATE
//////////////////////////////////////////////////////////////*/
/// @notice The five presale phases, indexed 0..4.
Phase[NUM_PHASES] public phases;
/// @notice Index of the currently active phase.
uint8 public currentPhase;
/// @notice One-way flag: once true, no further buying is possible in any phase.
bool public presaleEnded;
/// @notice One-way flag: once true, buyers may claim their booked allocation.
bool public claimOpen;
/// @notice Booked CON allocation per buyer (18 decimals); set to 0 on claim.
mapping(address buyer => uint256 conAmount) public purchased;
/// @notice CON already claimed by each buyer (18 decimals); lets the frontend distinguish
/// "claimable" (`purchased > 0`) from "already claimed" (`claimed > 0 && purchased == 0`).
/// @dev Informational mirror of claims; does not affect any accounting.
mapping(address buyer => uint256 amount) public claimed;
/// @notice Total CON booked across all buyers and phases.
uint256 public totalSold;
/// @notice Total CON already claimed by buyers.
uint256 public totalClaimed;
/// @notice Cumulative USD(1e6) each buyer has actually paid in (stables 1:1, ETH via the oracle).
/// @dev Drives the stacking bonus tiers; only the amount actually charged is counted.
mapping(address buyer => uint256 usdE6) public contributedUsd;
/// @notice Number of bonus tiers already awarded to each buyer (0..{NUM_BONUS_TIERS}).
/// @dev Monotonic; ensures each tier is granted at most once per buyer.
mapping(address buyer => uint8 tiers) public bonusTiersAwarded;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a buyer books an allocation.
/// @param buyer The purchaser.
/// @param phaseIndex The phase the purchase was booked in.
/// @param conAmount CON amount booked (18 decimals).
/// @param asset Payment asset (address(0) for ETH).
/// @param paid Amount of `asset` charged.
event Purchased(
address indexed buyer, uint8 indexed phaseIndex, uint256 conAmount, address indexed asset, uint256 paid
);
/// @notice Emitted when a buyer crosses one or more stacking bonus tiers.
/// @param buyer The purchaser receiving the bonus.
/// @param bonusCon Extra CON booked for the newly crossed tier(s) (after any global-cap clamp).
/// @param newTier The buyer's bonus tier count after this award (0..{NUM_BONUS_TIERS}).
event BonusAwarded(address indexed buyer, uint256 bonusCon, uint8 newTier);
/// @notice Emitted when a buyer claims their allocation.
event Claimed(address indexed buyer, uint256 conAmount);
/// @notice Emitted when the admin starts a phase.
event PhaseStarted(uint8 indexed phaseIndex, uint256 priceUsdE6, uint64 endsAt);
/// @notice Emitted when the active phase timer is changed.
event TimerSet(uint8 indexed phaseIndex, uint64 endsAt);
/// @notice Emitted when the active phase is closed early.
event PhaseEnded(uint8 indexed phaseIndex, uint64 endsAt);
/// @notice Emitted when the presale is permanently ended.
event PresaleEnded();
/// @notice Emitted when claiming is permanently enabled.
event ClaimEnabled();
/// @notice Emitted when raised funds are withdrawn to the treasury.
event Withdrawn(address indexed asset, uint256 amount);
/// @notice Emitted when excess (unsold) $CON is swept to the treasury.
event Swept(uint256 conAmount);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error ZeroAddress();
error InvalidPhaseIndex();
error ZeroDuration();
error PhaseNotStarted();
error PresaleIsEnded();
error PhaseExpired();
error PhaseSoldOut();
error PresaleCapReached();
error UnsupportedStable();
error ZeroConAmount();
error ZeroPayment();
error ClaimNotOpen();
error ClaimAlreadyOpen();
error NothingToClaim();
error OracleInvalidPrice();
error OracleStale();
error OracleRoundIncomplete();
error InvalidFeedDecimals();
error CannotWithdrawConToken();
error NothingToWithdraw();
error NothingToSweep();
error PresaleNotEnded();
error EthTransferFailed();
error NotFullyFunded();
error RenounceDisabled();
error PriceExceedsMax();
error InvalidTokenDecimals();
error FeeOnTransferNotSupported();
error NotFunded();
error PhaseCannotGoBackward();
error TimerCannotShorten();
error InvalidSchedule();
error SaleClosed();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploys the presale bound to the existing $CON token and fixed phase prices.
/// @dev Reverts ({ZeroAddress}) if any address is zero and ({InvalidFeedDecimals}) if the feed
/// does not report 8 decimals. Phase prices are fixed at $0.005..$0.009 and have no setter.
/// @param conToken The already-deployed $CON token.
/// @param usdc USDC payment token (6 decimals).
/// @param usdt USDT payment token (6 decimals).
/// @param ethUsdFeed Chainlink ETH/USD aggregator.
/// @param treasury Treasury and initial owner/admin (receives funds and unsold $CON).
/// @param saleHardEnd Unix timestamp at/after which buying is permanently closed.
/// @param claimStart Unix timestamp at/after which claiming auto-opens (must be > `saleHardEnd`).
constructor(
IERC20 conToken,
IERC20 usdc,
IERC20 usdt,
IAggregatorV3 ethUsdFeed,
address treasury,
uint256 saleHardEnd,
uint256 claimStart
) Ownable(treasury) {
if (
address(conToken) == address(0) || address(usdc) == address(0) || address(usdt) == address(0)
|| address(ethUsdFeed) == address(0) || treasury == address(0)
) {
revert ZeroAddress();
}
if (ethUsdFeed.decimals() != FEED_DECIMALS) {
revert InvalidFeedDecimals();
}
// Enforce the decimal assumptions the pricing math relies on (stables 6, CON 18).
if (
IERC20Metadata(address(usdc)).decimals() != 6 || IERC20Metadata(address(usdt)).decimals() != 6
|| IERC20Metadata(address(conToken)).decimals() != 18
) {
revert InvalidTokenDecimals();
}
// Fixed schedule: the sale must end in the future and claiming must open strictly after it.
// forge-lint: disable-next-line(block-timestamp) - schedule is defined relative to deploy time.
if (saleHardEnd <= block.timestamp || claimStart <= saleHardEnd) {
revert InvalidSchedule();
}
CON_TOKEN = conToken;
USDC = usdc;
USDT = usdt;
ETH_USD_FEED = ethUsdFeed;
TREASURY = treasury;
SALE_HARD_END = saleHardEnd;
CLAIM_START = claimStart;
// Fixed phase prices: $0.005, $0.006, $0.007, $0.008, $0.009 (1e6 USD scale).
uint256[NUM_PHASES] memory prices = [uint256(5000), 6000, 7000, 8000, 9000];
for (uint8 i = 0; i < NUM_PHASES; ++i) {
phases[i].priceUsdE6 = prices[i];
phases[i].cap = PHASE_CAP;
}
}
/*//////////////////////////////////////////////////////////////
BUY
//////////////////////////////////////////////////////////////*/
/// @notice Buy (book) $CON with a supported stablecoin (USDC or USDT).
/// @dev Books the allocation; no $CON is transferred until {claim}. If the purchase would
/// exceed the phase cap, the CON amount is clamped to the remaining cap and only the exact
/// cost of that clamped amount is charged. CEI: state is updated before the token pull.
/// @param stable The payment token; must equal {USDC} or {USDT}.
/// @param amount The stablecoin amount to spend (6 decimals).
function buyWithStable(IERC20 stable, uint256 amount) external nonReentrant whenNotPaused {
_buyWithStable(stable, amount, 0);
}
/// @notice Buy (book) $CON with a stablecoin, reverting if the active phase price exceeds a bound.
/// @dev Identical to {buyWithStable(IERC20,uint256)} but with execution-price protection.
/// @param stable The payment token; must equal {USDC} or {USDT}.
/// @param amount The stablecoin amount to spend (6 decimals).
/// @param maxPriceUsdE6 Max acceptable phase price in USD(1e6); `0` means no limit.
function buyWithStable(IERC20 stable, uint256 amount, uint256 maxPriceUsdE6) external nonReentrant whenNotPaused {
_buyWithStable(stable, amount, maxPriceUsdE6);
}
/// @notice Buy (book) $CON with ETH, priced via the Chainlink ETH/USD feed.
/// @dev Books the allocation; no $CON is transferred until {claim}. The CON amount is clamped to
/// the remaining cap, only the exact ETH cost is kept, and any excess ETH is refunded after
/// state updates (CEI) under the reentrancy guard.
function buyWithETH() external payable nonReentrant whenNotPaused {
_buyWithETH(0);
}
/// @notice Buy (book) $CON with ETH, reverting if the active phase price exceeds a bound.
/// @dev Identical to {buyWithETH()} but with execution-price protection.
/// @param maxPriceUsdE6 Max acceptable phase price in USD(1e6); `0` means no limit.
function buyWithETH(uint256 maxPriceUsdE6) external payable nonReentrant whenNotPaused {
_buyWithETH(maxPriceUsdE6);
}
/*//////////////////////////////////////////////////////////////
BUY (INTERNAL)
//////////////////////////////////////////////////////////////*/
/// @dev Core stablecoin buy logic. `maxPriceUsdE6 == 0` disables the price check. Rejects tokens
/// that take a fee on transfer so booked allocations are always fully backed.
function _buyWithStable(IERC20 stable, uint256 amount, uint256 maxPriceUsdE6) internal {
if (stable != USDC && stable != USDT) revert UnsupportedStable();
if (amount == 0) revert ZeroPayment();
uint8 phaseIndex = currentPhase;
Phase storage phase = _activePhase(phaseIndex);
uint256 price = phase.priceUsdE6;
if (maxPriceUsdE6 != 0 && price > maxPriceUsdE6) revert PriceExceedsMax();
uint256 conAmount = (amount * CON_SCALE) / price;
uint256 remaining = _baseRemaining(phase);
uint256 charge = amount;
if (conAmount > remaining) {
conAmount = remaining;
// Exact stablecoin cost for the clamped CON amount (floor); never over-charges.
charge = (conAmount * price) / CON_SCALE;
}
if (conAmount == 0) revert ZeroConAmount();
_book(msg.sender, phaseIndex, conAmount);
emit Purchased(msg.sender, phaseIndex, conAmount, address(stable), charge);
// Stables are 1:1 USD with 6 decimals, so the charged amount IS the USD(1e6) contributed.
_awardBonus(msg.sender, charge);
// Reject fee-on-transfer stables: the contract must actually receive the full `charge` that
// was booked, otherwise later claims could be under-backed.
uint256 balBefore = stable.balanceOf(address(this));
stable.safeTransferFrom(msg.sender, address(this), charge);
if (stable.balanceOf(address(this)) - balBefore < charge) revert FeeOnTransferNotSupported();
}
/// @dev Core ETH buy logic. `maxPriceUsdE6 == 0` disables the price check. Clamps to the remaining
/// cap, keeps only the exact ETH cost and refunds the remainder after state updates (CEI).
function _buyWithETH(uint256 maxPriceUsdE6) internal {
if (msg.value == 0) revert ZeroPayment();
uint8 phaseIndex = currentPhase;
Phase storage phase = _activePhase(phaseIndex);
uint256 price = phase.priceUsdE6;
if (maxPriceUsdE6 != 0 && price > maxPriceUsdE6) revert PriceExceedsMax();
uint256 ethUsd = _readEthUsd();
// USD(1e6) value of msg.value, then CON(1e18) at the phase price.
uint256 usdE6 = (msg.value * ethUsd) / ETH_USD_SCALE;
uint256 conAmount = (usdE6 * CON_SCALE) / price;
uint256 remaining = _baseRemaining(phase);
bool clamped = conAmount > remaining; // L-02: capture before clamping
if (clamped) {
conAmount = remaining;
}
if (conAmount == 0) revert ZeroConAmount();
// Exact ETH cost of the (possibly clamped) CON amount; refund the remainder.
uint256 requiredUsdE6 = (conAmount * price) / CON_SCALE;
uint256 requiredEth = (requiredUsdE6 * ETH_USD_SCALE) / ethUsd;
// Defensive: rounding can never make the requirement exceed what was sent.
if (requiredEth > msg.value) {
requiredEth = msg.value;
}
uint256 refund = msg.value - requiredEth;
_book(msg.sender, phaseIndex, conAmount);
emit Purchased(msg.sender, phaseIndex, conAmount, address(0), requiredEth);
// L-02: credit the full USD value of the ETH when unclamped (floor rounding on the
// CON->USD step must not drop a buyer a micro-dollar below a bonus tier); when clamped,
// credit the exact USD charged for the booked CON.
_awardBonus(msg.sender, clamped ? requiredUsdE6 : usdE6);
if (refund > 0) {
(bool ok,) = msg.sender.call{value: refund}("");
if (!ok) revert EthTransferFailed();
}
}
/*//////////////////////////////////////////////////////////////
CLAIM
//////////////////////////////////////////////////////////////*/
/// @notice Claim the caller's booked $CON allocation once claiming is open.
/// @dev Pull-pattern, CEI, reentrancy-guarded and double-claim safe (allocation zeroed first).
/// Claiming is available once the owner has called {enableClaim} OR the scheduled
/// {CLAIM_START} has arrived, so buyers can always claim at/after {CLAIM_START} even if the
/// owner never opens it early.
function claim() external nonReentrant {
// forge-lint: disable-next-line(block-timestamp) - scheduled auto-open is intentional.
if (!claimOpen && block.timestamp < CLAIM_START) revert ClaimNotOpen();
uint256 amount = purchased[msg.sender];
if (amount == 0) revert NothingToClaim();
purchased[msg.sender] = 0;
claimed[msg.sender] += amount;
totalClaimed += amount;
emit Claimed(msg.sender, amount);
CON_TOKEN.safeTransfer(msg.sender, amount);
}
/*//////////////////////////////////////////////////////////////
ADMIN
//////////////////////////////////////////////////////////////*/
/// @notice Start (or restart) a phase, activating it and setting its timer.
/// @dev Phases are forward-only: the owner may (re)start the current phase or move to a later,
/// more expensive one, but can never activate an earlier/cheaper phase. Requires the sale to
/// be pre-funded with the full {PRESALE_CAP} of $CON so every future booking is provably
/// backed. Cannot be called once the presale has ended.
/// @param i Phase index to start; must satisfy `currentPhase <= i < NUM_PHASES`.
/// @param duration Seconds from now until the phase closes.
function startPhase(uint8 i, uint64 duration) external onlyOwner {
// Root protection: the presale must already hold the full cap of CON before any phase opens,
// so every allocation booked from now on (base + bonuses) is fully claimable.
if (CON_TOKEN.balanceOf(address(this)) < PRESALE_CAP) revert NotFunded();
if (presaleEnded) revert PresaleIsEnded();
if (i >= NUM_PHASES) revert InvalidPhaseIndex();
if (i < currentPhase) revert PhaseCannotGoBackward();
if (duration == 0) revert ZeroDuration();
// forge-lint: disable-next-line(unsafe-typecast) - block.timestamp fits in uint64 for millennia.
uint64 endsAt = uint64(block.timestamp) + duration;
phases[i].started = true;
phases[i].endsAt = endsAt;
currentPhase = i;
emit PhaseStarted(i, phases[i].priceUsdE6, endsAt);
}
/// @notice Set the active phase's end timestamp directly.
/// @dev The timer can only ever be lengthened ({TimerCannotShorten}); the owner can never pull a
/// phase's end forward via this function. Use {endPhase} to close a phase early instead.
/// @param newEndsAt New end timestamp for the active phase; must be >= the current end.
function setTimer(uint64 newEndsAt) external onlyOwner {
Phase storage phase = phases[currentPhase];
if (!phase.started) revert PhaseNotStarted();
if (newEndsAt < phase.endsAt) revert TimerCannotShorten();
phase.endsAt = newEndsAt;
emit TimerSet(currentPhase, newEndsAt);
}
/// @notice Extend the active phase's timer by a number of seconds.
/// @param extraSeconds Seconds to add to the active phase's end timestamp.
function extendTimer(uint64 extraSeconds) external onlyOwner {
Phase storage phase = phases[currentPhase];
if (!phase.started) revert PhaseNotStarted();
uint64 newEndsAt = phase.endsAt + extraSeconds;
phase.endsAt = newEndsAt;
emit TimerSet(currentPhase, newEndsAt);
}
/// @notice Close the active phase immediately by setting its timer to now.
function endPhase() external onlyOwner {
Phase storage phase = phases[currentPhase];
if (!phase.started) revert PhaseNotStarted();
// forge-lint: disable-next-line(unsafe-typecast) - block.timestamp fits in uint64 for millennia.
uint64 nowTs = uint64(block.timestamp);
// L-01: mark already-expired (nowTs - 1) so a buy in THIS block can no longer slip in at the
// old phase price. nowTs is always far greater than 1, so this cannot underflow.
phase.endsAt = nowTs - 1;
emit PhaseEnded(currentPhase, nowTs);
}
/// @notice Permanently end the presale; no further buying is possible. One-way.
function endPresale() external onlyOwner {
if (presaleEnded) revert PresaleIsEnded();
presaleEnded = true;
emit PresaleEnded();
}
/// @notice Permanently enable claiming EARLIER than the scheduled {CLAIM_START}. One-way and
/// independent of {endPresale}.
/// @dev Reverts ({NotFullyFunded}) unless the contract holds at least the outstanding allocation,
/// so claiming can never be opened while under-funded. This only ever moves claiming earlier;
/// it can never delay it, because {CLAIM_START} auto-opens claiming regardless of this flag.
function enableClaim() external onlyOwner {
if (claimOpen) revert ClaimAlreadyOpen();
uint256 outstanding = totalSold - totalClaimed;
if (CON_TOKEN.balanceOf(address(this)) < outstanding) revert NotFullyFunded();
claimOpen = true;
emit ClaimEnabled();
}
/// @notice Pause buying (claims remain enabled).
function pause() external onlyOwner {
_pause();
}
/// @notice Unpause buying.
function unpause() external onlyOwner {
_unpause();
}
/// @notice Renouncing ownership is permanently disabled to avoid stranding buyer allocations.
/// @dev Always reverts ({RenounceDisabled}). Two-step ownership transfer via {Ownable2Step}
/// remains available.
function renounceOwnership() public pure override {
revert RenounceDisabled();
}
/// @notice Withdraw raised funds to the treasury.
/// @dev `asset == address(0)` withdraws ETH; otherwise withdraws the full balance of `asset`.
/// Reverts if `asset` is the $CON token (buyers' tokens are never withdrawable this way).
/// @param asset The asset to withdraw (address(0) for ETH).
function withdraw(address asset) external nonReentrant onlyOwner {
if (asset == address(CON_TOKEN)) revert CannotWithdrawConToken();
if (asset == address(0)) {
uint256 amount = address(this).balance;
if (amount == 0) revert NothingToWithdraw();
emit Withdrawn(asset, amount);
(bool ok,) = TREASURY.call{value: amount}("");
if (!ok) revert EthTransferFailed();
} else {
uint256 amount = IERC20(asset).balanceOf(address(this));
if (amount == 0) revert NothingToWithdraw();
emit Withdrawn(asset, amount);
IERC20(asset).safeTransfer(TREASURY, amount);
}
}
/// @notice Sweep only the EXCESS (unsold) $CON to the treasury, always leaving claimers covered.
/// @dev Excess = `balanceOf(this) - (totalSold - totalClaimed)`. Only callable once the presale has
/// ended (so buying can no longer create new claims after a sweep). Reverts if there is nothing
/// to sweep, guaranteeing outstanding claims remain fully backed.
function sweepUnsold() external nonReentrant onlyOwner {
if (!presaleEnded) revert PresaleNotEnded();
uint256 outstanding = totalSold - totalClaimed;
uint256 balance = CON_TOKEN.balanceOf(address(this));
if (balance <= outstanding) revert NothingToSweep();
uint256 excess = balance - outstanding;
emit Swept(excess);
CON_TOKEN.safeTransfer(TREASURY, excess);
}
/*//////////////////////////////////////////////////////////////
VIEWS
//////////////////////////////////////////////////////////////*/
/// @notice Outstanding (booked but unclaimed) $CON that the contract must keep covered.
/// @return The amount of CON owed to buyers who have not yet claimed.
function outstandingClaims() external view returns (uint256) {
return totalSold - totalClaimed;
}
/// @notice Remaining CON sellable in the active phase, clamped to the global base+bonus cap.
/// @dev Returns the minimum of the phase remaining (`phase.cap - phase.sold`) and the global
/// remaining (`PRESALE_CAP - totalSold`). The returned value reflects the global
/// `PRESALE_CAP`, which already accounts for both base sales and awarded bonuses, so it is
/// never larger than what can actually still be sold.
/// @return The CON still sellable right now (18 decimals).
function remainingInActivePhase() external view returns (uint256) {
Phase storage phase = phases[currentPhase];
uint256 phaseRemaining = phase.cap - phase.sold;
uint256 globalRemaining = PRESALE_CAP - totalSold;
return phaseRemaining < globalRemaining ? phaseRemaining : globalRemaining;
}
/// @notice Whether buying is currently possible in the active phase.
/// @return active True if a buy would be accepted right now.
function isBuyingActive() external view returns (bool active) {
Phase storage phase = phases[currentPhase];
// forge-lint: disable-next-line(block-timestamp) - timed phase window + hard end are intentional.
return phase.started && !presaleEnded && !paused() && block.timestamp < SALE_HARD_END
&& block.timestamp <= phase.endsAt && phase.sold < phase.cap && totalSold < PRESALE_CAP;
}
/// @notice Preview the base + stacking-bonus CON a buyer would receive for spending `usdE6`.
/// @dev Pure view (no state change). Mirrors the buy path: base is priced at the current phase
/// price and clamped to the phase and global caps; only the USD actually charged drives the
/// one-time, stacking bonus, which is itself clamped to the remaining global cap.
/// @param buyer The buyer whose existing contribution/awarded tiers are considered.
/// @param usdE6 The USD amount to spend, scaled by 1e6 (for ETH, pass the oracle-derived USD).
/// @return baseCon Base CON booked for the spend (18 decimals), after cap clamping.
/// @return bonusCon Extra CON from any newly crossed bonus tiers (18 decimals).
/// @return newTier The buyer's resulting bonus tier count (0..{NUM_BONUS_TIERS}).
function previewPurchase(address buyer, uint256 usdE6)
external
view
returns (uint256 baseCon, uint256 bonusCon, uint8 newTier)
{
Phase storage phase = phases[currentPhase];
uint256 price = phase.priceUsdE6;
baseCon = (usdE6 * CON_SCALE) / price;
uint256 phaseRemaining = phase.cap - phase.sold;
uint256 globalRemaining = PRESALE_CAP - totalSold;
uint256 remaining = phaseRemaining < globalRemaining ? phaseRemaining : globalRemaining;
uint256 chargedUsdE6 = usdE6;
if (baseCon > remaining) {
baseCon = remaining;
chargedUsdE6 = (baseCon * price) / CON_SCALE;
}
uint8 awarded = bonusTiersAwarded[buyer];
newTier = _tiersFor(contributedUsd[buyer] + chargedUsdE6);
if (newTier > awarded) {
for (uint8 t = awarded; t < newTier; ++t) {
bonusCon += _tierCon(t);
}
uint256 remainingAfterBase = globalRemaining - baseCon;
if (bonusCon > remainingAfterBase) bonusCon = remainingAfterBase;
}
}
/// @notice The bonus-tier thresholds and amounts.
/// @return usdThresholds Cumulative USD(1e6) needed to unlock each tier.
/// @return conAmounts Extra CON(1e18) granted for crossing each tier.
function bonusTiers()
external
pure
returns (uint256[NUM_BONUS_TIERS] memory usdThresholds, uint256[NUM_BONUS_TIERS] memory conAmounts)
{
usdThresholds = [BONUS_TIER1_USD, BONUS_TIER2_USD, BONUS_TIER3_USD];
conAmounts = [BONUS_TIER1_CON, BONUS_TIER2_CON, BONUS_TIER3_CON];
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Returns the active phase storage pointer after enforcing that buying is allowed.
function _activePhase(uint8 phaseIndex) internal view returns (Phase storage phase) {
if (presaleEnded) revert PresaleIsEnded();
// forge-lint: disable-next-line(block-timestamp) - hard sale end is intentional.
if (block.timestamp >= SALE_HARD_END) revert SaleClosed();
phase = phases[phaseIndex];
if (!phase.started) revert PhaseNotStarted();
// forge-lint: disable-next-line(block-timestamp) - timed phase window is intentional.
if (block.timestamp > phase.endsAt) revert PhaseExpired();
}
/// @dev Applies the booking effects for a base purchase (no external interaction).
function _book(address buyer, uint8 phaseIndex, uint256 conAmount) internal {
purchased[buyer] += conAmount;
phases[phaseIndex].sold += conAmount;
totalSold += conAmount;
}
/// @dev CON still sellable as *base* right now: min of the phase cap and the global cap.
/// Reverts if either the phase ({PhaseSoldOut}) or the presale ({PresaleCapReached}) is full.
function _baseRemaining(Phase storage phase) internal view returns (uint256 remaining) {
uint256 phaseRemaining = phase.cap - phase.sold;
if (phaseRemaining == 0) revert PhaseSoldOut();
uint256 globalRemaining = PRESALE_CAP - totalSold;
if (globalRemaining == 0) revert PresaleCapReached();
remaining = phaseRemaining < globalRemaining ? phaseRemaining : globalRemaining;
}
/// @dev Credits `usdE6Added` to the buyer's running total and books any newly crossed bonus
/// tiers. Pure internal booking: bonuses go to `purchased`/`totalSold` only (never a phase
/// cap) and are clamped to the remaining global cap. No external interaction (CEI-safe).
function _awardBonus(address buyer, uint256 usdE6Added) internal {
uint256 contributed = contributedUsd[buyer] + usdE6Added;
contributedUsd[buyer] = contributed;
uint8 awarded = bonusTiersAwarded[buyer];
uint8 reached = _tiersFor(contributed);
if (reached <= awarded) return;
uint256 bonus;
for (uint8 t = awarded; t < reached; ++t) {
bonus += _tierCon(t);
}
// Bonuses count against the global cap only; clamp near sellout so totalSold <= PRESALE_CAP.
uint256 globalRemaining = PRESALE_CAP - totalSold;
if (bonus > globalRemaining) bonus = globalRemaining;
bonusTiersAwarded[buyer] = reached;
if (bonus > 0) {
purchased[buyer] += bonus;
totalSold += bonus;
}
emit BonusAwarded(buyer, bonus, reached);
}
/// @dev Number of bonus tiers unlocked by a cumulative contribution of `usdE6` (0..3).
function _tiersFor(uint256 usdE6) internal pure returns (uint8 tiers) {
if (usdE6 >= BONUS_TIER3_USD) return 3;
if (usdE6 >= BONUS_TIER2_USD) return 2;
if (usdE6 >= BONUS_TIER1_USD) return 1;
return 0;
}
/// @dev Bonus CON granted for crossing the tier at `tierIndex` (0-based).
function _tierCon(uint8 tierIndex) internal pure returns (uint256) {
if (tierIndex == 0) return BONUS_TIER1_CON;
if (tierIndex == 1) return BONUS_TIER2_CON;
return BONUS_TIER3_CON;
}
/// @dev Reads and validates the ETH/USD price (8-decimal answer), reverting on bad/stale data.
/// @return ethUsd The validated ETH/USD price (8 decimals).
function _readEthUsd() internal view returns (uint256 ethUsd) {
(uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) = ETH_USD_FEED.latestRoundData();
if (answer <= 0) revert OracleInvalidPrice();
if (updatedAt == 0) revert OracleRoundIncomplete();
if (answeredInRound < roundId) revert OracleRoundIncomplete();
// forge-lint: disable-next-line(block-timestamp) - staleness guard is the intended use.
if (block.timestamp - updatedAt > MAX_ORACLE_AGE) revert OracleStale();
// forge-lint: disable-next-line(unsafe-typecast) - answer is guaranteed > 0 by the check above.
ethUsd = uint256(answer);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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) {
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);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// 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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// 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;
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/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());
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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);
}
src/interfaces/IAggregatorV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IAggregatorV3
/// @notice Minimal Chainlink AggregatorV3 interface used by {Presale} to read the ETH/USD price.
/// @dev Matches the canonical Chainlink `AggregatorV3Interface`. Only the members consumed by the
/// presale are declared here to avoid pulling in an extra dependency.
interface IAggregatorV3 {
/// @notice Number of decimals in the answer returned by {latestRoundData}.
function decimals() external view returns (uint8);
/// @notice Latest round data for the feed.
/// @return roundId The round ID.
/// @return answer The price answer for the round (for an ETH/USD feed: USD per ETH).
/// @return startedAt Timestamp when the round started.
/// @return updatedAt Timestamp when the round was last updated (used for the staleness guard).
/// @return answeredInRound The round in which the answer was computed.
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.