Back

How Smart Contracts Work

Smart Contracts Part 2: A look at how these self-executing contracts are coded, deployed, and automated on the blockchain.

Written By
Kevin Ciantar

Kevin Ciantar

CFO - Pyaza

Blockchain

Introduction

In the previous article we introduced you to Smart contracts. Now, we're going to dive into the nuts and bolts of smart contracts. Our mission? To understand the mechanics behind these self-executing agreements and how they operate on blockchain networks. 

The Technology Behind Smart Contracts

At their core, smart contracts are programs stored on a blockchain. But what does that really mean? Let's break it down:

  1. Blockchain Foundation: Smart contracts operate on blockchain platforms, with Ethereum being the most popular. These platforms provide the decentralized, secure environment necessary for smart contracts to function.

  2. Programming Languages: Smart contracts are written in specific programming languages. For Ethereum, it's Solidity, a language designed specifically for creating smart contracts.

  3. Deterministic Execution: Once deployed, smart contracts execute in a deterministic way. This means given the same input, they will always produce the same output, regardless of where or when they're run.

  4. Decentralized Storage: The code of a smart contract is stored across all nodes in the blockchain network, ensuring its integrity and availability.

  5. Cryptographic Security: Smart contracts leverage the blockchain's cryptographic security to ensure that transactions are secure and tamper-proof.

By integrating these elements, smart contracts serve as self-executing agreements that automatically enforce and execute terms without the need for intermediaries. Operating within a decentralized and secure blockchain environment, they offer a reliable, transparent, and tamper-proof way to conduct transactions and agreements. 

Components of a Smart Contract

Now, let's dissect a smart contract and look at its key components:

Contract Code

The contract code is the heart of a smart contract. It's a set of instructions written in a blockchain-specific programming language (like Solidity for Ethereum). This code defines:

  • The rules and conditions of the contract

  • The actions to be taken when certain conditions are met

  • The data to be stored and manipulated

For example, a simple escrow smart contract might have code that says: "If buyer confirms receipt of goods, release payment to seller. If not confirmed within 30 days, return payment to buyer."

Address on the Blockchain

When a smart contract is deployed to a blockchain, it's assigned a unique address. This address is like the contract's home on the blockchain. It's where users can interact with the contract, where the contract's code and data are stored, and where any transactions relating to the contract are directed.

Think of it as a unique ID for your smart contract, similar to a web address for a website.

State Variables

State variables are where a smart contract stores its data. These variables represent the current state of the contract and can include things like account balances, user information, and contract status (e.g., active, completed, terminated).

Every time the smart contract executes, these state variables can be updated. It's like the smart contract's memory, keeping track of all important information as it goes about its business.

Lifecycle of a Smart Contract

Smart contracts have a lifecycle that takes them from creation to execution. Let's walk through each stage:

Development

This is where it all begins. A developer writes the smart contract code, defining its rules, conditions, and actions. This stage involves:

  1. Planning: Determining what the contract needs to do

  2. Coding: Writing the actual code in a language like Solidity

  3. Testing: Rigorously testing the contract to ensure it behaves as expected

It's crucial to get this stage right because once deployed, changing a smart contract can be difficult or impossible.

Deployment

Once the smart contract is developed and tested, it's time to deploy it to the blockchain. This process involves:

  1. Compiling the code into bytecode that the blockchain can understand

  2. Sending a special transaction to the blockchain that includes this bytecode

  3. Paying a fee (in cryptocurrency) to have the contract added to the blockchain

After deployment, the contract is assigned its unique address on the blockchain.

Execution

Now the smart contract is live and ready for action. It can be triggered either by transactions sent to its address, or by other smart contracts calling its functions. Some smart contracts are also triggered when they reach a specific block or time on the blockchain

When triggered, the contract executes its code, potentially updating its state, transferring assets, or interacting with other contracts.

Termination (if applicable)

Some smart contracts have a built-in expiration or self-destruct function. When certain conditions are met, the contract can terminate itself, often returning any remaining funds to a designated address.

However, it's important to note that even a terminated contract's transaction history remains on the blockchain forever, maintaining a complete record of its activities.

How Smart Contracts Execute Transactions

The execution of smart contracts is where the magic really happens. Let's break down this process:

Trigger Conditions

