Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 47 ยท Projects

Project: A Token and Simple Sale

Build an ERC-20 token and a sale contract that sells it for ether with a price, a per-buyer cap, a deadline and owner withdrawal, then test a JavaScript stand-in.

Selling a token for ether is one of the most common things people do with Solidity, and also one of the easiest ways to lose money through small mistakes: a price calculation that rounds the wrong way, a missing cap, a function anyone can call to take the proceeds. In this project you build two contracts that work together. The first is an ERC-20 token. The second is a sale contract that holds an inventory of tokens and hands them out to anyone who sends ether at a fixed price.

The two contracts show how real systems are put together from small pieces that talk through an interface. The Solidity is read-only, because the site cannot compile or deploy it. A JavaScript stand-in with BigInt money then follows the same rules so you can see the price math and the safety checks run. The stand-in has no real accounts or gas, and a thrown error does not undo changes by itself, so each method checks before it changes anything.

Two contracts, one sale

Token ERC-20 balances and transfers.
Sale Holds inventory, sells for ether.
Owner Withdraws the proceeds.
Buyer Sends ether, receives tokens.

The sale only needs the token's interface, not its code.

1 / 2

The token

The token is a plain ERC-20 as built in Building an ERC-20 Token: balances, a total supply, transfer, and the approve and transferFrom pair. In a real project you would inherit from OpenZeppelin instead (Using OpenZeppelin). It is written out here so the project is self-contained.

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

