Solidity Smart Contract Examples: 8 Common Patterns
How eight standard contracts work, from ERC-20 tokens and multi-sig wallets to DAOs, AMMs, NFTs, lending pools, staking and escrow.

This guide walks through eight contract patterns that most Solidity work is built on: fungible tokens, multisig wallets, DAO governance, automated market makers, NFTs, lending markets, staking and escrow. For each one it covers what the contract has to do, which functions do it, and the mistakes that tend to be expensive.
It is a survey of patterns rather than a code tutorial. For line-by-line Solidity, see Solidity tutorial for beginners and how to deploy a smart contract.
1. ERC-20 Token Contract
ERC-20 defines the interface for fungible tokens on Ethereum: a fixed set of functions and events that every token contract implements. Because the interface is fixed, wallets, exchanges and other contracts can handle a token they have never seen before. Stablecoins such as USDT, governance tokens such as UNI and the LINK token all use it.
The core functions are totalSupply, balanceOf, transfer, approve, transferFrom and allowance. The pair that matters most is approve and transferFrom: a user approves a contract to spend a set amount of their tokens, and that contract can then move them. Decentralized exchanges, lending protocols and yield farms all rely on this. It is how a dApp moves a user's funds without holding the user's keys.
Three things to get right:
- Use audited libraries. Do not write an ERC-20 from scratch. OpenZeppelin's implementations are widely used and audited, which removes a whole category of avoidable bugs.
- Compile with Solidity 0.8.0 or later. From 0.8.0, arithmetic is checked for overflow and underflow by default, which was a common source of token exploits before then.
- Put access control on administration. Minting, pausing and parameter changes should sit behind an ownership or role pattern such as
Ownable, so only named addresses can call them.
2. Multi-Signature Wallet Contract
A multisig wallet requires several parties to approve a transaction before it executes. Instead of one private key authorizing a transfer, the contract requires a threshold of owners to sign — 3 of 5, for example. One owner proposes the transaction, the others confirm, and only then does the contract make the call. It is the standard way DAOs, protocols and companies hold funds, because no single compromised key can move the money.

Safe, previously called Gnosis Safe, is the most widely used implementation.
Three things to get right:
- Use a proven implementation. A multisig is simple to describe and easy to get subtly wrong. For anything holding real funds, use an audited one rather than your own.
- Balance security against usability. 2 of 3 or 3 of 5 protects against a single compromised key without making routine payments impossible when one signer is unavailable.
- Test recovery before you need it. Keep each signing key on a hardware wallet, and write down and rehearse what happens when a key is lost, before the wallet holds anything.
3. Decentralized Autonomous Organization (DAO) Contract
A DAO contract encodes an organization's rules on-chain: who can propose, who can vote, what counts as passing, and what happens when a vote passes. The usual components are a governance token that carries voting weight, a proposal mechanism, a vote counter, a treasury and an execution contract.
Uniswap is governed this way, as is MakerDAO, the protocol behind the DAI stablecoin, which rebranded to Sky in 2024. Token holders vote on treasury spending and protocol upgrades. If this is the part of Web3 you want to work in, the board lists DAO roles.
The piece that turns a vote into an action is a Timelock. A passed proposal does not execute immediately; it queues a transaction that can be executed after a fixed delay. That delay is what makes the outcome binding without handing control to an administrator.
Three things to get right:
- Always use a timelock. The delay gives everyone time to read the queued transaction and react if a proposal is malicious or simply wrong.
- Set the quorum carefully. Too low and a small group can pass anything; too high and nothing passes at all. It is worth modeling against your actual token distribution rather than copying a number.
- Plan for emergencies. A security council or pause function can stop an active exploit while the slower governance process catches up.
4. Automated Market Maker (AMM) Contract
An AMM replaces an exchange's order book with a liquidity pool. Rather than matching buyers to sellers, users trade against the pool, and price comes from a formula. The best-known is the constant product formula, x * y = k: as a trade removes one asset from the pool, that asset gets more expensive relative to the other. Uniswap introduced the model, and Curve adapted it for assets that should trade close to parity, such as stablecoins.
Anyone can supply liquidity and earn a share of the fees, which is the part that was previously limited to firms. Uniswap v2 charges 0.30% on every swap and adds it to the pool, raising the value of each LP share; Uniswap v3 offers several fee tiers instead of a single rate.
Large trades move the price inside the pool away from the wider market. That gap is the slippage a trader pays, and it is also the profit an arbitrageur takes for trading the pool back into line — which is how the pool tracks market prices without anyone managing it.
Three things to get right:
- Require slippage protection. Every swap should take a
minAmountOut, so a user who submits a trade and waits for confirmation cannot be filled at a far worse price than they saw. - Never use the spot price as an oracle. An instantaneous pool price can be pushed a long way in a single transaction. Use a time-weighted average price if other contracts read your pool.
- Consider dynamic fees. A flat fee is fine to start. Fees that rise with volatility compensate liquidity providers better for the risk they carry in fast markets.
A walkthrough of a constant-product AMM in Solidity 0.8, from the Smart Contract Programmer channel:
5. NFT (Non-Fungible Token) Contract
An NFT contract, usually ERC-721 or ERC-1155, tracks ownership of individual items rather than balances. Every token has its own ID and its own owner. ERC-721's core functions are ownerOf, which returns the owner of a token ID, and transferFrom, which moves it. Each token also has a tokenURI, a link to a JSON file holding its name, description, image and traits.

