smart contractsblockchainethereum

Smart Contracts Are Stored Procedures

by Steve Marx on

You may have heard the term “smart contracts” before, particularly if you’ve read about the Ethereum blockchain. The term is quite a misnomer. (Try searching for “smart contracts are neither” in your favorite search engine.) Vitalik Buterin, the inventor of Ethereum, regrets the term.1

I find smart contracts incredibly cool. My last job was conducting security audits of smart contracts.2 Before that, I co-authored a blog about them called Program the Blockchain, and I built a security capture the flag game called Capture the Ether.

You should think smart contracts are cool too. And what could be cooler than stored procedures?

First, what’s a blockchain?

I’m not going to try to explain how a blockchain works. There’s no point, because Grant Sanderson of 3Blue1Brown nails it in the video below. When I share a video that’s almost 30 minutes long, I usually equivocate a bit, but I’ll say without qualification that you should watch this video:

You’re welcome.

A blockchain is a database

A blockchain can be described in many ways, but from a functional perspective, I think it’s best thought of as a distributed, history-preserving3 database4. The magic of the blockchain (as explained in the video above—you did watch it, right?) is that it makes it possible for the whole world to agree on the state of that database.

In the most popular use, the blockchain state we’re all agreeing on is everyone’s account balances, which result from a bunch of transactions. This use case, known as a cryptocurrency, is an important enabling technology in its own right.

But it’s small potatoes.

Smart contracts are stored procedures

If the blockchain is a database, then smart contracts are the stored procedures.

In Ethereum, a simple transfer of ether (Ethereum’s native cryptocurrency) looks something like this5:

from:   Alice
to:     Bob
amount: 1 ether
data:   "Thanks for feeding my cat while I was on vacation."

This transaction describes a very simple state transformation. Alice’s balance is decreased by 1 ether, and Bob’s balance is increased by the same amount. But what about the data field? Without the involvement of smart contracts, that data is just permanently stored as part of the transaction. Future historians will never have to wonder why Alice paid Bob 1 ether.

Ethereum has a special kind of transaction, which is sent to no one:

from:   Alice
to:     null    # !!
amount: 0 ether
data:   ...     # bytecode

Such a transaction is used to create a smart contract. A smart contract is an account, just like Alice’s account or Bob’s account. The only difference is that it has a piece of code associated with it. That code is executed automatically if somebody sends a transaction to the smart contract account. Hence the term “stored procedure”.

Ethereum smart contracts have their own ether balance like any other account, and they also have storage, which they can use to persist state between code invocations. When invoked, they can manipulate storage and interact with other accounts (including other smart contracts) by sending their own transactions.

A simple example

That explanation was a bit abstract. Let me show you a real, working example written in Solidity, Ethereum’s primary smart contract language. The following smart contract splits incoming ether evenly between two parties6:

pragma solidity 0.7.0;

contract SplitterBot3000 {
    address payable immutable alice;
    address payable immutable bob;
    
    constructor(address payable _alice, address payable _bob) {
        alice = _alice;
        bob = _bob;
    }
    
    receive() payable external {
        bool success;
        bytes memory returnData;

        (success, returnData) = alice.call{value: msg.value / 2}("");
        require(success, "Transfer to alice failed.");

        (success, returnData) = bob.call{value: msg.value / 2}("");
        require(success, "Transfer to bob failed.");
    }
}

Using this smart contract is as simple as sending a transaction to it:

from:   Charlie
to:     SplitterBot3000
amount: 2 ether
data:   ""

Assuming Alice and Bob are regular (non-smart-contract) accounts, this transaction results in Charlie’s balance being decreased by 2 ether, and Alice and Bob’s accounts each being increased by 1 ether.

If Alice and/or Bob are smart contracts, then all sorts of things could have happened! Stored procedures can have cascading effects, after all.

Okay, but why?

It’s possible that I’ve succeeded in giving you a good mental model for what a smart contract is. But you may not be convinced that smart contracts are cool. This is because the example I used is quite boring.

Let’s think about something considerably more exciting: gambling. Imagine that you and I want to bet $1 on the outcome of a coin flip. How can we do this in a way that’s fair to both of us? Here’s my proposal:

  1. Send me $1.
  2. I’ll flip a coin.
  3. If it comes up “tails”, I’ll send you $2.

Sound good?

If that doesn’t sound fair to you, it’s because you don’t trust me. This is wise. But you can trust a stored procedure smart contract. Over on Program the Blockchain, I wrote a blog post called Flipping a Coin in Ethereum, which shows how we can gamble over the internet in a perfectly safe and fair way.

More use cases

Maybe gambling isn’t your thing. How about shopping? Using a smart contract, digital goods can be sold in such a way that the buyer and seller don’t have to trust each other at all. (If and only if the digital goods are delivered, the payment is delivered too.)

How about voting? A trivial version is the ubiquitous “multisignature wallet” contract. See Writing a Trivial Multisig Wallet for an example. But much more sophisticated voting and governance schemes are regularly being invented on Ethereum.

How about prediction markets? Insurance? Crowdfunding? Auctions? Peer-to-peer lending? A lot of the easiest use cases center around digital assets, but people are tracking ownership and selling physical objects like houses with smart contracts too.

Resources

If this piqued your curiosity about smart contracts, I have a few recommendations for where you can learn more:

  • The first post on Program the Blockchain, What Is a Smart Contract?, explains smart contracts in a more technical way.
  • If you’re interested in learning to write smart contracts, the rest of Program the Blockchain are great! (Nobody ever accused me of modesty.)
  • The original Ethereum whitepaper explains the blockchain as a series of state transitions. It also provides the motivation for smart contracts.

And of course, stay tuned to this blog, where I will undoubtedly write more about smart contracts. I would love it if you would subscribe to my newsletter.


  1. But note that he didn’t originate the term. That honor goes to Nick Szabo, whose ideas led directly to Bitcoin. ↩︎

  2. By the way, my old team is hiring! If you’re interested in doing smart contract security work, reach out to them, and tell them I sent you! ↩︎

  3. You may prefer “immutable”, especially if you’re used to immutable data structures. But I think that terminology confuses a lot of people. Obviously the blockchain is mutable. Otherwise you couldn’t transfer cryptocurrency. ↩︎

  4. You may also prefer the term “ledger” to database. This is okay, but particularly when discussing smart contracts, it fails to capture the expressiveness. ↩︎

  5. This is an oversimplification, but not that big of one. Read How Ethereum Transactions Work for a more detailed treatment. ↩︎

  6. There’s an Office Space / Superman III opportunity here! What if an odd amount of ether is sent? There will be a tiny remainder, but those remainders might add up, right? Two problems: 1) There’s no way to get those scraps out of the smart contract because it has no code to send it. 2) The maximum remainder for each transaction is 1 wei, which is 1/1018 of an ether. At today’s ether prices, it would take on the order of ten quadrillion odd-valued transactions before you made your first dollar. ↩︎

Me. In your inbox?

Admit it. You're intrigued.

Subscribe

Related posts