contract SaleToken {
    string public constant name = "Sale Token";
    string public constant symbol = "SALE";
    uint8 public constant decimals = 18;

    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    error InsufficientBalance();
    error InsufficientAllowance();

    constructor(uint256 initialSupply) {
        totalSupply = initialSupply;
        balanceOf[msg.sender] = initialSupply;
        emit Transfer(address(0), msg.sender, initialSupply);
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _move(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        uint256 allowed = allowance[from][msg.sender];
        if (allowed < amount) revert InsufficientAllowance();
        allowance[from][msg.sender] = allowed - amount;
        _move(from, to, amount);
        return true;
    }

    function _move(address from, address to, uint256 amount) internal {
        if (balanceOf[from] < amount) revert InsufficientBalance();
        balanceOf[from] -= amount;
        balanceOf[to] += amount;
        emit Transfer(from, to, amount);
    }
}

The whole supply is minted to the deployer, which then sends some of it to the sale contract as inventory. Selling out of an inventory the sale already holds is simpler and safer than letting the sale mint tokens: the maximum that can ever be sold is visible as the sale contract's token balance.

The sale contract

Sizes first. The token has 18 decimals, so one whole token is 1e18 base units. The price is stored as wei per whole token. If a buyer sends msg.value wei, they receive msg.value * 1e18 / price base units. The multiplication comes first so that no precision is lost before the division.

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

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract TokenSale {
    IERC20 public immutable token;
    address public immutable owner;
    uint256 public immutable priceWeiPerToken; // wei for 1e18 token units
    uint256 public immutable maxPerBuyer;      // token base units
    uint256 public immutable saleEnds;

    mapping(address => uint256) public bought;

    event Purchased(address indexed buyer, uint256 weiPaid, uint256 tokens);
    event ProceedsWithdrawn(uint256 amount);

    error SaleClosed();
    error NotOwner();
    error AmountTooSmall();
    error SoldOut(uint256 available);
    error OverBuyerCap(uint256 allowed);
    error TokenTransferFailed();
    error WithdrawFailed();

    constructor(IERC20 token_, uint256 priceWei, uint256 maxPerBuyerUnits, uint256 durationSeconds) {
        token = token_;
        owner = msg.sender;
        priceWeiPerToken = priceWei;
        maxPerBuyer = maxPerBuyerUnits;
        saleEnds = block.timestamp + durationSeconds;
    }

    function buy() external payable {
        if (block.timestamp >= saleEnds) revert SaleClosed();

        uint256 amount = (msg.value * 1e18) / priceWeiPerToken;
        if (amount == 0) revert AmountTooSmall();

        uint256 available = token.balanceOf(address(this));
        if (amount > available) revert SoldOut(available);

        uint256 newTotal = bought[msg.sender] + amount;
        if (newTotal > maxPerBuyer) revert OverBuyerCap(maxPerBuyer - bought[msg.sender]);

        bought[msg.sender] = newTotal;                       // effect before interaction
        if (!token.transfer(msg.sender, amount)) revert TokenTransferFailed();
        emit Purchased(msg.sender, msg.value, amount);
    }

    function withdrawProceeds() external {
        if (msg.sender != owner) revert NotOwner();
        uint256 amount = address(this).balance;
        emit ProceedsWithdrawn(amount);
        (bool ok, ) = owner.call{value: amount}("");
        if (!ok) revert WithdrawFailed();
    }
}

How the checks protect you

  • Rounding. Integer division rounds down, so a buyer who sends nothing (or, for a very expensive token, almost nothing) would get zero tokens. The AmountTooSmall check refuses that. A buyer may still overpay by up to one unit of rounding (the "dust"), which stays with the sale. Stricter designs compute the exact cost and refund the difference. Making that change is a good exercise.
  • Inventory. Selling more than the contract holds would make token.transfer revert anyway, but a named error with the available amount is friendlier, and the explicit check keeps the failure close to its cause.
  • Per-buyer cap. A cap is only a soft limit, because one person can use many addresses. It limits accidents and casual hoarding, not a determined whale. If you need real limits, you need an identity check, for example with signed messages (Oracles, Randomness and Off-Chain Data).
  • Order of operations. The buyer's record is updated before the token is sent, so a token with a callback cannot bring the buyer over their cap by calling buy() again from inside the transfer.
  • The deadline. After saleEnds, buy() reverts and unsold tokens remain in the sale. The project has no function for the owner to recover them. Adding one is a useful extension, and so is a refund path if the sale has a minimum.
  • Owner-only withdrawal. withdrawProceeds is guarded and sends the whole balance with call, whose result is checked (Sending and Receiving Ether). Because the owner is one address, a real sale would use a multisig.

The sale trusts the token to behave. A malicious or buggy token could return false or reenter. Here the sale and the token are both yours. When a sale accepts someone else's token, use a safe wrapper such as OpenZeppelin's SafeERC20 and keep state updates before external calls.

The stand-in implementation

The stand-in builds both contracts as classes. Ether and tokens are BigInt, so there are no floating-point surprises, and the price math is the same as in Solidity: multiply first, divide last, and let integer division round down. A tiny Ledger plays the part of the chain's ether balances.

JS Token and sale as JavaScript classes

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

No output.

Read the output against the rules. Ann hits her exact cap and is then refused one more. A buyer sending nothing gets AmountTooSmall. The unauthorized withdrawal fails, and the owner collects the proceeds. After the deadline, nobody can buy.

Testing the price math

Money bugs often live in the arithmetic. This second stand-in checks the formula over many amounts and prices and measures the dust, the wei a buyer paid but did not get tokens for. The properties worth testing are that dust is never negative (nobody gets more than they paid for) and that it stays tiny, no more than the price of one base unit of the token.

JS Property checks for the price formula

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

No output.

Real: the price formula, the rounding direction and the habit of testing properties over many inputs. Stand-in: the classes model balances with maps and have no gas costs, token callbacks or real ether transfers, so the reentrancy and failed-payment paths are discussed in the text but not run here.

Ideas to extend it

  • Exact refunds: compute the cost of the whole tokens bought and send back the dust.
  • Soft cap and refunds: if a minimum amount is not raised by the deadline, allow buyers to claim their ether back, using the pull pattern from Project: Crowdfunding With Refunds.
  • Allowlist: only addresses that present a valid signature may buy.
  • Unsold tokens: after the deadline, let the owner send leftover inventory back or burn it.
  • Pausing: add a pause switch held by a multisig (Modifiers and Access Control).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the price formula compute (msg.value * 1e18) / priceWeiPerToken and not divide first?

    Solidity has only integer division. Multiplying by 1e18 first keeps the fractional part inside the number, and the division at the end rounds down only once.
  2. 2. What does the per-buyer cap really protect against?

    Addresses are free to create, so an address cap is only a soft limit. Real limits need an identity check such as signed approvals.
  3. 3. Why does buy() record bought[msg.sender] before calling token.transfer?

    State changes go before external calls. If the token calls back into buy() during the transfer, the cap already counts the purchase in progress.
  4. 4. In the sale design, where do the tokens that are sold come from?

    The sale holds a fixed inventory of tokens and sells from it. The maximum that can be sold is simply its token balance, which anyone can check.

Summary

  • A token sale is two contracts: an ERC-20 token and a sale that holds an inventory and talks to the token through an interface.
  • Price math in integers: multiply first, divide last, reject zero results, and understand where the rounding dust goes.
  • Guard the sale with a deadline, an inventory check, a per-buyer cap and an owner-only withdrawal.
  • Update your own records before external calls, and check results of call and token transfers.
  • Address-based caps are soft limits. Property tests over many random inputs catch arithmetic mistakes.
  • A single owner address is a risk, so use a multisig for real sales.

Next: Project: Escrow and English Auction.