The standard runs profile picture collections like Bored Ape Yacht Club, generative art platforms like Art Blocks and collectibles like NBA Top Shot. Because ownership and traits are readable by any other contract, the same token can gate a Discord, unlock an in-game item or stand in for an identity. Roles building these systems show up on the board as NFT jobs.
Three things to get right:
- Keep metadata off your own server. Point the
tokenURIat IPFS or similar, so the art and traits survive your company and cannot be quietly swapped. - Optimize minting gas. For large collections, ERC-721A, written by the Azuki team, makes minting several tokens in one transaction much cheaper than a naive loop.
- Publish royalties with EIP-2981, but do not assume they are paid. The standard is a way for a contract to state its royalty terms so a marketplace can read them. It does not enforce anything, and marketplaces have differed on whether to honor creator fees.
6. Lending and Borrowing Protocol Contract
A lending protocol lets users deposit assets into a pool to earn interest, or post assets as collateral and borrow against them. Interest rates, collateral ratios and liquidations are handled by the contracts, with no underwriter in the middle. Aave and Compound are the reference implementations.
The main functions are supply, withdraw, borrow, repay and liquidate. Everything depends on pricing collateral correctly and closing risky positions before they turn into bad debt. Liquidation is what keeps the protocol solvent: by paying a discount to anyone who repays an undercollateralized loan, the protocol pays outsiders to watch its books continuously. Jobs in this corner of the market are listed under DeFi roles.
Three things to get right:
- Use a resilient price oracle. A single price source is an attack surface. An aggregating oracle such as Chainlink is much harder to push around than one pool or one exchange.
- Start with conservative collateral factors. Low loan-to-value ratios and early liquidation thresholds cost users some capital efficiency and buy the protocol a margin against sudden price drops.
- Build in a pause. A governance- or multisig-controlled switch on borrowing and withdrawals is what limits the damage when a vulnerability surfaces.
7. Staking Contract
A staking contract locks tokens and pays rewards for keeping them locked. On a proof-of-stake network the stake backs consensus; in DeFi it usually backs a yield or governance program. Ethereum's staking deposit contract holds the stake that secures the network, and liquid staking protocols such as Lido and Rocket Pool issue a transferable token representing a staked position, so the capital is not idle while it is locked.
The core functions are stake, unstake and claimRewards, with reward accounting that tracks how long and how much each participant has staked. Two mechanisms shape behavior: slashing, which destroys part of a validator's stake for misbehavior, and an unbonding period, which stops everyone leaving at once.
Three things to get right:
- Make reward math predictable. Time-weighted rewards that anyone can recompute from on-chain state are harder to game and easier to explain than a discretionary schedule.
- Define slashing precisely. For consensus staking, spell out exactly what is penalized — double-signing, prolonged downtime — and by how much.
- Include an emergency exit. A withdrawal path controlled by governance or an admin lets users recover funds if the contract turns out to be broken.
8. Escrow and Payment Contract
An escrow contract holds funds from one party and releases them to another when an agreed condition is met. There is a payer, a payee and often an arbiter, and the contract is a state machine: funds are locked until both sides agree the work is done, or until the arbiter decides. It is the pattern behind milestone-based freelance payments and marketplace sales where money should not move before delivery.

Three things to get right:
- Name every state and every transition. States such as
AwaitingPayment,AwaitingDelivery,FundsReleasedandInDispute, with strict access control on each transition — only the payer deposits, only the arbiter resolves. - Add a timeout. Without one, a party who walks away leaves the funds locked forever. A reclaim function after a set period of inactivity prevents that.
- Define the arbiter in the contract. If there is a tiebreaker, the contract should say who it is, when they can act and that their decision settles the matter.
Comparing the eight patterns
| Contract type | Build complexity | Typical use | What the pattern gives you |
|---|---|---|---|
| ERC-20 token | Moderate — fixed interface, well documented | Currencies, utility and governance tokens | Works with any wallet, exchange or contract that speaks ERC-20 |
| Multi-signature wallet | High — multi-party state and approval tracking | Treasuries and shared funds | No single key can move the money |
| DAO | High — voting, quorum and execution logic | Protocol governance, community treasuries | Decisions execute on-chain without an administrator |
| Automated market maker | High — pricing math and pool accounting | Token swaps, decentralized exchanges | Trading with no order book and no market maker |
| NFT | Moderate — per-token ownership and metadata | Art, collectibles, game items, access passes | Ownership of a specific item, readable by other contracts |
| Lending protocol | High — interest rates, collateral checks, liquidation | Money markets, collateralized loans | Borrowing and lending with no underwriter |
| Staking | Moderate to high — reward accounting and penalties | Consensus participation, yield programs | Pays users for locking capital |
| Escrow | Moderate — state machine plus a dispute path | Freelance payments, marketplace sales | Payment released on a condition rather than on trust |
Where to go next
These patterns get combined more often than they get used alone. A DAO usually holds its treasury in a multisig and votes with an ERC-20 token; a lending protocol reads an oracle and is governed by a DAO. Knowing which pattern solves which problem matters more than knowing every language feature.
Three ways to practice:
- Rebuild one from scratch. Take the escrow or staking pattern and write it without reference. The state variables you forget are the ones you did not really understand.
- Combine two. Design a DAO that votes with an ERC-20 token and pays from a multisig treasury. That combination is most real protocols.
- Attack your own code. Run Slither or Mythril over it, and write tests in Hardhat or Foundry that try to break it rather than confirm it works. Securing smart contracts covers the common failure modes.
For the route into the job itself, see the blockchain developer roadmap. For what these roles pay, Web3 salaries shows medians from listings that state pay, and the Web3 jobs report tracks hiring by month and category. Open roles are on the board under smart contract and Solidity.