Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 47 ยท Projects

Project: Escrow and English Auction

Build two classic contracts: an escrow with a buyer, seller and arbiter, and an English auction with timed bids and pull refunds, and test them in a JavaScript stand-in.

Two of the oldest ideas in commerce translate well to contracts. An escrow holds money while a buyer and seller finish a deal, so neither has to trust the other first. An auction lets many people compete for one item and gives the money to the winner's seller while everyone else gets their bids back. Both are about holding other people's money, so the main lesson of this project is care: who can take the funds out, when, and what happens at the awkward moments.

You will read both contracts in Solidity (read-only, since the site cannot compile or deploy it) and then run JavaScript stand-ins with the same rules. The stand-ins are not Solidity: there is no real ether, a clock field plays the part of block.timestamp, and a thrown error does not undo changes by itself, so every method checks before it changes anything.

Escrow: three parties

Buyer Locks the payment in.
Seller Gets paid when the buyer is happy.
Arbiter Settles a dispute either way.

Only the exact agreed amount can be deposited, and only once.

1 / 2

Part one: the escrow

The escrow has one job: hold the buyer's payment until one of two things happens. The buyer is satisfied and releases the money to the seller, or the deal falls apart and the money goes back to the buyer. If buyer and seller disagree, a third party, the arbiter, can decide either way. The arbiter must be neither the buyer nor the seller, or the dispute process means nothing.

stateDiagram-v2
    [*] --> AwaitingPayment
    AwaitingPayment --> Funded: buyer deposits the exact price
    Funded --> Released: buyer or arbiter releases
    Funded --> Refunded: seller or arbiter refunds
    Released --> [*]
    Refunded --> [*]

Once the escrow leaves Funded, it never changes again.

