Beyond Bitcoin: Smart Contracts

Chapter 15:

Previous: Beyond Bitcoin: Proof of Stake

Next: Coding a smart contract

A smart contract is a computer program. A computer program can do something simple like add two numbers together, then take action based on the result or do something more complex like run an organization, hold the terms of a wager, manage a video game economy, or perhaps an international bank. The more complex the task, the more likely multiple smart contracts will be involved. As you might expect, smart contracts that are stored and run on a blockchain also have the facility to program the tokens of that blockchain.

Code is law

All the cryptographic guarantees of ownership still exist, however. For example, you couldn’t program a smart contract for Ethereum that arbitrarily moves someone’s ETH unless you stole the private key somehow. However, you could write a smart contract that allows someone to opt-in to give the power to do things with their tokens while they still maintain ownership.

It is essential to know that when you interact with a smart contract, you will be charged a fee through your wallet, which is connected to the smart contract. This fee is called a gas fee, and it goes to the validators and the stakers to reward them for their effort, capital costs, and risks. A gas fee varies enormously based on the computing power (CPU cycles) required to execute the chosen smart contract, the blockchain the smart contract is on, and the current congestion of the computing power on a given blockchain. Expect to pay between a tiny fraction of a cent and hundreds of dollars for a single transaction. As we progress, we will see how to know what a gas fee will be before you commit to using a smart contract so there are no nasty surprises.

Let’s look at some hypothetical smart contract examples to try and comprehend how powerful an idea this is.

  1. You can code a smart contract that allows people to deposit 0.1 ETH to a smart contract wallet that will store the ETH until ten people have each deposited 0.1 ETH, or perhaps an unlimited number of depositors and a cut-off date. The smart contract could then randomly pick one of the depositors and pay out all the ETH to one lucky winner, simulating the functionality of a lottery.
  2. You could write a smart contract allowing people to interact with their crypto wallets and swap one type of token for another at a pre-agreed price—decentralizing crypto exchanges.
  3. You could write a smart contract that creates (mints) a custom token that represents a digital product. Perhaps an image, video game accessory (character, sword, playable level, or entire game), music file, or a movie. The user would then own this token to use, share or sell without the creator’s influence. Once the token is in the user’s wallet, they effectively own it, as it cannot be removed without their private key signing a transaction. They could then transfer it peer to peer or interact with another smart contract, perhaps to sell the image, music, or video, or maybe to equip a new set of armor to a video game character that they also have in their wallet or send to a friend because they have a duplicate.
  4. Users could interact with a smart contract they trust and lend tokens in return for an interest payment. After depositing some security, these lent tokens could then be borrowed by another user in return for paying interest.
  5. A smart contract could be programmed to receive election or sports results and to pay out agreed amounts to wallets that placed a bet on an outcome.

There isn’t any limit but the imagination and waiting for the supporting infrastructure. In case you’re wondering, all the above examples have already been built. In the future, you should expect smart contract-controlled Internet and phone services, traffic management, legal services, insurance, and tokenizing real-world assets like property deeds and marriage certificates.

At the time of editing (25th February 2023), the German corporate giant Siemens has just announced a bond issuance on the Polygon blockchain.

A sample smart contract

If you are a coder, you might like to see some samples. I generated this code using ChatGPT, I haven’t tested it, but it looks syntactically correct to me, an amateur programmer. There is no requirement to understand this code to continue with the book; I just thought it would be interesting to show exactly what the code running inside the Ethereum Virtual Machine or EVM looks like because we will discuss Ethereum in the next chapter. Other blockchains use different programming languages; this language is called Solidity.

pragma solidity ^0.8.0;

