Smart Contract Patterns
Disclaimer: This is a summary of patterns we have observed during our research and should not be considered any form of technical or investment advice. Also, the given “known examples” do not imply they are the best implementations of the said pattern or any superior to any other implementation of the pattern not listed.
Smart contracts are programs running on blockchains. Thus, some of the existing design patterns and programming principles for conventional software environments are also applicable to smart contracts. If a public blockchain is used, the structural design of the smart contract has a large impact on its execution cost. The cost of deploying a smart contract depends on the size of the smart contract(s) because the code is stored on the blockchain, resulting in a data storage fee that is proportional to the size of the smart contract. Thus, a structural design with more lines of compiled code costs more money. There is also a cost to execute a smart contract function, and it depends on the time, space, and message complexity. Time complexity typically reflects the complexity of the smart contract instructions and their combinations. Space complexity includes both memory and ledger storage consumption. Message complexity typically reflects the number of messages or volume of data in/out of a blockchain client. As a consortium blockchain does not necessarily have tokens/currency, the monetary cost of storing and executing smart contracts is typically not an issue. However, a smart contract’s (binary) code still need to fit into the limits of transaction and block sizes. Also, they increase the total size of the blockchain as more blocks are appended to it and no block can be detached from it. Further, every participant typically stores a full replica of the blockchain. Besides, different structural designs of smart contracts may affect performance because more or fewer transactions may be required. Moreover, time, space, and message complexity could reduce the throughput of a consortium blockchain. Following patterns present several ways we can structure smart contracts:
- Contract Registry – Maintain a registry mapping a smart contract name and the address of its latest version. Before invoking a smart contract, look up the registry to find its address
- Data Contract (aka Data Segregation) – Store data in a separate smart contract
- Diamond (aka Multi-Facet Proxy) – A smart contract is modularised into multiple logic contracts called facets. Users then interact with the proxy contract that relays all requests to the latest version of the respective facet contract.
- Factory Contract – Use an on-chain contract as a factory to spawn contract instances from a smart contract template
- Incentive Execution – Offer a reward to the caller of a contract function for invoking it
- Proxy (aka Contract Relay) – Users interact with the same proxy contract that relays all requests to the latest contract version