SlotAuction

slotauction · auction-allocation · 1687 B runtime · funds-movement

scores

source

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

/// @title SlotAuction - single-slot priority auction with withdraw pattern
contract SlotAuction {
    address public immutable seller;
    address public winner;
    uint256 public highestBid;
    uint256 public immutable endTime;
    bool public settled;

    mapping(address => uint256) public pendingRefunds;

    event Bid(address indexed bidder, uint256 amount);
    event Settled(address indexed winner, uint256 amount);

    constructor(uint256 _duration) {
        seller = msg.sender;
        endTime = block.timestamp + _duration;
    }

    function bid() external payable {
        require(block.timestamp < endTime, "auction over");
        require(msg.value > highestBid, "bid too low");
        if (highestBid > 0) {
            pendingRefunds[winner] += highestBid;   // outbid -> withdraw pattern, no inline refund
        }
        winner = msg.sender;
        highestBid = msg.value;
        emit Bid(msg.sender, msg.value);
    }

    function settle() external {
        require(block.timestamp >= endTime, "auction live");
        require(!settled, "already settled");
        require(msg.sender == seller, "not seller");
        settled = true;
        (bool ok, ) = payable(seller).call{ value: highestBid }("");
        require(ok, "payout failed");
        emit Settled(winner, highestBid);
    }

    function withdraw() external {
        uint256 amt = pendingRefunds[msg.sender];
        require(amt > 0, "nothing to withdraw");
        pendingRefunds[msg.sender] = 0;
        (bool ok, ) = payable(msg.sender).call{ value: amt }("");
        require(ok, "withdraw failed");
    }
}