contract Lottery {

    address payable[] public players;

    address payable winner;

    uint public playerCount;

    uint public ticketPrice;

    bool public lotteryOpen;

    bool public lotteryClosed;

    constructor() public {

        ticketPrice = 10000000000000000; // 0.1 ETH

        lotteryOpen = true;


    function deposit() public payable {

        require(msg.value == ticketPrice, "Sorry, the ticket price is 0.1 ETH");

        require(lotteryOpen, "Sorry, the lottery is closed. Maybe next time!");

        require(playerCount < 10, "Sorry, the lottery is full. Better luck next time!");



        emit LotteryDeposit(msg.sender, msg.value);


    function closeLottery() public {

        require(msg.sender == msg.sender, "Sorry, only the contract owner can close the lottery.");

        require(lotteryOpen, "The lottery is already closed, no need to close it again!");

        lotteryOpen = false;

        lotteryClosed = true;

        emit LotteryClosed();


    function pickWinner() public {

        require(lotteryClosed, "The lottery is still open, cannot pick a winner yet.");

        uint randomIndex = uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty))) % playerCount;

        winner = players[randomIndex];

        winner.transfer(1 ether);

        emit WinnerPicked(winner, 1 ether);


    event LotteryDeposit(address player, uint value);

    event LotteryClosed();

    event WinnerPicked(address winner, uint prize);


This smart contract is a simple lottery that allows the first ten people to deposit 0.1 ETH, as in the 1st example from my list of possible smart contracts. Once the lottery is closed, the smart contract randomly picks a winner and transfers 1 ETH to the winner’s address. The contract also triggers events for lottery deposit, lottery closed, and the winner picked, so any external smart contract from another dApp can listen to these events.

The Lottery smart contract program is divided into functions. Functions are named sections of the code that can be called (executed) by other parts of the code. This is a common way to organize computer code. For example, the constructor function sets the lottery ticket price to 0.1 ETH and sets the lotteryOpen variable to true so players can deposit their hard-earned ETH. The deposit function allows players to deposit the price of the lottery ticket and adds the player to the players array, a particular variable that holds all the participants. It also emits the LotteryDeposit event. Finally, the closeLottery function allows the contract owner to close the lottery, and the pickWinner function allows the contract owner to pick the winner and transfer the prize.

This code is all it would take to implement a simple blockchain lottery. Imagine what you can achieve with thousands or millions of lines of code. Of course, the more extensive and computationally intensive the code, the more it costs the user to interact with the smart contract, especially on Ethereum. However, this interaction would cost mere cents or less on chains like Solana, Fantom, or Polygon.

Also, the contract uses a simple random number generator that uses the keccak256 hash of the timestamp and difficulty of the block the contract is called. Therefore, it’s not a cryptographically secure method for generating random numbers. When random numbers must be verifiably random smart contracts can use an oracle. We will discuss oracles soon.

How does a dApp use a smart contract?

Also, note that some way of interacting with this smart contract is required. This could be done through a simple web page using Javascript or a desktop or mobile application written in one of many languages using a standard RPC library to communicate with a node to run the smart contract.

RPC stands for remote procedure call, a protocol used for communication between two different processes running on separate systems over a network. RPC enables one process to communicate with a remote system. The critical point to make about RPC in this context is that RPC is a common standard, and it is simple for a modestly competent programmer to write a simple app or web page to interact with a smart contract via a node.

However, the vast range of utilities is not the most fascinating aspect of smart contracts.

Security of smart contracts

Smart contracts are immutable. This means they are on the blockchain and unalterable to the same extent as your funds are cryptographically secure. This means that some shady corporations cannot change the terms and conditions once you interact with a smart contract. Immutability also comes with problems if the smart contract has bugs or is malicious, and we will talk about this possibility many times as we progress through the book.

In the next chapter, we will actually code and deploy a smart contract albeit a bit simpler than this lottery example.

A malicious smart contract is possible because, just like anybody can get a wallet, anybody can also code and publish a smart contract. It is because of the decentralized, permissionless, censorship-resistant properties of most of these blockchain networks that nobody can be stopped from making available or interacting with a smart contract – within the rules defined by the smart contract.

Most smart contract blockchains are not secret. Therefore the code of a smart contract is public. Anybody can inspect the code, and the most trusted smart contracts have been thoroughly audited. Of course, audits don’t guarantee safety, but they are a good start. Unfortunately, the public nature of smart contracts also means that your activity is not necessarily private and raises the possibility, perhaps, the likelihood that interested parties, such as governments, can discover and even track your smart contract interactions. They might then try and use real-world means to “encourage” you not to interact with a particular smart contract, creating off-chain censorship.

For example, Tornado Cash is a collection of smart contracts (a dApp) built on the Ethereum blockchain. It is a dApp that allows users to make anonymous transactions by pooling their assets and using smart contracts to hide their wallet addresses.

The Office of Foreign Assets Control (OFAC), part of the US Treasury Department, added Tornado Cash to its international sanctions list. This meant that anyone interacting with Tornado Cash would be subject to penalties from OFAC. The situation brings into question the censorship resistance of smart contracts. To be clear, OFAC cannot take down the smart contracts. It can, however, threaten people with severe consequences if they interact with them.

These real-world tactics can also be used against validators who execute smart contracts on their nodes. This can lead to real, on-chain censorship and will likely be a fundamental standoff between projects and the authorities in the coming years.


We have learned about smart contracts, which facilitate decentralized, permissionless, unstoppable applications. When you code a smart contract, people can interact with it using code and a compatible wallet. Smart contracts can also interact and execute (call) each other. Of course, this differs from how most people will interact with smart contracts. Most are designed to be interacted with a UI, usually via a website, desktop, or mobile application. The smart contracts and the UI combination is a DApp or decentralized applications. DApps are what much of this book will be about – not the code itself.

Next, we will explore some of the most prominent, newest, most established, and most exciting blockchains; most use PoS consensus and are smart contract chains. It goes without saying, of course, that being the biggest, newest, most established, and most exciting does not mean the price will go up.

Previous: Beyond Bitcoin: Proof of Stake

Next: Coding a smart contract


Leave a Reply

Your email address will not be published. Required fields are marked *