Smart Contracts: The Ultimate Guide (with 5 Examples)

Smart contracts are the backbone of blockchain games, NFT collections, and web3 apps. Learn more about the different types of smart contracts.

Smart Contracts: The Ultimate Guide (with 5 Examples)

Smart contracts are at the core of web3. They are pieces of code that live on the blockchain and work like vending machines: Give them an input and they do the rest — be it transferring funds, registering ownership, or anything else that pre-defined.

From simple token swaps and lending transactions to complex social media algorithms and DAO governance, smart contracts power most of web3.

That means, there’s a wide range of smart contracts that developers can choose to build.

But what are these types of smart contracts?

In this blog, we will explain what smart contracts are and the different types of smart contracts that you can build or use.

What are smart contracts?

Smart contracts are pieces of code that reside on a blockchain, and they automatically execute predefined actions when certain conditions are met. This execution happens without the need for any human involvement. Also, smart contracts operate transparently with the actions immutably recorded on a blockchain.

Ethereum was the first blockchain to introduce smart contract functionality. To simplify the web3 development process, Ethereum introduced Solidity, a programming language custom-built to write and implement smart contracts.

Technically, smart contracts are Ethereum accounts, or contract accounts to be specific. They are:

  • an ‘account’ because they can hold, receive, and send ETH and other tokens.
  • a ‘contract’ because once deployed they are not controlled by any user and they run as programmed.
💡
History of smart contracts: Nick Szabo coined the term "smart contract" in 1994. And in 1996, he delved into the potential applications of smart contracts.

But today, Ethereum isn’t the only network with smart contacts. There are hundreds of blockchains where developers can build smart contracts and deploy web3 applications. However, to avoid any confusion, we’ll look at most definitions from the perspective of Ethereum contracts.

Now, let’s dive into how smart contracts actually work.



How do smart contracts work?

Using phrases like ‘logic coded into blockchain’ and ‘automatic execution’ is great while explaining how a smart contract works. But, in reality, how does this all unfold?

A smart contract is composed of two things:

  • Code: The set of rules and functionalities programmed into the contract. It defines what the contract can do and under what conditions.
  • State: It represents the contract's state or the current information that the contract holds. It can include things like account balances or ownership status.

The lifecycle of a smart contract from creation to execution unfolds like this: creation > contract deployment > transaction initiation > transaction execution > even logging.

Let’s break each one down to better understand the process.

Creation

The creation stage is where the developer writes the smart contract using programming languages like Solidity or Vyper. Here, developers can set conditions for execution, define functions, and establish how the contract will interact with data and other contracts on the blockchain.

Integrated development environments (IDE) like Remix IDE help developers write, test, and deploy Solidity smart contracts on the Ethereum blockchain.

Contract deployment

The process of deploying a smart contract starts in a testnet, a sandboxed environment, to iron out code vulnerabilities without risking real assets or users.

After making the changes, developers compile the Solidity code into bytecode i.e. a language that the Ethereum virtual machine (EVM) understands. Finally, developers use the constructor function to initialize the contract on the blockchain. This function can only be invoked once.

💡
Learn more about EVMs and EVM-compatible blockchains.

Transaction initiation

An externally owned account (EOA), i.e. a user account, initiates a transaction by sending a transaction to the smart contract's address on the blockchain. The transaction must include data specifying the function to execute, any required parameters, and sufficient gas to cover the execution cost.

Transaction execution

Transaction execution happens when the EOA-initiated transaction calls the specific functions of the smart contract account.

For example, An EOA wanting to swap ETH for USDT through Uniswap would interact with Uniswap's smart contracts. In this transaction, the EOA calls distinct functions within the smart contract for the swap to take place:

  • approve: The EOA authorizes the Uniswap contract to use a certain amount of its USDT tokens.
  • swapExactETHForTokens: The smart contract processes the swap, handling exchange rates and liquidity pools. The function also specifies minimum amounts and addresses to send the tokens to.
  • block.timestamp: The smart contract can utilize this variable as a data point, representing the current time to immutably time-stamp the swap transaction.

Event logging

Events in smart contracts serve as notifications to decentralized applications (dApps), blockchain explorers, and other sources about changes made to the contracts. They can listen to these events and use them to trigger and execute dependent logic accordingly.

For example, event logging helps in updating DeFi users’ portfolio balances.

Most smart contracts have no time limits. However, there are a few contracts like those of escrow services and betting platforms that come with an expiry date and time. So, the majority of smart contracts are timeless and perform their duties whenever interacted with. The lifecycle of a smart contract might also have a predefined end like in the case of using the selfdestruct function.

💡
Did you know?The selfdestruct function was initially known as SUICIDE opcode.


Types of smart contracts

Smart contracts have versatile applications. From minting tokens with token contracts to making decisions through governance contracts, smart contracts can be tailored to meet specific needs. However, today, we are only delving into the most popular smart contract types.

Token contracts

Token smart contracts are pieces of code deployed on a blockchain that are used to create digital tokens. They specify attributes like token name, symbol, and supply, and implement functions for transferring tokens between accounts, approving transactions, and checking balances.

ERC-20 and ERC-721 are widely used token contract standards on the Ethereum network.

Fungible tokens

Fungible tokens are based on the ERC-20 token standard on Ethereum. These fungible tokens are exactly equal to any other token and no tokens possess special rights or behaviors.

This versatility makes ERC-20 tokens ideal for various applications such as medium of exchange currency, voting rights, staking, and more.

