Smart Contracts: Code that Executes Itself

Charlie J
Charlie J
|
Published on 08 Jul 2025

🤖 What is a smart contract?

A smart contract is a type of computer program that runs on a blockchain. It automatically carries out agreements when certain rules are met. Unlike traditional contracts, which are written on paper and need people like lawyers or judges to enforce them, smart contracts use code and are enforced by the blockchain network itself.

smart contractsSmart contracts let people and organizations make automated and trustless agreements. You don’t need to trust the other person, a middleman, or a bank. The code makes sure the rules are followed. This can make digital agreements faster, cheaper, and more reliable.

Smart contracts became popular with Ethereum, a blockchain launched in 2015. Before Ethereum, Bitcoin used simple scripts for payments. Ethereum made it possible for anyone to write more complex programs on the blockchain. This change allowed developers to build new kinds of apps, called decentralized applications (dApps).

🧠 What makes a contract "smart"?

The “smart” part means these contracts can run by themselves when the right conditions are met. Traditional contracts are written in everyday language and need people to read and enforce them. Smart contracts are written in programming code, so computers can run them automatically.

Smart contracts always produce the same result if given the same input. When a smart contract is deployed, it runs on every computer (node) in the blockchain network. All nodes must agree on the result, so there’s no confusion or disagreement.

Once added to the blockchain, most smart contracts cannot be changed or deleted. This is called immutability. It gives users confidence that the rules won’t change later. However, it also means it is very hard to fix mistakes or bugs. Some smart contracts can be upgraded if they are designed in a special way, called proxy contracts. They achieve this through a proxy pattern where the proxy contract delegates calls to an implementation contract that can be swapped out.

🔑 Key properties of smart contracts

Smart contracts have special features that make them powerful and reliable. These properties explain how they work and why they are useful:

  • Trustless execution: You don’t have to trust the other person or any third party. The blockchain enforces the contract automatically.

  • Transparency and auditability: Anyone can look at the contract’s code and see what it does. All actions are recorded on the blockchain, creating a permanent record.

  • Atomicity: Actions in a smart contract either happen completely or not at all. If part of a transaction fails, the whole thing is canceled.

  • Composability: Smart contracts can work together. One contract can call another, allowing developers to build complex apps from smaller parts.

  • Gas costs and limits: Every action a smart contract takes costs a small fee, often called a gas fee, paid in the blockchain's native token (ETH for Ethereum, SOL for Solana, etc.). This prevents people from overloading the network with complicated or endless operations. Not all blockchains refer to their fees as gas. For example, Solana uses the term 'transaction fee'.

🌍 Real-world use cases

Smart contracts are already being used in many areas. Here are some examples of how they power real applications on the blockchain:

Other uses include holding money until certain conditions are met (escrow), tracking products in a supply chain, and selling event tickets securely.

NOTE: Consider taking a small break before moving on. Review what you've learned above.

🏗️ Basic smart contract structure (Solidity example)

Smart contracts are made up of functions, which are blocks of code for specific tasks. It's important to understand the visibility of a function. Function visibility controls who can call (execute) your functions. It's like setting permissions on different rooms in a building. Some are open to everyone, others are restricted.

Here is a simple example using Solidity, the main language for Ethereum smart contracts. You do not need to know what all of this code does at the moment. We are only focusing on the visibility of the function and other key concepts of smart contract code, as underlined in red.

Example of a Solidity smart contractIf any of this seems a bit difficult, that's ok. We are only focusing on the meaning of the terms for now. In future lessons we will dive a bit deeper into the code.

Public Functions

Anyone can use this function from outside the contract.

  • Open to everyone. Any person or other contract can call it.

  • Think of it as a public library. Anyone can enter.

  • Example: getBalance() - anyone can check the wallet balance.

Private Functions

These functions are only accessible within the same contract.

  • Hidden from outsiders. Only works inside this specific contract.

  • Just like your bedroom is private, only you can use it.

  • Example: _updateBalance() - only internal contract logic can change the balance.

View Functions

Look at data but don't modify anything.

  • This is a read-only function. Anyone can see the information but cannot change it.

  • Similar to looking through a window. You can see what's on the other side, but can't touch it.

  • Example: getBalance() - returns the balance without changing it.

Pure Functions

Work with only the inputs you give them. They don't read or change contract data.

  • They are self-contained, only use the parameters (information or data) passed in, nothing from storage.

  • Works like a calculator. Only uses numbers you type in.

  • Example: calculateFee() - takes an amount and returns 3% without reading any stored data.