Smart contracts don't just run continuously. They need to be triggered. This can happen in several ways:

  1. A user (via their wallet) sends a transaction to the contract's address.

  2. Another smart contract calls a function in this contract.

  3. Some blockchains allow contracts to execute when certain Time-Based triggers happen. Now we should clarify that most blockchains don't use actual clock time due to potential synchronization issues across a decentralized network. Instead, they often use block numbers as a proxy for time. Since blocks are typically produced at regular intervals, contract developers can estimate when certain conditions will be met. These types of time-based triggers are used for scheduled payments, token vesting (gradually releasing tokens over time), or for changing contract parameters at predetermined intervals, for example.

Automated Enforcement

Once triggered, the smart contract automatically enforces its rules. This is where its ‘smart’ nature shines.

The contract first runs through its code based on the trigger and checks if all necessary conditions are met. If conditions are met, it performs the specified actions.

Let's say we have a crowdfunding contract. When it's triggered by a donation, it might check if the funding goal has been reached. If so, it could automatically transfer the funds to the project creator. If not, it holds onto the funds.

Consensus Mechanism

Here's where the blockchain's decentralized nature comes into play. The execution of a smart contract isn't verified by just one computer, but by many nodes in the network:

The transaction triggering the contract is broadcast to all nodes (this is known as propagation). Each node independently executes the contract based on this transaction. Once consensus is reached, ie, the network reaches agreement on the outcome of the execution, the changes are added to the blockchain.

This consensus process ensures that everyone agrees on what the smart contract did, maintaining the integrity and trustworthiness of the system.

Fees and Costs

Running smart contracts isn't free. In the Ethereum network (and many others), the cost of executing a smart contract is measured in "gas". But what exactly is gas?

Gas is a unit that measures the computational effort required to execute operations on the blockchain. Every operation in a smart contract costs a certain amount of gas. The more complex the operation, the more gas it requires.

Users pay for this gas in the blockchain's native cryptocurrency (like Ether for Ethereum). The gas price fluctuates based on network demand. Users can set how much they're willing to pay per unit of gas, with higher prices typically resulting in faster execution.

For example, if a simple transaction costs 21,000 gas, and the gas price is 20 Gwei (0.00000002 Ether), the transaction would cost 0.00042 Ether.

Factors Affecting Costs

Several factors can influence the cost of executing a smart contract:

  1. Complexity of the Contract: More complex operations require more gas.

  2. Network Congestion: When the network is busy, gas prices typically increase.

  3. Storage Requirements: Operations that store data on the blockchain are generally more expensive.

  4. Optimization of Code: Well-optimized code can significantly reduce gas costs.

Understanding these costs is crucial for developers and users alike. High fees can make some applications impractical, driving the need for more efficient smart contract design and alternative blockchain solutions.

Security Considerations

While smart contracts offer many advantages, they also come with unique security challenges. One of the main challenges is code vulnerabilities. After all, smart contracts can only be as secure as their code. 

These vulnerabilities can lead to unexpected behavior or even loss of funds. The infamous DAO hack in 2016, which resulted in the loss of millions of dollars worth of Ether, was due to a reentrancy vulnerability (that’s where a contract is interrupted during execution and called again before the first execution is completed).

Given the potential risks, smart contract audits are crucial. These audits involve:

  1. Code Review: Expert developers scrutinize the code for potential vulnerabilities.

  2. Automated Testing: Using tools to simulate various scenarios and attack vectors.

  3. Formal Verification: Mathematical approach to prove the correctness of the contract.

Many projects now make their audit reports public to build trust with users. However, even audited contracts can have undiscovered vulnerabilities, so caution is always advised.

Immutable Code Risks

One of the key features of smart contracts is their immutability, which can also be a double-edged sword. Once deployed, code cannot be changed easily. This means

  1. Bugs are Permanent: Any bugs in the code remain there unless there's a specific upgrade mechanism built in.

  2. Difficult Upgrades: Upgrading smart contracts often involves complex processes and potential security risks.

  3. Inflexibility: The contract may not be able to adapt to unforeseen circumstances or changes in requirements.

This immutability underscores the importance of thorough testing and careful design before deployment. 

Conclusion

As we've peeled back the layers of smart contracts, we've seen a blend of elegant simplicity and mind-bending complexity. But, understanding how smart contracts work is just the beginning. The real excitement lies in imagining how they could be applied to solve real-world problems. 

What new possibilities could smart contracts unlock in your field?