Notice who may do what. The buyer can release (their own money, their own decision), but the buyer cannot refund themselves, because a buyer who could take the money back after receiving the goods would defeat the point. The seller can refund (giving up the deal), but cannot release to themselves. The arbiter can do either.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Escrow {
    enum State { AwaitingPayment, Funded, Released, Refunded }

    address public immutable buyer;
    address public immutable seller;
    address public immutable arbiter;
    uint256 public immutable price;

    State public state;
    mapping(address => uint256) public pending; // pull-payment balances

    event Deposited(uint256 amount);
    event Released(address indexed to, uint256 amount);
    event Refunded(address indexed to, uint256 amount);
    event Withdrawn(address indexed who, uint256 amount);

    error BadParties();
    error NotAllowed();
    error WrongState(State current);
    error WrongAmount(uint256 expected);
    error NothingToWithdraw();
    error TransferFailed();

    constructor(address seller_, address arbiter_, uint256 price_) {
        if (seller_ == msg.sender || arbiter_ == msg.sender || arbiter_ == seller_) revert BadParties();
        buyer = msg.sender;
        seller = seller_;
        arbiter = arbiter_;
        price = price_;
    }

    function deposit() external payable {
        if (msg.sender != buyer) revert NotAllowed();
        if (state != State.AwaitingPayment) revert WrongState(state);
        if (msg.value != price) revert WrongAmount(price);
        state = State.Funded;
        emit Deposited(msg.value);
    }

    function release() external {
        if (msg.sender != buyer && msg.sender != arbiter) revert NotAllowed();
        if (state != State.Funded) revert WrongState(state);
        state = State.Released;
        pending[seller] += price;
        emit Released(seller, price);
    }

    function refund() external {
        if (msg.sender != seller && msg.sender != arbiter) revert NotAllowed();
        if (state != State.Funded) revert WrongState(state);
        state = State.Refunded;
        pending[buyer] += price;
        emit Refunded(buyer, price);
    }

    function withdraw() external {
        uint256 amount = pending[msg.sender];
        if (amount == 0) revert NothingToWithdraw();
        pending[msg.sender] = 0;
        emit Withdrawn(msg.sender, amount);
        (bool ok, ) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}

Two design choices deserve a comment. First, release and refund do not send ether: they credit the winner's pending balance and change the state, and the winner calls withdraw() to collect. That is the withdrawal pattern again (Sending and Receiving Ether): a recipient whose address rejects payments can never freeze the state change. Second, the state is changed first, so the same funds cannot be released and refunded. The arbiter is a trusted role and a single point of failure, so in real use it should be a multisig (Project: A Multisig Wallet) or a clear, publicly agreed process.

Part two: the English auction

In an English auction bids go up. Everyone sees the highest bid, and anyone may beat it until the clock runs out. The tricky part is what to do with the money of the person who was just outbid. The obvious but dangerous approach is to refund them inside bid(): if their address rejects ether, then bid() reverts for everyone, and that bidder blocks the auction at the current price forever. This is a known denial-of-service bug.

The safe approach is again the pull pattern. When a new highest bid arrives, the previous leader's money is added to a pending balance, and the previous leader withdraws it whenever they like.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract EnglishAuction {
    address public immutable seller;
    uint256 public immutable endTime;

    address public highestBidder;
    uint256 public highestBid;      // starts at the reserve price
    bool public finalized;
    mapping(address => uint256) public pending;

    event NewBid(address indexed bidder, uint256 amount);
    event Finalized(address indexed winner, uint256 amount);
    event Withdrawn(address indexed who, uint256 amount);

    error AuctionEnded();
    error AuctionNotEnded();
    error AlreadyFinalized();
    error SellerCannotBid();
    error BidTooLow(uint256 mustExceed);
    error NothingToWithdraw();
    error TransferFailed();

    constructor(uint256 reservePrice, uint256 durationSeconds) {
        seller = msg.sender;
        highestBid = reservePrice;
        endTime = block.timestamp + durationSeconds;
    }

    function bid() external payable {
        if (block.timestamp >= endTime) revert AuctionEnded();
        if (msg.sender == seller) revert SellerCannotBid();
        if (msg.value <= highestBid) revert BidTooLow(highestBid);

        if (highestBidder != address(0)) {
            pending[highestBidder] += highestBid;   // credit, do not send
        }
        highestBidder = msg.sender;
        highestBid = msg.value;
        emit NewBid(msg.sender, msg.value);
    }

    function finalize() external {
        if (block.timestamp < endTime) revert AuctionNotEnded();
        if (finalized) revert AlreadyFinalized();
        finalized = true;
        if (highestBidder != address(0)) {
            pending[seller] += highestBid;
        }
        emit Finalized(highestBidder, highestBid);
    }

    function withdraw() external {
        uint256 amount = pending[msg.sender];
        if (amount == 0) revert NothingToWithdraw();
        pending[msg.sender] = 0;
        emit Withdrawn(msg.sender, amount);
        (bool ok, ) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}

Anyone may call finalize(), which is fine because it only moves money to the right accounts once. Because the reserve price is stored as the first highestBid, the first real bid must exceed the reserve. If no one bids, nothing is credited and the item (which lives off-chain in this simple version) stays with the seller. A real auction for an on-chain asset such as an NFT would also hold the asset in the contract and transfer it to the winner on finalize().

The awkward moments

Edge cases are where auctions go wrong. Write down each of these and decide what the contract does:

  • A bid in the very last second. Here, block.timestamp >= endTime is closed, so a bid exactly at the end time is refused. Whichever side of the line you pick, state it.
  • Sniping. A bidder who bids one second before the end gives others no time to react. Some auctions extend the deadline when a late bid arrives. That adds complexity and the extension must be limited, or an auction can be stretched forever.
  • A bid equal to the highest bid. Refused: bids must be strictly higher, so the earlier bidder wins ties.
  • The seller bidding on their own item to inflate the price is blocked, although they could still use a second address. Contracts cannot fully stop that, which is a general limit of address-based rules.
  • Block timestamps. Producers can shift them slightly, which is fine for auctions that last hours, and a poor basis for a five-second auction.
  • Forgotten withdrawals. Pull payments mean money may sit in pending for a long time. That is safe, but the contract should make the balance easy to see.

The stand-in implementation

Both contracts are modeled below. A small Bank object plays the part of the chain's ether: withdraw moves a credited amount into a wallet. The demo runs the happy paths and then pokes at each awkward moment.

JS Escrow and auction as JavaScript classes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the happy path, only the exact amount from the buyer is accepted, the seller cannot release money to themselves, and a second withdrawal finds nothing. In the dispute, the buyer cannot take the money back alone, and the arbiter's refund is what finally returns it.

The auction follows, including outbid refunds, the end-time boundary and a bidder who rejects payments to show why pull refunds matter.

JS The English auction, with edge cases

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at what the pull pattern buys. Bo's address rejects payments, yet Cy's bid went through and Dee's too, because outbidding never tried to send money. Bo's refund just sits in pending until Bo can receive it.

Real: the state machines, the credit-then-withdraw pattern, the strict inequalities and the edge-case list. Stand-in: amounts are plain numbers, the clock is a field, and rejecting is a flag that imitates a contract with a failing receive. A real contract would also be tested against reentrancy and gas limits (Testing Contracts).

Ideas to extend it

  • Escrow timeout: if the arbiter and buyer both vanish, let the seller claim after a long delay, or the buyer refund, and decide which.
  • Minimum increment: require each bid to beat the last by a percentage, to stop pennies-at-a-time bidding.
  • Anti-sniping: extend the end time by a few minutes when a bid arrives near the end, with a hard cap on total extensions.
  • Asset auction: hold an NFT in the contract (ERC-721 NFTs) and transfer it on finalize().
  • Events and a front end: use the events to show bids live (Events and Logs).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the auction credit the outbid bidder's pending balance instead of sending the money back inside bid()?

    Pushing money to an arbitrary address lets that address veto the transaction. With the pull pattern the outbid bidder only affects their own later withdrawal.
  2. 2. In the escrow, why can the buyer not call refund() on their own?

    Refund is allowed to the seller (giving up the deal) or the arbiter (settling a dispute), but not to the buyer, who would otherwise keep both the goods and the money.
  3. 3. The auction rejects a bid equal to the highest bid. What does that decide?

    Requiring a strictly higher bid means a tie never replaces the current leader, so the earlier bid wins.
  4. 4. What is the purpose of the finalized flag?

    finalize() can be called by anyone. The flag turns every call after the first into a revert, so the winning bid cannot be credited to the seller twice.
  5. 5. Which edge case is NOT fully solvable by address-based checks in the contract?

    Time, state and amount checks are enforceable. Nothing on chain proves that two addresses belong to the same person, so shill bidding cannot be blocked by address rules alone.

Summary

  • An escrow holds a payment while a deal completes: the buyer deposits the exact price, and the buyer or arbiter releases it to the seller, or the seller or arbiter refunds it to the buyer.
  • Assign each action to the parties whose interests it matches, and keep the arbiter independent.
  • An English auction needs strictly higher bids, a fixed end, and a one-time finalize.
  • Never push money to an arbitrary address inside a state-changing function. Credit a pending balance and let the recipient withdraw.
  • Write down the awkward moments (the last second, ties, sniping, shill bids) and decide each one on purpose.
  • Test every state transition and the failure paths, not just the happy path.

Next: Project: A Multisig Wallet.