// SPDX-License-Identifier: MIT pragma solidity 0.8.38; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.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 {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; interface IBurnableToken is IERC20 { function burn(uint256 amount) external; } /// @notice One immutable, valueless testnet round. Every funded claim is always for sale. /// @dev Control is deliberately not an ERC721: an ordinary NFT transfer must not bypass settlement. contract HighNoonBoard is Ownable2Step, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant CLAIM_COUNT = 64; uint256 public constant MIN_PRICE = 100 ether; uint256 public constant MAX_PRICE = 1_000_000 ether; uint256 public constant OPENING_PRICE = 1000 ether; uint256 public constant DAY = 1 days; uint256 public constant FEE_DENOMINATOR = 100 days; uint256 public constant CURE_PERIOD = 6 hours; uint256 public constant AUCTION_DESCENT = 5 hours; uint256 public constant AUCTION_FLOOR = 1 hours; uint256 public constant MAX_PAUSE_DURATION = 24 hours; enum State { Locked, Vacant, Active, Cure, Auction, Expired, Ended } struct Plot { address holder; uint256 askingPrice; uint256 deposit; uint256 debt; uint256 remainder; uint64 lastSettled; uint64 depletedAt; uint64 version; // Ownership epoch: only purchase and release invalidate it. } struct PlotView { uint256 id; uint8 state; address holder; uint256 askingPrice; uint256 purchasePrice; uint256 deposit; uint256 accruedDebt; uint256 dailyUpkeep; uint64 fundedUntil; uint64 cureEnds; uint64 auctionEnds; uint64 version; bool holderIsNpc; } IERC20 public immutable token; uint64 public immutable roundStart; uint64 public immutable roundEnd; bool private pauseStored; uint64 private pausedAt; uint64 private pausedDuration; Plot[64] private plots; mapping(address => uint256) public credits; mapping(address => bool) public isNpc; mapping(address => uint256) public selectedClaim; mapping(address => uint256) private earnedScore; uint256 public totalCredits; uint256 public totalDeposits; uint256 public totalBurned; uint256 public totalPurchases; uint256 public humanPurchases; uint256 public npcPurchases; event ClaimPurchased(uint256 indexed id, address indexed buyer, address indexed seller, uint256 price, uint256 newAsk, uint256 newDeposit, bool buyerIsNpc); event AskingPriceChanged(uint256 indexed id, address indexed holder, uint256 oldPrice, uint256 newPrice); event UpkeepFunded(uint256 indexed id, address indexed holder, uint256 amount); event DepositWithdrawn(uint256 indexed id, address indexed holder, uint256 amount); event UpkeepSettled(uint256 indexed id, uint256 burned, uint256 remainingDeposit, uint256 debt); event ClaimReleased(uint256 indexed id, address indexed holder); event CreditWithdrawn(address indexed account, uint256 amount); event ScoringClaimSelected(address indexed account, uint256 id); event NpcUpdated(address indexed account, bool value); event PauseUpdated(bool value, uint64 gameTimestamp); error InvalidClaim(); error GameNotActive(); error TradingPaused(); error InvalidPrice(); error BufferTooSmall(); error NotHolder(); error StaleQuote(); error QuoteExpired(); error PriceExceeded(); error RecoveryStarted(); error ZeroAmount(); error NoCredit(); error OwnershipRenunciationDisabled(); constructor(address token_, address admin_, uint64 startTime_) Ownable(admin_) { require(token_ != address(0), "Zero token"); require(startTime_ >= block.timestamp && startTime_ <= block.timestamp + 7 days, "Start outside window"); token = IERC20(token_); roundStart = startTime_; roundEnd = startTime_ + 14 days; } /// @notice A virtual UNIX-seconds clock, excluding at most 24 hours per pause and capped at round end. function gameTime() public view returns (uint64) { uint256 currentPause = pauseStored ? Math.min(block.timestamp - pausedAt, MAX_PAUSE_DURATION) : 0; uint256 clock = block.timestamp - pausedDuration - currentPause; return uint64(Math.min(clock, roundEnd)); } /// @notice Trading resumes automatically at the pause deadline without an owner transaction. function paused() public view returns (bool) { return pauseStored && block.timestamp < uint256(pausedAt) + MAX_PAUSE_DURATION; } /// @notice Deadline of the stored pause, or zero when no pause is stored. function pauseEndsAt() external view returns (uint64) { return pauseStored ? uint64(uint256(pausedAt) + MAX_PAUSE_DURATION) : 0; } function setPaused(bool value) external onlyOwner { bool expired = pauseStored && !paused(); if (expired) { pausedDuration += uint64(MAX_PAUSE_DURATION); pauseStored = false; pausedAt = 0; } require(value != pauseStored || expired, "Already set"); if (value) { pausedAt = uint64(block.timestamp); pauseStored = true; } else if (pauseStored) { pausedDuration += uint64(block.timestamp) - pausedAt; pauseStored = false; pausedAt = 0; } emit PauseUpdated(value, gameTime()); } /// @notice Administration remains transferable through the two-step ownership flow. function renounceOwnership() public view override onlyOwner { revert OwnershipRenunciationDisabled(); } function setNpc(address account, bool value) external onlyOwner { require(account != address(0), "Zero NPC"); isNpc[account] = value; emit NpcUpdated(account, value); } function getPlots() external view returns (PlotView[] memory all) { all = new PlotView[](CLAIM_COUNT); for (uint256 id; id < CLAIM_COUNT; ++id) all[id] = getPlot(id); } function getPlot(uint256 id) public view returns (PlotView memory v) { _validId(id); uint64 t = gameTime(); (Plot memory p,,) = _accrue(plots[id], t); State state = _state(id, p, t); uint256 ask = p.holder == address(0) ? OPENING_PRICE : p.askingPrice; uint64 fundedUntil; if (p.holder != address(0)) { fundedUntil = p.depletedAt != 0 ? p.depletedAt : uint64(uint256(p.lastSettled) + _fundedSeconds(p)); fundedUntil = uint64(Math.min(fundedUntil, roundEnd)); } v = PlotView(id, uint8(state), p.holder, ask, _price(p, state, t), p.deposit, p.debt, ask / 100, fundedUntil, p.depletedAt == 0 ? 0 : uint64(p.depletedAt + CURE_PERIOD), p.depletedAt == 0 ? 0 : uint64(p.depletedAt + CURE_PERIOD + AUCTION_DESCENT + AUCTION_FLOOR), p.version, isNpc[p.holder]); } function quote(uint256 id) external view returns (uint256 purchasePrice, uint64 version, uint8 state) { PlotView memory p = getPlot(id); return (p.purchasePrice, p.version, p.state); } function buy(uint256 id, uint256 newAsk, uint256 newDeposit, uint256 maxPrice, uint64 expectedVersion, uint256 deadline) external nonReentrant { _trading(); _validId(id); if (block.timestamp > deadline) revert QuoteExpired(); if (plots[id].version != expectedVersion) revert StaleQuote(); _checkPrice(newAsk); if (newDeposit < minimumDeposit(newAsk)) revert BufferTooSmall(); _settle(id); Plot memory old = plots[id]; // Final settlement rounds the outgoing holder's fractional upkeep up by at most one wei. // Otherwise a self-purchase would discard the carried fractional remainder. if (old.remainder != 0 && old.deposit != 0) { --old.deposit; --totalDeposits; _burn(1); old.remainder = 0; } uint64 t = gameTime(); State state = _state(id, old, t); if (state == State.Locked || state == State.Ended) revert GameNotActive(); uint256 price = _price(old, state, t); if (price > maxPrice) revert PriceExceeded(); address seller = old.holder; bool vacant = seller == address(0) || state == State.Expired; token.safeTransferFrom(msg.sender, address(this), price + newDeposit); if (seller != address(0)) { _credit(seller, old.deposit); totalDeposits -= old.deposit; if (selectedClaim[seller] == id + 1) selectedClaim[seller] = 0; } if (vacant) _burn(price); else { uint256 debtPayment = Math.min(old.debt + (old.remainder == 0 ? 0 : 1), price); _burn(debtPayment); _credit(seller, price - debtPayment); } plots[id] = Plot(msg.sender, newAsk, newDeposit, 0, 0, t, 0, old.version + 1); totalDeposits += newDeposit; if (selectedClaim[msg.sender] == 0) { selectedClaim[msg.sender] = id + 1; emit ScoringClaimSelected(msg.sender, id); } ++totalPurchases; if (isNpc[msg.sender]) ++npcPurchases; else ++humanPurchases; emit ClaimPurchased(id, msg.sender, vacant ? address(0) : seller, price, newAsk, newDeposit, isNpc[msg.sender]); } function minimumDeposit(uint256 ask) public pure returns (uint256) { return Math.ceilDiv(ask, 100); } function reprice(uint256 id, uint256 newAsk, uint64 expectedVersion) external nonReentrant { _trading(); _holder(id); if (plots[id].version != expectedVersion) revert StaleQuote(); _checkPrice(newAsk); _settle(id); Plot storage p = plots[id]; if (p.depletedAt != 0) revert RecoveryStarted(); if (p.deposit < minimumDeposit(newAsk)) revert BufferTooSmall(); uint256 old = p.askingPrice; p.askingPrice = newAsk; emit AskingPriceChanged(id, msg.sender, old, newAsk); } function topUp(uint256 id, uint256 amount) external nonReentrant { _trading(); _holder(id); if (amount == 0) revert ZeroAmount(); _settle(id); Plot storage p = plots[id]; if (p.depletedAt != 0 && gameTime() >= p.depletedAt + CURE_PERIOD) revert RecoveryStarted(); token.safeTransferFrom(msg.sender, address(this), amount); uint256 payment = Math.min(amount, p.debt); p.debt -= payment; _burn(payment); uint256 added = amount - payment; p.deposit += added; totalDeposits += added; if (p.depletedAt != 0) { if (p.debt != 0 || p.deposit < minimumDeposit(p.askingPrice)) revert BufferTooSmall(); p.depletedAt = 0; // Carry fractional debt into future upkeep. It is never erased by topping up. } emit UpkeepFunded(id, msg.sender, amount); } function withdrawDeposit(uint256 id, uint256 amount) external nonReentrant { _holder(id); if (amount == 0) revert ZeroAmount(); _settle(id); Plot storage p = plots[id]; if (amount > p.deposit) revert BufferTooSmall(); if (gameTime() < roundEnd && p.deposit - amount < minimumDeposit(p.askingPrice)) revert BufferTooSmall(); p.deposit -= amount; totalDeposits -= amount; _credit(msg.sender, amount); emit DepositWithdrawn(id, msg.sender, amount); } function release(uint256 id) external nonReentrant { _holder(id); _settle(id); Plot memory p = plots[id]; if (p.remainder != 0 && p.deposit != 0) { --p.deposit; --totalDeposits; _burn(1); } _credit(msg.sender, p.deposit); totalDeposits -= p.deposit; if (selectedClaim[msg.sender] == id + 1) selectedClaim[msg.sender] = 0; delete plots[id]; plots[id].version = p.version + 1; emit ClaimReleased(id, msg.sender); } function withdrawCredits() external nonReentrant { uint256 amount = credits[msg.sender]; if (amount == 0) revert NoCredit(); credits[msg.sender] = 0; totalCredits -= amount; token.safeTransfer(msg.sender, amount); emit CreditWithdrawn(msg.sender, amount); } function selectScoringClaim(uint256 id) external nonReentrant { _trading(); _holder(id); uint256 previous = selectedClaim[msg.sender]; if (previous != 0) _settle(previous - 1); if (previous != id + 1) _settle(id); if (plots[id].depletedAt != 0) revert RecoveryStarted(); selectedClaim[msg.sender] = id + 1; emit ScoringClaimSelected(msg.sender, id); } function scoreOf(address account) external view returns (uint256 score) { score = earnedScore[account]; uint256 selected = selectedClaim[account]; if (selected != 0) { Plot memory p = plots[selected - 1]; if (p.holder == account) { (,, uint256 pending) = _accrue(p, gameTime()); score += pending; } } } function settle(uint256 id) external nonReentrant { _validId(id); _settle(id); } function _settle(uint256 id) internal { Plot memory before_ = plots[id]; if (before_.holder == address(0)) return; uint256 priorDebt = before_.debt; (Plot memory after_, uint256 burned, uint256 funded) = _accrue(before_, gameTime()); plots[id] = after_; if (selectedClaim[before_.holder] == id + 1) earnedScore[before_.holder] += funded; totalDeposits -= burned; _burn(burned); if (burned != 0 || after_.debt != priorDebt) emit UpkeepSettled(id, burned, after_.deposit, after_.debt); } /// @dev Upkeep uses numerator remainders so repeated lazy settlements do not forgive sub-wei charges. /// Depletion/scoring timestamps are rounded down to whole seconds; debt is capped to six hours. function _accrue(Plot memory p, uint64 t) internal pure returns (Plot memory, uint256 burned, uint256 funded) { if (p.holder == address(0) || t <= p.lastSettled) return (p, 0, 0); if (p.depletedAt != 0) { uint256 end = Math.min(t, uint256(p.depletedAt) + CURE_PERIOD); uint256 start = Math.min(p.lastSettled, end); uint256 numerator = p.debt * FEE_DENOMINATOR + p.remainder + p.askingPrice * (end - start); numerator = Math.min(numerator, p.askingPrice * CURE_PERIOD); p.debt = numerator / FEE_DENOMINATOR; p.remainder = numerator % FEE_DENOMINATOR; } else { uint256 elapsed = t - p.lastSettled; uint256 numerator = p.askingPrice * elapsed + p.remainder; uint256 due = numerator / FEE_DENOMINATOR; if (due < p.deposit) { p.deposit -= due; burned = due; p.remainder = numerator % FEE_DENOMINATOR; funded = elapsed; } else { funded = _fundedSeconds(p); p.depletedAt = uint64(uint256(p.lastSettled) + funded); burned = p.deposit; uint256 unpaid = numerator - p.deposit * FEE_DENOMINATOR; unpaid = Math.min(unpaid, p.askingPrice * CURE_PERIOD); p.deposit = 0; p.debt = unpaid / FEE_DENOMINATOR; p.remainder = unpaid % FEE_DENOMINATOR; } } p.lastSettled = t; return (p, burned, funded); } function _fundedSeconds(Plot memory p) internal pure returns (uint256) { if (p.deposit == 0 || p.askingPrice == 0) return 0; return (p.deposit * FEE_DENOMINATOR - p.remainder) / p.askingPrice; } function _state(uint256 id, Plot memory p, uint64 t) internal view returns (State) { if (t >= roundEnd) return State.Ended; uint256 opens = uint256(roundStart) + (id < 32 ? 0 : id < 48 ? 3 days : 7 days); if (t < opens) return State.Locked; if (p.holder == address(0)) return State.Vacant; if (p.depletedAt == 0) return State.Active; if (t < p.depletedAt + CURE_PERIOD) return State.Cure; if (t < p.depletedAt + CURE_PERIOD + AUCTION_DESCENT + AUCTION_FLOOR) return State.Auction; return State.Expired; } function _price(Plot memory p, State state, uint64 t) internal pure returns (uint256) { if (state == State.Vacant || state == State.Expired || p.holder == address(0)) return OPENING_PRICE; if (state == State.Auction) { uint256 elapsed = t - (p.depletedAt + CURE_PERIOD); if (elapsed >= AUCTION_DESCENT) return MIN_PRICE; return p.askingPrice - (p.askingPrice - MIN_PRICE) * elapsed / AUCTION_DESCENT; } return p.askingPrice; } function _burn(uint256 amount) internal { if (amount == 0) return; totalBurned += amount; IBurnableToken(address(token)).burn(amount); } function _credit(address account, uint256 amount) internal { if (amount == 0) return; credits[account] += amount; totalCredits += amount; } function _validId(uint256 id) internal pure { if (id >= CLAIM_COUNT) revert InvalidClaim(); } function _holder(uint256 id) internal view { _validId(id); if (plots[id].holder != msg.sender) revert NotHolder(); } function _checkPrice(uint256 price) internal pure { if (price < MIN_PRICE || price > MAX_PRICE) revert InvalidPrice(); } function _trading() internal view { if (paused()) revert TradingPaused(); uint64 t = gameTime(); if (t < roundStart || t >= roundEnd) revert GameNotActive(); } }