Note: State variables (like owner and balance) store information on the blockchain. Pure functions ignore this stored information completely.

Events

Example of an event in SolidityEvents let your contract announce when something important happens.

  • Use event to define what information you want to broadcast

  • Use emit to actually send the announcement

  • External apps can listen for these events to track contract activity

Access control

Example of an onlyOwner modifier in SolidityControl who can use specific functions in your contract.

  • Create rules that check if someone has permission before they can act.

  • Think of it as a bouncer at a club. They check your ID before letting you in.

  • Use modifier to write the permission rule once, then apply it to any function.

  • Example: onlyOwner - only the contract owner can withdraw funds.

Constructor functions

Example of a constructor in SolidityThe constructor sets up your contract when it's first created on the blockchain.

  • Runs exactly once, when the contract is deployed.

  • Perfect for setting the initial owner, starting values, or creation timestamp.

  • It's like your contract's birth certificate. It records who created it and when.

  • Example: constructor() - saves the deployer as owner and records creation time.

Fallback functions

Example of fallback functions in SolidityFallback functions handle unexpected situations in your contract.

  • receive() catches direct ETH payments sent to your contract.

  • fallback() catches calls to functions that don't exist.

  • Consider them emergency handlers, like having a "catch-all" mailbox for misdirected mail.

  • Example: Someone sends ETH directly to your contract address, receive() handles it.

⚙️ How do smart contracts run?

Smart contracts run when someone sends a transaction to call one of their functions. They cannot run by themselves natively, but automation services like Chainlink can trigger them on schedules or when conditions are met.

There are two main types of operations:

  • Read operations (like checking a balance): Free if run locally, do not change the contract.

  • Write operations (like sending tokens): Change the contract’s data and cost gas.

Each transaction sets a gas limit, the maximum amount of gas or effort. If the contract tries to use too much gas, the operation fails and all changes are canceled.

The usual process: validate the transaction, check who is allowed to call the function, run the code, update the contract’s data, and send any events.

💻 Languages and platforms

Here are some of the most commonly used smart contract languages:

  • Solidity: The main language for Ethereum and similar blockchains. Syntax is similar to JavaScript or C++.

  • Vyper: Also for Ethereum, simpler and more focused on safety, but with fewer features.

  • Rust: Used for newer blockchains like Solana and NEAR. Known for speed and safety.

  • Move: Used on Aptos and Sui blockchains, designed for handling digital assets safely.

🛡️ Common security issues

Let's take a look at some common security issues developers and managers should be concerned about. You do not need to fully understand these at this point, as we will be looking closer at these in future lessons:

  • Reentrancy attacks: An attacker tricks a contract into calling them back before it finishes, so they can repeat actions and steal tokens. This works because the contract hasn't updated its records yet, so it thinks the attacker still has funds to withdraw.

  • Integer overflows/underflows: Numbers go above or below their allowed range, causing errors. New versions of Solidity protect against this. When this happens, a huge number might suddenly become zero, or a small balance might become massive.

  • Unchecked external calls: If a contract calls another contract and doesn't check if it worked, things can go wrong. The calling contract continues executing as if everything worked, even when the other contract failed or rejected the call.

  • Front-running: Attackers see pending transactions and rush to act first by paying higher fees. They do this to profit from knowing what's about to happen - like buying a token right before a big purchase drives up the price.

  • Denial of Service (DoS): Making a contract unusable by using up all the gas or breaking key parts. Attackers force the contract to run out of gas or fail every time someone tries to use it.

  • Missing access controls: Letting anyone call sensitive functions if rules aren't set up correctly. Without proper checks, strangers can withdraw funds, change settings, or perform admin actions they shouldn't have access to.

  • Timestamp manipulation: Miners can slightly change block timestamps, so they should not be used for important timing. This lets miners influence time-sensitive functions like lottery drawings or auction endings in their favor.

  • Delegatecall issues: Running code from another contract can have unexpected side effects. The external code runs with full access to your contract's storage and can modify or delete your data.

  • Storage collisions in proxies: Upgradable contracts must be designed carefully to avoid overwriting stored data. New contract versions might accidentally use the same storage slots as old data, corrupting important information.

  • Lack of input validation: Not checking user input can let bad data break the contract. Malicious users can send extreme values, empty data, or unexpected formats that cause the contract to behave incorrectly.

⚠️ Limitations of smart contracts

