Gas Price Auction

gas-price-auction · auction-allocation · 1264 B runtime · funds-movement

scores

source

pragma solidity ^0.8.13;

contract GasAuction {
    uint256 public immutable endBlock;
    address public winner;
    uint256 public winningBid;
    bool public settled;

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

    constructor(uint256 _endBlock) payable {
        require(_endBlock > block.number, "end must be future");
        endBlock = _endBlock;
    }

    function bid() external {
        require(block.number < endBlock, "auction ended");
        uint256 gasPrice = tx.gasprice;
        require(gasPrice > winningBid, "bid not higher");
        winner = msg.sender;
        winningBid = gasPrice;
        emit Bid(msg.sender, gasPrice);
    }

    function settle() external {
        require(block.number >= endBlock, "auction not ended");
        require(!settled, "already settled");
        require(winner != address(0), "no bids");
        settled = true;
        emit Settled(winner, winningBid);
    }

    function withdraw() external {
        require(settled, "not settled");
        require(msg.sender == winner, "not winner");
        uint256 prize = address(this).balance;
        delete winner;
        (bool ok, ) = msg.sender.call{value: prize}("");
        require(ok, "transfer failed");
        emit Withdrawn(msg.sender, prize);
    }
}