This ERC-20 token contract actively manages the minting and burning of USDC, a stablecoin issued by a fintech company Circle. In this token contract, key pointers to take note of are:

  • minter: The function responsible for both minting and burning USDC tokens.
  • totalSupply: The variable that tracks the number of USDC tokens in circulation.
  • pause: The function that allows Circle to pause the minting and burning of USDC tokens, in case of a bug or key compromise.

Create an ERC-20-compliant digital currency using thirdweb’s read-to-deploy smart contract.

Non-fungible tokens

Non-fungible tokens (NFTs) are majorly based on the ERC-721 token standard on Ethereum. NFT smart contracts manage NFTs by ensuring the contract address, uint256, and tokenId are globally unique. The contract contains functions for minting, transferring, and inquiring about token ownership, and is pivotal in domains like digital art and collectibles.

CryptoPunks, a notable NFT collection of 10,000 unique characters, is powered by 250 lines of code. Amongst these, the game-changer functions are:

  • nextPunkIndexToAssign: Gives a new, successive index to every Punk being minted.
  • PunkBidEntered: Specifies the highest bid made for a CryptoPunk by a specific EOA.
  • address onlySellTo: Defines that each NFT can be wholly sold only to one person i.e. one EOA.

For more, see thirdweb’s smart contract library which contains a suite of NFT-related smart contracts from NFT minting to rentals.

Marketplace contracts

Marketplace contracts are smart contracts that facilitate the buying, selling, and trading of assets on a blockchain. They play a crucial role in the DeFi and NFT space by creating the foundation for decentralized marketplaces.

These contracts automate the trading process and ensure transparency and security of asset transfers. Blur and Uniswap are marketplaces where smart contracts replace any central authority to ensure permissionless on-chain trading.

Here is the official source code of Uniswap, a decentralized exchange (DEX). It involves multiple key smart contracts that coordinate to enable trading.

Two key smart contracts are:

  • pairs: the smart contract responsible for the creation of automated market makers (AMMs).
  • pool: the smart contract that maintains the liquidity pools using the amount*Desired parameters.
💡
Bonus: To learn more about Uniswap and its smart contracts, you can read their official documentation.

Creating a marketplace from scratch can be a tall order. But, you can use thirdweb’s marketplace smart contracts can things significantly easy for you.

Airdrop contracts

The primary function of an airdrop smart contract is to transfer tokens to a list of recipient addresses. Although it sounds like a simple call to a .send() or .transfer() function, the contract has a lot more to offer.

Right from qualifying recipients using whitelisting and eligibility criteria to the vesting of airdropped tokens, these contracts are highly-modular.

Airdrop contracts may also incorporate batch processing to handle large numbers of transactions efficiently, reducing the gas fees involved.

The Arbitrum airdrop was one of the most anticipated airdrops and over 700,000 addresses interacted with their official airdrop contract.

The key attributes of this airdrop contract are:

  • transferOwnership: A function that the owner (Arbitrum Foundation) calls to transfer the control of airdrop tokens to the smart contract. In this instance, the smart contract took control and airdropped over 1.1 billion $ARB tokens.
  • uint256 deadline: The variable that pre-defines the last date and time for eligible addresses to claim the airdrop.

You can check out thirdweb’s comprehensive guide on how to airdrop ERC-20 tokens to specific wallet addresses. Use the airdrop contract mentioned in this guide for free.

Smart wallets

Smart wallets are web3 wallets that use smart contracts for their transactional abilities. Instead of using an EOA to initiate a transaction and pay gas fees, smart wallets use UserOperation. It is a transaction-like structure that describes the execution terms and the necessary data for the verification.

This smart contract flexibility allows smart wallets to enjoy many benefits over regular (EOA) wallets. They can perform batch transactions, define transfer limits, assign guardians or recovery options, conduct multisig transactions, and much more.

💡
Learn more about smart wallets in our blog: What is a Smart Contract Wallet?

Argent is a smart wallet provider. It is a non-custodial wallet offering features like recovery without seed phrases, trusted contacts, and multisig. Argent’s smart contract architecture has key attributes like:

  • isValidSignature(): A function that validates messages signed by smart wallets similar to how EOAs sign messages with private keys.
  • GuardianManager: A smart contract that manages the EOA-based guardians who help in the social recovery of the smart wallet.
  • multiCall: A function to batch multiple transactions into a single transaction before posting on-chain. thirdweb has documented how to deploy a smart wallet. You can also find the contract library for the creation of a smart wallet.

How to get started with smart contracts

Creating a smart contract usually requires writing it in a programming language that supports it (with the most popular being Solidity), testing & debugging it to ensure it’s secure, and deploying it to the blockchain.

But with thirdweb, you can skip all of this & deploy smart contracts easily — using a library of pre-built & audited smart contracts for any application, with the option to add custom extensions for advanced functionality on top:

thirdweb Explore: Smart Contracts & Protocols
Browse a large collection of ready-to-deploy contracts that have been built by thirdweb and other contract developers. Find a contract for your specific app’s or game’s needs.

Smart contracts & the future of the internet

Smart contracts that initially started as simple digital ‘if - then’ statements are today the backbone of the web3 space. Learning about them is necessary as we move towards this new iteration of the internet.

We hope this blog has helped you better understand what smart contracts are, how they work, and more importantly, their different types.

If you have any questions, join 40,000+ other builders in our Discord community or reach out to the team directly for more info on how to get started with writing smart contracts, deploying them in dApps, and much more.

And if you want to deploy smart contracts in dApps of your own, get started with thirdweb’s smart contracts library, web3 tools, and SDKs — they’re free!