State machines
Many contracts move through stages: an auction is open, then ended, then settled. A state machine models this explicitly with an enum and a variable that holds the current stage. Each function is allowed only in certain stages.
An enum is a named list of values stored as a small integer. A modifier such as atStage checks the current stage before the function runs. This makes the rules easy to read, and it removes a whole class of bugs where a function is called at the wrong time.
Stages change when a function moves the variable forward. Some transitions are triggered by people and some by time. Use block.timestamp for time-based stages, and remember that it can be nudged by a few seconds, so do not depend on exact timing.
Keep transitions one-way when you can. A contract that can only move forward is far easier to reason about than one that can jump between any two stages. Emit an event on every transition so frontends and monitors can follow along. Notice that the bidder refunds below use a pull payment, so one bad bidder cannot block the auction.
contract Auction { enum Stage { Open, Ended, Settled } Stage public stage = Stage.Open; address public seller = msg.sender; uint256 public endTime = block.timestamp + 1 days; address public highBidder; uint256 public highBid; mapping(address => uint256) public refunds; event StageChanged(Stage newStage); modifier atStage(Stage s) { require(stage == s, "Wrong stage"); _; } function bid() external payable atStage(Stage.Open) { require(block.timestamp < endTime, "Time is up"); require(msg.value > highBid, "Bid too low"); if (highBidder != address(0)) refunds[highBidder] += highBid; highBidder = msg.sender; highBid = msg.value; } function end() external atStage(Stage.Open) { require(block.timestamp >= endTime, "Too early"); stage = Stage.Ended; emit StageChanged(stage); } function settle() external atStage(Stage.Ended) { stage = Stage.Settled; emit StageChanged(stage); (bool ok, ) = seller.call{value: highBid}(""); require(ok, "Failed"); } function withdrawRefund() external { uint256 amount = refunds[msg.sender]; refunds[msg.sender] = 0; (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "Failed"); } }
Try it yourself
Add a Cancelled stage that the seller can move to while the auction is Open and nobody has bid. Update the modifiers and compile.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.