The advantages and benefits of smart contracts are continuously growing. However, there are some limitations to be aware of:

  • No outside data without oracles: Smart contracts can’t see real-world information (like prices or weather) without special third-party services called oracles.

  • Gas and storage limits: Contracts can’t do very large or complex tasks because everything costs gas.

  • Hard to upgrade or fix bugs: Most contracts can’t be changed after being added to the blockchain. Upgradeable contracts are possible, but more complex and risky.

  • Legal uncertainty: What happens in the contract always follows the code, but real-world legal systems may not always recognize it.

❓ FAQ: Common Questions Answered

Q: Are smart contracts a type of cryptocurrency?

No, they're not a currency. Think of a smart contract as the "app" that runs on a blockchain, while a cryptocurrency (like ETH or SOL) is the "money" used to pay for the actions the app performs. The smart contract defines the rules for how the money is spent or sent, but it is not the money itself.

Q: Since smart contracts are just code, what's an easy-to-understand real-world example of how I might use one?

Imagine you're buying a ticket to a concert. A smart contract could be used to sell that ticket directly from the artist to you. The code would automatically check that you paid the right amount, and then instantly send the unique ticket (as an NFT) to your digital wallet. The contract could also automatically send a small royalty payment to the artist and the venue every time the ticket is resold on a secondary market, all without any middleman.

Q: The article mentions many security issues. Does this mean smart contracts are not safe?

Smart contracts are only as safe as the code they are written in. The security issues listed are common vulnerabilities that developers are well aware of and actively work to prevent. Audits by security firms such as Cyfrin are a standard practice in the industry to find and fix bugs before a contract goes live. However, because they are immutable, a single mistake can be permanent, so it's a field with high stakes. On the plus side, immutability and transparency of the blockchain can also make them more secure than traditional systems, since the rules cannot be changed after the fact.

Q: How are smart contracts different from a regular app on my phone?

A regular app on your phone runs on a company's centralized server. The company controls the data, can change the rules at any time, and can even shut the app down. A smart contract, however, runs on a decentralized network of thousands of computers. No single company or person can control it, the code is public and transparent for anyone to see, and it can't be turned off as long as the blockchain is running.

📢 Key Takeaways

  • Self-Executing Code: A smart contract is a computer program on a blockchain that automatically executes agreements without needing a middleman.

  • Trustless and Immutable: Unlike traditional paper contracts, smart contracts are enforced by code, not people. Once deployed, their rules are transparent and cannot be changed, ensuring all parties can trust the outcome.

  • Powered by Gas: Every action a smart contract takes requires a small fee (gas) to run, which prevents the network from being overloaded.

  • A Building Block for Web3: Smart contracts are the foundation of dApps, powering key sectors like DeFi, NFTs, and DAOs.

  • Security is Key: While smart contracts offer new benefits, developers must be extremely careful to write secure code, as bugs and vulnerabilities cannot be easily fixed once deployed.

🏆 Complete the Lesson

You’ve taken another step towards becoming fluent in Web3. Now, let’s lock in that knowledge. Test your understanding and see how much you've learned.

Take the Quiz!

Powered by wisp

#blockchain-concepts
Loading...
Related Posts
Blockchain Basics: Essential Concepts of Web3

Blockchain Basics: Essential Concepts of Web3

Beginner's guide to blockchain technology explained simply. Learn Bitcoin, Ethereum basics, decentralization, and cryptocurrency fundamentals step-by-step.

Read Full Story
Consensus Algorithms: How Blockchains Reach Agreement

Consensus Algorithms: How Blockchains Reach Agreement

This article provides a foundational overview of blockchain consensus algorithms, explaining how decentralized networks agree on a shared history without a central authority. It breaks down the two essential components of consensus—Sybil resistance mechanisms and chain selection rules—using real-world examples from Bitcoin, Ethereum, and Solana. Readers will learn how different blockchains prevent manipulation, finalize transaction history, and maintain security at scale.

Read Full Story
Describing Smart Contract Functionality

Describing Smart Contract Functionality

Learn to describe smart contract functionality using passive voice and relative clauses. Includes a bonus allocation example, grammar tips, code walkthroughs, and a quiz to test your skills.

Read Full Story
Types of Blockchains: Public, Private & Consortium

Types of Blockchains: Public, Private & Consortium

Learn the key differences between public, private, and consortium blockchains. This guide explains access, governance, transparency, consensus models, and real-world use cases. Perfect for developers and professionals entering Web3.

Read Full Story
© fluentDev 2025