Blockchain Design Patterns

Programming robust smart contracts in Solidity is a sophisticated task beause the special features of the language and how to smart contracts work.

These are some of the characteristics we should take in count when coding a smart contract:

  • Code and data are public.

  • Once deployed, code cannot change.

  • Writing costs gas.

  • Reading is free.

  • Returning variable-lengh arrays is not allowed.

  • Keys for maps are not stored.

Control Patterns

Guard Check

The desired behavior of a smart contract would be to check for all required circumstances and only proceed if everything is as intended. In case of any shortcomings, the contract is expected to revert all changes that have been made to its state.

State Machine

Enable a contract to go through different stages with different corresponding functionality exposed.

Oracle

Gain access to data stored outside of the blockchain.

Randomness

Randomness in computer systems and especially in Ethereum is notoriously difficult to achieve. While it is hard or even impossible to generate a truly random number via software, the need for randomness in Ethereum is high

Security Patterns

Access Restriction

Not all the functionality of a smart contract should be available for everyone, it should be restricted according to suitable criteria.

Multi Authorization

Sometimes in blockchain-based applications, activities might need to be authorised by multiple blockchain addresses.

Off-Chain Secret Enabled Dynamic Authorisation

In blockchain-based applications, the party(ies) that can authorise a given activity may be unknown when the corresponding smart contract is deployed or the corresponding transaction is submitted to the blockchain.

Ownership & Role Based Access Control

A deployed contract can have dedicated role-based operation & access, like in any traditional system. The roles allocation and administration can be done by enforcing ownership & role based access control rules.

The standard implementation for this pattern is available in the OpenZeppelin library.

Upgradeability Patterns

Proxy Delegate

Eternal Storage

Optimization Patterns

String Equality Comparison

Tight Variable Packing

Memory Array Building

\

⭐️ Extras

Interact with the outside world patterns

A set of patterns for interacting with offchain data.

Last updated