DApp Design PatternsEmerging best practices in
the world of Decentralized Applications
Joris Bontje @mids106
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
A design pattern is not a finished design that can be transformed directly into source or machine code.
It is a description or template for how to solve a problem that can be used in many different situations.
identity gateway
data feed
multisigescrow
event log
external control
voter
share holder
asset token
notary
arbitrator
deposit/slasher
PRNG
exchange
fan in/out
blocktime
oracle
CQRS
incentivized trigger
garbage collector
mortal
name registry
DOUG
alarm
timebomb
weak-hands
Name Single word or short phrase that refers to the pattern.
Problem Definition of a problem, including its intent or a desired outcome, and symptoms that would indicate that this problem exists.
Context Preconditions which must exist in order for that problem to occur; this is often a situation. When forces conflict, the resolutions of those conflicts is often implied by the context.
Forces Description of forces or constraints and how they interact. Some of the forces may be contradictory. For example: being thorough often conflicts with time or money constraints.
Solution Instructions, possibly including variants. The solution may include pictures, diagrams, code.
Examples Sample applications and solutions, analogies, visual examples, and known uses can be especially helpful, help user understand the context.
Related Patterns Differences and relationships with other patterns.
Data Patterns
Name Identity Gateway
Problem Need to verify identity of an public key (address) from a third party source.
Context Needed where there is an outside world interaction, possibly an arbitrator or regulatory authority or simply verifying a correspondence between two discrete pieces of data (i.e. a public key and correct mailing address).
Forces Privacy / anonymity is a contradiction with this. There might be legal limitation of personal identifiable information. The notary itself needs to be trusted.
Solution Third party smart contract controlled by a single party that maintains key value store of the outside world data associated with a particular public key. The smart contract is queried and returns an associated piece of data.
Examples Link between a LinkedIn identity (verified via OAuth login to the TTP) and the public key of the user. This is used to verify that the user is a real person with an associated business record and authorize them to some action in the original smart contract.
Related Patterns Data Feed, Notary
Name Name Registry
Problem Need to refer to contract or address in a human readable form; typically exposed to the user interface or part of a cluster of contracts.
Context Optionally the reference needs to be updatable. The referring account/contract might not exist in advance. Registries could be nested, creating support for “subdomains”.
Forces Since names should be unique there is the potential for name squatting. There could be clutter due to expiring references and associated keys getting lost.
Solution A (global) registry containing name -> address associations. Reverse lookups could be possible, as are numerous variants of registry rules.
Examples NameReg reference implementation for a simple global name registar. Ethereum clients have build-in support for this construct, while the register itself is configurable.
Related Patterns DOUG
https://github.com/ethereum/dapp-bin/blob/master/namereg/namereg.sol
Name Data Feed
Problem Need to act on state information of the outside world. For example the weather, currency exchange rates, soccer matches, etc.
Context The required data is from outside of the blockchain. Contracts in EVM can’t connect to the outside (for example a webservice) by themselves.
Forces The requested data might be generally useful or very specific; depending on this the content can be provided push or pull based.
Solution An automated process submits entires, which are stored (possibly including timestamp) in the contract storage; after which other contracts can access the data. Could be free service, or the data feed charges a fee for each consumption.
Examples Weather information in a certain area. USD/ETH exchange rate. Bitcoin blocks & transactions (btcrelay).
Related Patterns Oracle
https://github.com/SilentCicero/meteor-dapp-pricefeed/blob/master/pricefeed.sol
Transaction & ValuePatterns
Name Asset Token (aka Subcurrency)
Problem Need to have a virtual or physical asset represented on the blockchain, in order to be transferred, tracked, traded, etc
Context The assets are typically enumerable and equal in kind. Standardised interface allows for tracking in generic wallets and exchange on markets.
Forces The asset tokens will typically be the authoritative source for the underlying assets. Otherwise a data feed might be more appropriate.
Solution Contract tracking the number of owned assets per user account. The assets can be transferred between accounts and the balance can be requested.
Examples Crowdfunding tokens, IOUs, fiat currency assets, gold certificates (digix).
Related Patterns Market, Share Holder
https://github.com/slockit/smart-contract/blob/master/SlockCrowdfunding.sol
Name Exchange (aka Market)
Problem Need to exchange one asset token for another, or for the native Ether currency directly.
Context Both assets exist as contract on the blockchain and typically have the same interface.
Forces Order settlement can be done automatically (potentially expensive) or trailerable from the outside.
Solution Contract that tracks bids (buy) and asks (sell) orders. Orders can be matched upon which the ownership of assets are exchanged.
Examples Cyberdyne market (frequent batch auction), EtherEx (continuous double auction)
Related Patterns Asset Token
https://github.com/ethereum/serpent/blob/develop/examples/cyberdyne/market.se
Action & ControlPatterns
Name Event Log
Problem Need to track state or performed action with metadata.
Context Typically there is the need to display events in a user interface or have outside systems act upon them. Events might be indexed on certain topics (user account, location, etc) and are typically cheaper than using storage state.
Forces The EVM doesn’t allow contracts to query or inspect the event log of other contracts.
Solution Emit an event when a contract performs an action. User interfaces will watch these events and update their views accordingly.
Examples Orders placed, door open/closed, account registered.
Related Patterns CQRS
https://github.com/WeiFund/WeiFund/blob/master/contracts/WeiFund.sol
Name Incentivized Trigger
Problem A contract needs to have an action happening asynchronously from regular user interaction. For example clean up of expired records, making dividend payouts, etc.
Context Usually there is some aspect of time involved, after which an action should happen. Users don’t have a direct benefit from calling this action and/or the execution is expensive (gas wise).
Forces An outside agent is required to trigger the action; there is no guarantee of execution.
Solution Reward the caller of a contract action for triggering the execution, for example by sending them a percentage of payout or reimburse the (gas) execution cost.
Examples Casino games such lottery tickets where payouts happen after a certain time. Rewarding users from raising awareness of spammers or other kinds of business rule violations.
Related Patterns Alarm, Garbage Collector, Timebomb
https://github.com/ethereum/dapp-bin/blob/master/gavmble/gavmble.sol
Use Cases
DApps that interact with complex web applications
name registry
datafeed
event log
(CQRS)
asset token
exchange
incentivized trigger
DApps that utilize marketplace dynamics to make decisions
DApps that interactwith hardware
notary
oracle / data feed
event log
What’s next?